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 | 1510 | Solve the following coding problem using the programming language python:
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother.
As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b.
Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.
You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
-----Input-----
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 10^5). The second line will contain n space-separated integers representing content of the array a (1 ≤ a_{i} ≤ 10^9). The third line will contain m space-separated integers representing content of the array b (1 ≤ b_{i} ≤ 10^9).
-----Output-----
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
-----Examples-----
Input
2 2
2 3
3 5
Output
3
Input
3 2
1 2 3
3 4
Output
4
Input
3 2
4 5 6
1 2
Output
0
-----Note-----
In example 1, you can increase a_1 by 1 and decrease b_2 by 1 and then again decrease b_2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.
In example 3, you don't need to do any operation, Devu's condition is already satisfied.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Codeforces Round 251 Div 2 Problem D
Author : chaotic_iak
Language: Python 3.3.4
"""
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 [int(x) for x in inputs.split()]
def write(s="\n"):
if isinstance(s, list): s = " ".join(s)
s = str(s)
print(s, end="")
################################################### SOLUTION
n,m = read()
a = read()
b = read()
s = [(0,2)] + [(i,0) for i in a] + [(i,1) for i in b]
s.sort()
t = sum(b)
al = 0
br = m
mn = t
for i in range(1,n+m+1):
t += (al-br) * (s[i][0] - s[i-1][0])
mn = min(mn, t)
if s[i][1]:
br -= 1
else:
al += 1
print(mn)
``` | vfc_15794 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/439/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2\n2 3\n3 5\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n1 2 3\n3 4\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1511 | Solve the following coding problem using the programming language python:
The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.
At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.
The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.
-----Input-----
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Then follow n lines describing instructions. The i-th line contains m integers: x_{i}1, x_{i}2, ..., x_{im} (0 ≤ x_{ij} ≤ k), where x_{ij} is the instruction that must be executed by the i-th core at the j-th cycle. If x_{ij} equals 0, then the corresponding instruction is «do nothing». But if x_{ij} is a number from 1 to k, then the corresponding instruction is «write information to the memory cell number x_{ij}».
We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from 1 to k.
-----Output-----
Print n lines. In the i-th line print integer t_{i}. This number should be equal to 0 if the i-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked.
-----Examples-----
Input
4 3 5
1 0 0
1 0 2
2 3 1
3 2 0
Output
1
1
3
0
Input
3 2 2
1 2
1 2
2 2
Output
1
1
0
Input
1 1 1
0
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, m, k = list(map(int, input().split()))
deadstep = [0] * (n+1)
badmem = [False] * (k+1)
a = [0] * (n+1)
for i in range(1, n+1):
a[i] = [0] + list(map(int, input().split()))
for step in range(1, m+1):
t = [0] * (k+1)
for i in range(1, n+1):
if deadstep[i] == 0 and a[i][step] != 0:
t[a[i][step]] += 1
for j in range(1, k+1):
if t[j] > 1:
badmem[j] = True
for i in range(1, n+1):
if deadstep[i] == 0 and badmem[a[i][step]]:
deadstep[i] = step
for i in range(1, n+1):
print(deadstep[i])
``` | vfc_15798 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/411/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3 5\n1 0 0\n1 0 2\n2 3 1\n3 2 0\n",
"output": "1\n1\n3\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 2\n1 2\n1 2\n2 2\n",
"output": "1\n1\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n0\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1512 | Solve the following coding problem using the programming language python:
You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.
We remind that in a sequence of numbers a_1, a_2, ..., a_{k} the element a_{i} is a record if for every integer j (1 ≤ j < i) the following holds: a_{j} < a_{i}.
-----Input-----
The first line contains the only integer n (1 ≤ n ≤ 10^5) — the length of the permutation.
The second line contains n integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the permutation. All the integers are distinct.
-----Output-----
Print the only integer — the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.
-----Examples-----
Input
1
1
Output
1
Input
5
5 1 2 3 4
Output
5
-----Note-----
In the first example the only element can be removed.
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, stdout
n = int(stdin.readline().rstrip())
p = list(map(int,stdin.readline().rstrip().split()))
if n==1:
print(p[0])
else:
removeDict={i:0 for i in range(1,n+1)}
l1 = p[0]
removeDict[l1]-=1
l2 = 0
for i in range(1,n):
if p[i]>l2:
if p[i]>l1:
l2=l1
l1=p[i]
removeDict[l1]-=1
else:
l2=p[i]
removeDict[l1]+=1
maxN = 1
maxRemove=-10
for i in range(1,n+1):
if removeDict[i]>maxRemove:
maxN = i
maxRemove = removeDict[i]
print(maxN)
``` | vfc_15802 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/900/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n5 1 2 3 4\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n4 3 5 1 2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9\n9 5 8 6 3 2 4 1 7\n",
"output": "9\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1513 | Solve the following coding problem using the programming language python:
You have a long stick, consisting of $m$ segments enumerated from $1$ to $m$. Each segment is $1$ centimeter long. Sadly, some segments are broken and need to be repaired.
You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $t$ placed at some position $s$ will cover segments $s, s+1, \ldots, s+t-1$.
You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.
Time is money, so you want to cut at most $k$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?
-----Input-----
The first line contains three integers $n$, $m$ and $k$ ($1 \le n \le 10^5$, $n \le m \le 10^9$, $1 \le k \le n$) — the number of broken segments, the length of the stick and the maximum number of pieces you can use.
The second line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le m$) — the positions of the broken segments. These integers are given in increasing order, that is, $b_1 < b_2 < \ldots < b_n$.
-----Output-----
Print the minimum total length of the pieces.
-----Examples-----
Input
4 100 2
20 30 75 80
Output
17
Input
5 100 3
1 2 4 60 87
Output
6
-----Note-----
In the first example, you can use a piece of length $11$ to cover the broken segments $20$ and $30$, and another piece of length $6$ to cover $75$ and $80$, for a total length of $17$.
In the second example, you can use a piece of length $4$ to cover broken segments $1$, $2$ and $4$, and two pieces of length $1$ to cover broken segments $60$ and $87$.
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())
b=list(map(int,input().split()))
diffs=[]
for i in range(n-1):
diffs.append(b[i+1]-b[i])
diffs.sort()
print(k+sum(diffs[:n-k]))
``` | vfc_15806 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1110/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 100 2\n20 30 75 80\n",
"output": "17\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 100 3\n1 2 4 60 87\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1000000000 1\n228\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1514 | Solve the following coding problem using the programming language python:
A permutation of length $k$ is a sequence of $k$ integers from $1$ to $k$ containing each integer exactly once. For example, the sequence $[3, 1, 2]$ is a permutation of length $3$.
When Neko was five, he thought of an array $a$ of $n$ positive integers and a permutation $p$ of length $n - 1$. Then, he performed the following:
Constructed an array $b$ of length $n-1$, where $b_i = \min(a_i, a_{i+1})$. Constructed an array $c$ of length $n-1$, where $c_i = \max(a_i, a_{i+1})$. Constructed an array $b'$ of length $n-1$, where $b'_i = b_{p_i}$. Constructed an array $c'$ of length $n-1$, where $c'_i = c_{p_i}$.
For example, if the array $a$ was $[3, 4, 6, 5, 7]$ and permutation $p$ was $[2, 4, 1, 3]$, then Neko would have constructed the following arrays:
$b = [3, 4, 5, 5]$ $c = [4, 6, 6, 7]$ $b' = [4, 5, 3, 5]$ $c' = [6, 7, 4, 6]$
Then, he wrote two arrays $b'$ and $c'$ on a piece of paper and forgot about it. 14 years later, when he was cleaning up his room, he discovered this old piece of paper with two arrays $b'$ and $c'$ written on it. However he can't remember the array $a$ and permutation $p$ he used.
In case Neko made a mistake and there is no array $a$ and permutation $p$ resulting in such $b'$ and $c'$, print -1. Otherwise, help him recover any possible array $a$.
-----Input-----
The first line contains an integer $n$ ($2 \leq n \leq 10^5$) — the number of elements in array $a$.
The second line contains $n-1$ integers $b'_1, b'_2, \ldots, b'_{n-1}$ ($1 \leq b'_i \leq 10^9$).
The third line contains $n-1$ integers $c'_1, c'_2, \ldots, c'_{n-1}$ ($1 \leq c'_i \leq 10^9$).
-----Output-----
If Neko made a mistake and there is no array $a$ and a permutation $p$ leading to the $b'$ and $c'$, print -1. Otherwise, print $n$ positive integers $a_i$ ($1 \le a_i \le 10^9$), denoting the elements of the array $a$.
If there are multiple possible solutions, print any of them.
-----Examples-----
Input
5
4 5 3 5
6 7 4 6
Output
3 4 6 5 7
Input
3
2 4
3 2
Output
-1
Input
8
2 3 1 1 2 4 3
3 4 4 2 5 5 4
Output
3 4 5 2 1 4 3 2
-----Note-----
The first example is explained is the problem statement.
In the third example, for $a = [3, 4, 5, 2, 1, 4, 3, 2]$, a possible permutation $p$ is $[7, 1, 5, 4, 3, 2, 6]$. In that case, Neko would have constructed the following arrays:
$b = [3, 4, 2, 1, 1, 3, 2]$ $c = [4, 5, 5, 2, 4, 4, 3]$ $b' = [2, 3, 1, 1, 2, 4, 3]$ $c' = [3, 4, 4, 2, 5, 5, 4]$
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, Counter
N = int(input())
B = list(map(int, input().split()))
C = list(map(int, input().split()))
Edge = defaultdict(list)
Edc = defaultdict(int)
for b, c in zip(B, C):
if b > c:
print(-1)
return
Edge[b].append(c)
Edc[(b, c)] += 1
if b != c:
Edge[c].append(b)
Deg = Counter(B + C)
eul = 0
st = []
for k, v in list(Deg.items()):
if v % 2:
eul += 1
st.append(k)
s, e = B[0], B[0]
if eul and eul != 2:
print(-1)
return
if eul:
s, e = st[0], st[1]
ans = [s]
while True:
vn = ans[-1]
while True:
vf = Edge[vn][-1]
if Deg[vf] != 0 and Edc[(vn, vf) if vn < vf else (vf, vn)]:
break
Edge[vn].pop()
vf = Edge[vn].pop()
Deg[vn] -= 1
Deg[vf] -= 1
Edc[(vn, vf) if vn < vf else (vf, vn)] -= 1
ans.append(vf)
if not Deg[vf]:
break
loop = defaultdict(list)
for a in ans:
if Deg[a]:
loopa = [a]
while Deg[a]:
vn = loopa[-1]
while True:
vf = Edge[vn][-1]
if Deg[vf] != 0 and Edc[(vn, vf) if vn < vf else (vf, vn)]:
break
Edge[vn].pop()
vf = Edge[vn].pop()
Deg[vn] -= 1
Deg[vf] -= 1
Edc[(vn, vf) if vn < vf else (vf, vn)] -= 1
loopa.append(vf)
if not Deg[vf]:
break
loop[a] = loopa
Ans = []
for a in ans:
if loop[a]:
Ans.extend(loop[a])
loop[a] = []
else:
Ans.append(a)
if len(Ans) != N:
print(-1)
return
print(*Ans)
``` | vfc_15810 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1152/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n4 5 3 5\n6 7 4 6\n",
"output": "3 4 6 5 7 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 4\n3 2\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1515 | Solve the following coding problem using the programming language python:
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.
The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
-----Input-----
The single line contains integers p, x (1 ≤ p ≤ 10^6, 1 ≤ x ≤ 9).
-----Output-----
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
-----Examples-----
Input
6 5
Output
142857
Input
1 2
Output
Impossible
Input
6 4
Output
102564
-----Note-----
Sample 1: 142857·5 = 714285.
Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
p, k = map(int, input().split())
u = 10 * k - 1
v = pow(10, p - 1, u) - k
for y in range(k, 10):
if (y * v) % u == 0:
q = d = 9 * y
while q % u: q = 10 * q + d
q = str(q // u)
print(q * (p // len(q)))
break
else: print('Impossible')
``` | vfc_15814 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/394/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 5\n",
"output": "142857",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1516 | Solve the following coding problem using the programming language python:
This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $a_1, a_2, \dots, a_n$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.
A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.
Let's denote a function that alternates digits of two numbers $f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$, where $a_1 \dots a_p$ and $b_1 \dots b_q$ are digits of two integers written in the decimal notation without leading zeros.
In other words, the function $f(x, y)$ alternately shuffles the digits of the numbers $x$ and $y$ by writing them from the lowest digits to the older ones, starting with the number $y$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.
For example: $$f(1111, 2222) = 12121212$$ $$f(7777, 888) = 7787878$$ $$f(33, 44444) = 4443434$$ $$f(555, 6) = 5556$$ $$f(111, 2222) = 2121212$$
Formally, if $p \ge q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$; if $p < q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$.
Mishanya gives you an array consisting of $n$ integers $a_i$. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate $\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$ modulo $998\,244\,353$.
-----Input-----
The first line of the input contains a single integer $n$ ($1 \le n \le 100\,000$) — the number of elements in the array. The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the elements of the array. All numbers $a_1, a_2, \dots, a_n$ are of equal length (that is, they consist of the same number of digits).
-----Output-----
Print the answer modulo $998\,244\,353$.
-----Examples-----
Input
3
12 33 45
Output
26730
Input
2
123 456
Output
1115598
Input
1
1
Output
11
Input
5
1000000000 1000000000 1000000000 1000000000 1000000000
Output
265359409
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())
c = list(map(int,input().split()))
summ = 0
for i in range(a):
k = 0
k1 = 0
s = str(c[i])
for x in s:
k = k * 100 + int(x)
k1 = k * 10
summ += (k + k1) * a
summ %= 998244353
print(summ)
``` | vfc_15818 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1195/D1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n12 33 45\n",
"output": "26730",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n123 456\n",
"output": "1115598",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1517 | Solve the following coding problem using the programming language python:
Permutation p is an ordered set of integers p_1, p_2, ..., p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the length of permutation p_1, p_2, ..., p_{n}.
Petya decided to introduce the sum operation on the set of permutations of length n. Let's assume that we are given two permutations of length n: a_1, a_2, ..., a_{n} and b_1, b_2, ..., b_{n}. Petya calls the sum of permutations a and b such permutation c of length n, where c_{i} = ((a_{i} - 1 + b_{i} - 1) mod n) + 1 (1 ≤ i ≤ n).
Operation $x \text{mod} y$ means taking the remainder after dividing number x by number y.
Obviously, not for all permutations a and b exists permutation c that is sum of a and b. That's why Petya got sad and asked you to do the following: given n, count the number of such pairs of permutations a and b of length n, that exists permutation c that is sum of a and b. The pair of permutations x, y (x ≠ y) and the pair of permutations y, x are considered distinct pairs.
As the answer can be rather large, print the remainder after dividing it by 1000000007 (10^9 + 7).
-----Input-----
The single line contains integer n (1 ≤ n ≤ 16).
-----Output-----
In the single line print a single non-negative integer — the number of such pairs of permutations a and b, that exists permutation c that is sum of a and b, modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
3
Output
18
Input
5
Output
1800
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())
ans = [1, 3, 5, 7, 9, 11, 13, 15]
dct = \
{
1 : 1,
3 : 18,
5 : 1800,
7 : 670320,
9 : 734832000,
11 : 890786230,
13 : 695720788,
15 : 150347555
}
if n in ans:
print(dct[n])
else:
print(0)
``` | vfc_15822 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/285/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n",
"output": "18\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "1800\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "13\n",
"output": "695720788\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1518 | Solve the following coding problem using the programming language python:
You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):
choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number); swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmp = a[i], a[i] = a[j], a[j] = tmp (tmp is a temporary variable).
You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5). The next line contains n distinct integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ n).
-----Output-----
In the first line, print integer k (0 ≤ k ≤ 5n) — the number of used operations. Next, print the operations. Each operation must be printed as "i j" (1 ≤ i < j ≤ n; (j - i + 1) is a prime).
If there are multiple answers, you can print any of them.
-----Examples-----
Input
3
3 2 1
Output
1
1 3
Input
2
1 2
Output
0
Input
4
4 2 3 1
Output
3
2 4
1 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
import bisect
def gen_primes(upper_bound):
upper_bound += 1
t = [0] * (upper_bound)
primes = [2]
for i in range(3, upper_bound, 2):
if t[i]:
continue
primes.append(i)
for j in range(i + i, upper_bound, i):
t[j] = 1
return primes
def main():
n = int(input())
a = list(map(int, input().split()))
primes = gen_primes(n + 1)
process = list()
d = [0] * n
for i in range(n):
d[a[i] - 1] = i
i = 0
while i < n:
if a[i] == i + 1:
i += 1
continue
r = d[i]
l = r - primes[bisect.bisect(primes, r - i + 1) - 1] + 1
a[l], a[r] = a[r], a[l]
process.append('{} {}'.format(l + 1, r + 1))
d[a[l] - 1] = l
d[a[r] - 1] = r
print(len(process))
print('\n'.join(process))
def __starting_point():
main()
__starting_point()
``` | vfc_15826 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/432/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 2 1\n",
"output": "1\n1 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n4 2 3 1\n",
"output": "3\n2 4\n1 2\n2 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n10 9 8 7 6 5 4 3 2 1\n",
"output": "15\n4 10\n2 4\n1 2\n3 9\n2 3\n4 8\n3 4\n5 7\n4 5\n5 6\n6 7\n8 10\n7 8\n8 9\n9 10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n2 1 4 3 5\n",
"output": "2\n1 2\n3 4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1519 | Solve the following coding problem using the programming language python:
Vasya has recently got a job as a cashier at a local store. His day at work is $L$ minutes long. Vasya has already memorized $n$ regular customers, the $i$-th of which comes after $t_{i}$ minutes after the beginning of the day, and his service consumes $l_{i}$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer.
Vasya is a bit lazy, so he likes taking smoke breaks for $a$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day?
-----Input-----
The first line contains three integers $n$, $L$ and $a$ ($0 \le n \le 10^{5}$, $1 \le L \le 10^{9}$, $1 \le a \le L$).
The $i$-th of the next $n$ lines contains two integers $t_{i}$ and $l_{i}$ ($0 \le t_{i} \le L - 1$, $1 \le l_{i} \le L$). It is guaranteed that $t_{i} + l_{i} \le t_{i + 1}$ and $t_{n} + l_{n} \le L$.
-----Output-----
Output one integer — the maximum number of breaks.
-----Examples-----
Input
2 11 3
0 1
1 1
Output
3
Input
0 5 2
Output
2
Input
1 3 2
1 2
Output
0
-----Note-----
In the first sample Vasya can take $3$ breaks starting after $2$, $5$ and $8$ minutes after the beginning of the day.
In the second sample Vasya can take $2$ breaks starting after $0$ and $2$ minutes after the beginning of the day.
In the third sample Vasya can't take any breaks.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,L,a=list(map(int,input().split()))
count=0
last=0
for i in range(n):
t,l=list(map(int,input().split()))
count+=(t-last)//a
last=t+l
count+=(L-last)//a
print(count)
``` | vfc_15830 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1059/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 11 3\n0 1\n1 1\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0 5 2\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 3 2\n1 2\n",
"output": "0",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1520 | Solve the following coding problem using the programming language python:
Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings $s$ of length $m$ and $t$ is a string $t + s_1 + t + s_2 + \ldots + t + s_m + t$, where $s_i$ denotes the $i$-th symbol of the string $s$, and "+" denotes string concatenation. For example, the product of strings "abc" and "de" is a string "deadebdecde", while the product of the strings "ab" and "z" is a string "zazbz". Note, that unlike the numbers multiplication, the product of strings $s$ and $t$ is not necessarily equal to product of $t$ and $s$.
Roman was jealous of Denis, since he invented such a cool operation, and hence decided to invent something string-related too. Since Roman is beauty-lover, he decided to define the beauty of the string as the length of the longest substring, consisting of only one letter. For example, the beauty of the string "xayyaaabca" is equal to $3$, since there is a substring "aaa", while the beauty of the string "qwerqwer" is equal to $1$, since all neighboring symbols in it are different.
In order to entertain Roman, Denis wrote down $n$ strings $p_1, p_2, p_3, \ldots, p_n$ on the paper and asked him to calculate the beauty of the string $( \ldots (((p_1 \cdot p_2) \cdot p_3) \cdot \ldots ) \cdot p_n$, where $s \cdot t$ denotes a multiplication of strings $s$ and $t$. Roman hasn't fully realized how Denis's multiplication works, so he asked you for a help. Denis knows, that Roman is very impressionable, he guarantees, that the beauty of the resulting string is at most $10^9$.
-----Input-----
The first line contains a single integer $n$ ($2 \leq n \leq 100\,000$) — the number of strings, wroted by Denis.
Next $n$ lines contain non-empty strings $p_1, p_2, \ldots, p_n$, consisting of lowercase english letters.
It's guaranteed, that the total length of the strings $p_i$ is at most $100\,000$, and that's the beauty of the resulting product is at most $10^9$.
-----Output-----
Print exactly one integer — the beauty of the product of the strings.
-----Examples-----
Input
3
a
b
a
Output
3
Input
2
bnn
a
Output
1
-----Note-----
In the first example, the product of strings is equal to "abaaaba".
In the second example, the product of strings is equal to "abanana".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t = [0] * 26
def get_k(c):
return ord(c) - ord('a')
def analyze(s):
length_of_str = len(s)
pos = 0
beauty_table = [0] * 26
for i in range(1, length_of_str):
if s[i] != s[pos]:
k = get_k(s[pos])
beauty_table[k] = max(beauty_table[k], i - pos)
pos = i
k = get_k(s[pos])
beauty_table[k] = max(beauty_table[k], length_of_str - pos)
pos = 0
while pos < length_of_str and s[pos] == s[0]:
pos += 1
left_beauty = pos
pos = length_of_str - 1
while pos > 0 and s[pos] == s[length_of_str - 1]:
pos -= 1
right_beauty = length_of_str - pos - 1
return beauty_table, left_beauty, right_beauty
r = []
for _ in range(int(input())):
p = input()
if all(x == p[0] for x in p): # pure
k = get_k(p[0])
for i in range(26):
if i == k:
t[i] = len(p) * (t[i] + 1) + t[i]
else:
t[i] = min(1, t[i])
else:
for i in range(26):
t[i] = min(1, t[i])
bt, lb, rb = analyze(p)
lk, rk = get_k(p[0]), get_k(p[-1])
if lk == rk:
t[lk] = lb + rb + t[lk]
else:
t[lk], t[rk] = t[lk] + lb, t[rk] + rb
for i in range(26):
t[i] = max(t[i], bt[i])
# r.append(max(t))
# print('\ntableInfo: ', end= ' ')
# for i in range(26):
# print('{}:{}/'.format(chr(i + ord('a')), t[i]), end=' ')
# print('')
# print(' '.join(map(str, r)))
print(max(t))
``` | vfc_15834 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1131/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\na\nb\na\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1521 | Solve the following coding problem using the programming language python:
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number x_{i}, DZY will put it into the bucket numbered h(x_{i}), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b denotes taking a remainder after division a by b.
However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.
-----Input-----
The first line contains two integers, p and n (2 ≤ p, n ≤ 300). Then n lines follow. The i-th of them contains an integer x_{i} (0 ≤ x_{i} ≤ 10^9).
-----Output-----
Output a single integer — the answer to the problem.
-----Examples-----
Input
10 5
0
21
53
41
53
Output
4
Input
5 5
0
1
2
3
4
Output
-1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
p, n = map(int, input().split())
a = [-1 for i in range(p)]
for i in range(n):
b = int(input())
if a[b % p] != -1:
print(i + 1)
return
else:
a[b % p] = b
print(-1)
``` | vfc_15838 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/447/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 5\n0\n21\n53\n41\n53\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n0\n1\n2\n3\n4\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 6\n811966798\n734823552\n790326404\n929189974\n414343256\n560346537\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n788371161\n801743052\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1522 | Solve the following coding problem using the programming language python:
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.
The potato pie is located in the n-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.
Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
-----Input-----
The first line of the input contains a positive integer n (2 ≤ n ≤ 10^5) — the number of rooms in the house.
The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one.
The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2.
The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1.
-----Output-----
Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
-----Examples-----
Input
3
aAbB
Output
0
Input
4
aBaCaB
Output
3
Input
5
xYyXzZaZ
Output
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())
r = {}
ans = 0
for i in input():
if i == i.lower():
if i in r:
r[i] += 1
else:
r[i] = 1
else:
i = i.lower()
if i in r and r[i] > 0:
r[i] -= 1
else:
ans += 1
print(ans)
``` | vfc_15842 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/525/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\naAbB\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\naBaCaB\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\nxYyXzZaZ\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "26\naAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyY\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1523 | Solve the following coding problem using the programming language python:
The kingdom of Lazyland is the home to $n$ idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland.
Today $k$ important jobs for the kingdom ($k \le n$) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the $i$-th idler has chosen the job $a_i$.
Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes $b_i$ minutes to persuade the $i$-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him?
-----Input-----
The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$) — the number of idlers and the number of jobs.
The second line of the input contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le k$) — the jobs chosen by each idler.
The third line of the input contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le 10^9$) — the time the King needs to spend to persuade the $i$-th idler.
-----Output-----
The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done.
-----Examples-----
Input
8 7
1 1 3 1 5 3 7 1
5 7 4 8 1 3 5 2
Output
10
Input
3 3
3 1 2
5 3 4
Output
0
-----Note-----
In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6.
In the second example each job was chosen by some idler, so there is no need to persuade anyone.
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().strip().split()))
jobs = list(map(int, input().strip().split()))
times = list(map(int, input().strip().split()))
counts_jobs = {}
for job in jobs:
if job in counts_jobs:
counts_jobs[job] += 1
else:
counts_jobs[job] = 1
times_i = []
for i, time in enumerate(times):
times_i.append((time, i))
times_i.sort()
jobs_left = k-len(counts_jobs.keys())
ans = 0
for time, i in times_i:
if jobs_left == 0:
break
if counts_jobs[jobs[i]] > 1:
ans += time
jobs_left -= 1
counts_jobs[jobs[i]] -= 1
print(ans)
``` | vfc_15846 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1089/L",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "8 7\n1 1 3 1 5 3 7 1\n5 7 4 8 1 3 5 2\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n3 1 2\n5 3 4\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "14 6\n2 3 6 6 6 2 5 3 5 5 5 6 5 5\n56 41 19 81 19 32 99 37 97 20 90 44 19 79\n",
"output": "38\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "12 9\n6 8 2 6 8 2 6 6 6 5 1 1\n59 27 78 92 31 26 59 12 80 77 94 31\n",
"output": "96\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1529 | Solve the following coding problem using the programming language python:
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.
-----Input-----
The first line of the input contains an integer n (1 ≤ n ≤ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn’t exceed 100.
-----Output-----
For each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG>.< I don't know!" if liouzhou_101 can’t recognize whose sentence it is. He can’t recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions.
-----Examples-----
Input
5
I will go to play with you lala.
wow, welcome.
miao.lala.
miao.
miao .
Output
Freda's
OMG>.< I don't know!
OMG>.< I don't know!
Rainbow's
OMG>.< I don't know!
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
for i in range(int(input())):
s = input()
if s.endswith('lala.') and not s.startswith('miao.'):
print("Freda's")
elif s.startswith('miao.') and not s.endswith('lala.'):
print("Rainbow's")
else:
print("OMG>.< I don't know!")
``` | vfc_15870 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/312/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\nI will go to play with you lala.\nwow, welcome.\nmiao.lala.\nmiao.\nmiao .\n",
"output": "Freda's\nOMG>.< I don't know!\nOMG>.< I don't know!\nRainbow's\nOMG>.< I don't know!\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\nLpAEKiHVJrzSZqBVSSyY\nYECGBlala.\nUZeGpeM.UCwiHmmA\nqt_,.b_.LSwJtJ.\nFAnXZtHlala.\nmiao.iapelala.\nCFPlbUgObrXLejPNu.F\nZSUfvisiHyrIMjMlala.\nmiao. lala.\nd,IWSeumytrVlala.\n",
"output": "OMG>.< I don't know!\nFreda's\nOMG>.< I don't know!\nOMG>.< I don't know!\nFreda's\nOMG>.< I don't know!\nOMG>.< I don't know!\nFreda's\nOMG>.< I don't know!\nFreda's\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1530 | Solve the following coding problem using the programming language python:
(Легенда будет поправлена позже) У нас есть n целых чисел. Первое число становится корнем дерева, для остальных нужно реализовать добавление в дерево поиска и вывести для каждого n - 1 числа его непосредственного предка в дереве.
-----Входные данные-----
В первой строке записано одно целое число n (2 ≤ n ≤ 10^5) — количество чиcел. Во второй строке через пробел записаны n различных целых чисел a_{i} (1 ≤ a_{i} ≤ 10^9).
-----Выходные данные-----
Для всех i > 1 выведите непосредственного предка a_{i}
-----Примеры-----
Входные данные
3
1 2 3
Выходные данные
1 2
Входные данные
5
4 2 3 1 6
Выходные данные
4 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
class RedBlackNode(object):
def __init__(self, key):
self._key = key
self._red = False
self._left = None
self._right = None
self._p = None
class RedBlackTree(object):
def __init__(self):
self._nil = RedBlackNode(None)
self._root = self._nil
def insert_key(self, key):
y = self.search(key, True)
z = RedBlackNode(key)
z._p = y
if y == self._nil:
self._root = z
elif z._key < y._key:
y._left = z
else:
y._right = z
z._left = self._nil
z._right = self._nil
z._red = True
self._insert_fixup(z)
def _insert_fixup(self, z):
while z._p._red:
if z._p == z._p._p._left:
y = z._p._p._right
if y._red:
z._p._red = False
y._red = False
z._p._p._red = True
z = z._p._p
else:
if z == z._p._right:
z = z._p
self._left_rotate(z)
z._p._red = False
z._p._p._red = True
self._right_rotate(z._p._p)
else:
y = z._p._p._left
if y._red:
z._p._red = False
y._red = False
z._p._p._red = True
z = z._p._p
else:
if z == z._p._left:
z = z._p
self._right_rotate(z)
z._p._red = False
z._p._p._red = True
self._left_rotate(z._p._p)
self._root._red = False
def _left_rotate(self, x):
y = x._right
x._right = y._left
if y._left != self._nil:
y._left._p = x
y._p = x._p
if x._p == self._nil:
self._root = y
elif x == x._p._left:
x._p._left = y
else:
x._p._right = y
y._left = x
x._p = y
def _right_rotate(self, y):
x = y._left
y._left = x._right
if x._right != self._nil:
x._right._p = y
x._p = y._p
if y._p == self._nil:
self._root = x
elif y == y._p._right:
y._p._right = x
else:
y._p._left = x
x._right = y
y._p = x
def search(self, key, s):
x = self._root
g = self._nil
while x != self._nil:
g = x
if key < x._key:
x = x._left
else:
x = x._right
return(g)
def search2(self, key):
a = None
b = None
x = self._root
while x != self._nil and key != x._key:
if key < x._key:
a = x
x = x._left
else:
b = x
x = x._right
if key == x._key:
return(None)
else:
return((a,b))
n = int(input())
s = [int(i) for i in input().split()]
t = RedBlackTree()
t.insert_key([s[0],0,0])
e = []
for i in s[1:]:
o,u = t.search2([i,0,0])
if u == None:
e.append(o._key[0])
if o._key[0] > i:
o._key[1] = 1
else:
o._key[2] = 1
elif o == None:
e.append(u._key[0])
if u._key[0] > i:
u._key[1] = 1
else:
u._key[2] = 1
else:
if o._key[0] > i and u._key[0] > i:
if o._key[1] == 0:
o._key[1] = 1
e.append(o._key[0])
else:
u._key[1] = 1
e.append(u._key[0])
elif o._key[0] < i and u._key[0] > i:
if o._key[2] == 0:
o._key[2] = 1
e.append(o._key[0])
else:
u._key[1] = 1
e.append(u._key[0])
elif o._key[0] > i and u._key[0] < i:
if o._key[1] == 0:
o._key[1] = 1
e.append(o._key[0])
else:
u._key[2] = 1
e.append(u._key[0])
elif o._key[0] < i and u._key[0] < i:
if o._key[2] == 0:
o._key[2] = 1
e.append(o._key[0])
else:
u._key[2] = 1
e.append(u._key[0])
t.insert_key([i,0,0])
print(*e)
``` | vfc_15874 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/675/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "1 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n4 2 3 1 6\n",
"output": "4 2 2 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n991309218 517452607 870021923 978357992 136426010 10601767 302627526 883615372 163475700 600546765\n",
"output": "991309218 517452607 870021923 517452607 136426010 136426010 978357992 302627526 870021923\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1531 | Solve the following coding problem using the programming language python:
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal a_{i} — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart: The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible; the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same; and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
-----Input-----
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers a_{i} — the esthetic appeals of each tree. All esthetic appeals do not exceed 10^9 in their absolute value. to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1); to get 100 points, you need to solve the problem with constraints: n ≤ 3·10^5 (subproblems A1+A2).
-----Output-----
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
-----Examples-----
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5
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=tuple(map(int,input().split()))
c={}
p={}
s=x=y=0
m=-1e18
for i in range(0,len(a)):
d=c.get(a[i])
if d!=None and s-d+a[i]*2>m:
m=s-d+a[i]*2
x,y=p.get(a[i]),i
if(a[i]>0):s+=a[i]
if p.get(a[i])==None:
p[a[i]]=i
c[a[i]]=s
a=[str(i+1) for i in range(0,len(a)) if i!=x and i!=y and (a[i]<0 or i<x or i>y)]
print(m,len(a))
print(" ".join(a))
``` | vfc_15878 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/331/A1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 3 1 2\n",
"output": "8 1\n1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 -2 3 1 -2\n",
"output": "5 2\n2 5 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n0 0\n",
"output": "0 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n0 -1 0\n",
"output": "0 1\n2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 1 1\n",
"output": "3 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n-1 1 1 -1\n",
"output": "2 2\n1 4 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1532 | Solve the following coding problem using the programming language python:
Kate has a set $S$ of $n$ integers $\{1, \dots, n\} $.
She thinks that imperfection of a subset $M \subseteq S$ is equal to the maximum of $gcd(a, b)$ over all pairs $(a, b)$ such that both $a$ and $b$ are in $M$ and $a \neq b$.
Kate is a very neat girl and for each $k \in \{2, \dots, n\}$ she wants to find a subset that has the smallest imperfection among all subsets in $S$ of size $k$. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size $k$, will name it $I_k$.
Please, help Kate to find $I_2$, $I_3$, ..., $I_n$.
-----Input-----
The first and only line in the input consists of only one integer $n$ ($2\le n \le 5 \cdot 10^5$) — the size of the given set $S$.
-----Output-----
Output contains only one line that includes $n - 1$ integers: $I_2$, $I_3$, ..., $I_n$.
-----Examples-----
Input
2
Output
1
Input
3
Output
1 1
-----Note-----
First sample: answer is 1, because $gcd(1, 2) = 1$.
Second sample: there are subsets of $S$ with sizes $2, 3$ with imperfection equal to 1. For example, $\{2,3\}$ and $\{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
n = int(input())
l = []
for i in range(n + 1):
l.append(0)
for i in range(2, n + 1):
for j in range(i * 2, n + 1, i):
l[j] = i
l.sort()
for i in range(2, n + 1):
if l[i] == 0:
print(1, end=" ")
else:
print(l[i], end=" ")
``` | vfc_15882 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1333/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n",
"output": "1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "1 1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "1 1 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "1 1 1 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n",
"output": "1 1 1 2 3 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1533 | Solve the following coding problem using the programming language python:
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name s_{i} in the i-th line, output "YES" (without quotes) if there exists an index j such that s_{i} = s_{j} and j < i, otherwise, output "NO" (without quotes).
-----Input-----
First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list.
Next n lines each contain a string s_{i}, consisting of lowercase English letters. The length of each string is between 1 and 100.
-----Output-----
Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.
You can print each letter in any case (upper or lower).
-----Examples-----
Input
6
tom
lucius
ginny
harry
ginny
harry
Output
NO
NO
NO
NO
YES
YES
Input
3
a
a
a
Output
NO
YES
YES
-----Note-----
In test case 1, for i = 5 there exists j = 3 such that s_{i} = s_{j} and j < i, which means that answer for i = 5 is "YES".
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())
s = set()
for _ in range(n):
w = input()
if w in s:
print('YES')
else:
print('NO')
s.add(w)
main()
``` | vfc_15886 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/855/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\ntom\nlucius\nginny\nharry\nginny\nharry\n",
"output": "NO\nNO\nNO\nNO\nYES\nYES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1534 | Solve the following coding problem using the programming language python:
One day Nikita found the string containing letters "a" and "b" only.
Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".
Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?
-----Input-----
The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b".
-----Output-----
Print a single integer — the maximum possible size of beautiful string Nikita can get.
-----Examples-----
Input
abba
Output
4
Input
bab
Output
2
-----Note-----
It the first sample the string is already beautiful.
In the second sample he needs to delete one of "b" to make it beautiful.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s=input()
dp=[[0,0,0] for i in range(len(s))]
for i in range(len(s)):
if s[i]=='a':
dp[i][0]=dp[i-1][0]+1
dp[i][1]=dp[i-1][1]
dp[i][2]=max(dp[i-1][1]+1,dp[i-1][2]+1)
else:
dp[i][0]=dp[i-1][0]
dp[i][1]=max(dp[i-1][0]+1,dp[i-1][1]+1)
dp[i][2]=dp[i-1][2]
e=len(s)-1
print(max(dp[e][0],dp[e][1],dp[e][2]))
``` | vfc_15890 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/877/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "abba\n",
"output": "4",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "bab\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "bbabbbaabbbb\n",
"output": "9",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "bbabbbbbaaba\n",
"output": "10",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1535 | Solve the following coding problem using the programming language python:
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane.
Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x_0, y_0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x_0, y_0).
Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.
The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.
-----Input-----
The first line contains three integers n, x_0 и y_0 (1 ≤ n ≤ 1000, - 10^4 ≤ x_0, y_0 ≤ 10^4) — the number of stormtroopers on the battle field and the coordinates of your gun.
Next n lines contain two integers each x_{i}, y_{i} ( - 10^4 ≤ x_{i}, y_{i} ≤ 10^4) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.
-----Output-----
Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers.
-----Examples-----
Input
4 0 0
1 1
2 2
2 0
-1 -1
Output
2
Input
2 1 2
1 1
1 0
Output
1
-----Note-----
Explanation to the first and second samples from the statement, respectively: [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Codeforces Contest 291 Div 2 Problem B
Author : chaotic_iak
Language: Python 3.4.2
"""
################################################### SOLUTION
def gcd(a,b):
if a < 0: a = -a
if b < 0: b = -b
if a == 0: return b
if b == 0: return a
return gcd(b, a%b)
def main():
n, x0, y0 = read()
lines = set()
for i in range(n):
x, y = read()
x -= x0
y -= y0
if x < 0 or (x == 0 and y < 0): x,y = -x,-y
g = gcd(x,y)
x //= g
y //= g
lines.add((x,y))
return len(lines)
#################################################### 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_15894 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/514/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 0 0\n1 1\n2 2\n2 0\n-1 -1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1 2\n1 1\n1 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n0 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 0 0\n10000 -10000\n-10000 10000\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1537 | Solve the following coding problem using the programming language python:
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of $n$ rows and $n$ columns of square cells. The rows are numbered from $1$ to $n$, from top to bottom, and the columns are numbered from $1$ to $n$, from left to right. The position of a cell at row $r$ and column $c$ is represented as $(r, c)$. There are only two colors for the cells in cfpaint — black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size $k$ ($1 \le k \le n$). To use the eraser, Gildong needs to click on a cell $(i, j)$ where $1 \le i, j \le n - k + 1$. When a cell $(i, j)$ is clicked, all of the cells $(i', j')$ where $i \le i' \le i + k - 1$ and $j \le j' \le j + k - 1$ become white. In other words, a square with side equal to $k$ cells and top left corner at $(i, j)$ is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$) — the number of rows and columns, and the size of the eraser.
The next $n$ lines contain $n$ characters each without spaces. The $j$-th character in the $i$-th line represents the cell at $(i,j)$. Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
-----Output-----
Print one integer: the maximum number of white lines after using the eraser exactly once.
-----Examples-----
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
-----Note-----
In the first example, Gildong can click the cell $(2, 2)$, then the working screen becomes: BWWW
WWWW
WWWW
WWWB
Then there are four white lines — the $2$-nd and $3$-rd row, and the $2$-nd and $3$-rd column.
In the second example, clicking the cell $(2, 3)$ makes the $2$-nd row a white line.
In the third example, both the $2$-nd column and $5$-th row become white lines by clicking the cell $(3, 2)$.
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 count(n, k, field):
blank = 0
cnt = [[0] * (n - k + 1) for _ in range(n)]
for i, row in enumerate(field):
l = row.find('B')
r = row.rfind('B')
if l == r == -1:
blank += 1
continue
if r - l + 1 > k:
continue
kl = max(0, r - k + 1)
kr = min(l + 1, n - k + 1)
cnt[i][kl:kr] = [1] * (kr - kl)
acc = [[0] * (n - k + 1) for _ in range(n - k + 1)]
t_cnt = list(zip(*cnt))
for i, col in enumerate(t_cnt):
aci = acc[i]
tmp = sum(col[n - k:])
aci[n - k] = tmp
for j in range(n - k - 1, -1, -1):
tmp += col[j]
tmp -= col[j + k]
aci[j] = tmp
return blank, acc
n, k = list(map(int, input().split()))
field = [line.strip() for line in sys.stdin]
bh, hor = count(n, k, field)
t_field = [''.join(col) for col in zip(*field)]
bv, t_var = count(n, k, t_field)
var = list(zip(*t_var))
print(bh + bv + max(h + v for (rh, rv) in zip(hor, var) for (h, v) in zip(rh, rv)))
``` | vfc_15902 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1200/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2\nBWWW\nWBBW\nWBBW\nWWWB\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1\nBWB\nWWB\nBWB\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3\nBWBBB\nBWBBB\nBBBBB\nBBBBB\nWBBBW\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1538 | Solve the following coding problem using the programming language python:
Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length a_{i}.
Mishka can put a box i into another box j if the following conditions are met:
i-th box is not put into another box; j-th box doesn't contain any other boxes; box i is smaller than box j (a_{i} < a_{j}).
Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.
Help Mishka to determine the minimum possible number of visible boxes!
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 5000) — the number of boxes Mishka has got.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is the side length of i-th box.
-----Output-----
Print the minimum possible number of visible boxes.
-----Examples-----
Input
3
1 2 3
Output
1
Input
4
4 2 4 3
Output
2
-----Note-----
In the first example it is possible to put box 1 into box 2, and 2 into 3.
In the second example Mishka can put box 2 into box 3, and box 4 into box 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())
d = list(map(int, input().split()))
s = {i:0 for i in set(d)}
for i in d:
s[i] += 1
print(max(s.values()))
``` | vfc_15906 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/903/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1539 | Solve the following coding problem using the programming language python:
Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.
In total the table Arthur bought has n legs, the length of the i-th leg is l_{i}.
Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number d_{i} — the amount of energy that he spends to remove the i-th leg.
A table with k legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with 5 legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths.
Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 10^5) — the initial number of legs in the table Arthur bought.
The second line of the input contains a sequence of n integers l_{i} (1 ≤ l_{i} ≤ 10^5), where l_{i} is equal to the length of the i-th leg of the table.
The third line of the input contains a sequence of n integers d_{i} (1 ≤ d_{i} ≤ 200), where d_{i} is the number of energy units that Arthur spends on removing the i-th leg off the table.
-----Output-----
Print a single integer — the minimum number of energy units that Arthur needs to spend in order to make the table stable.
-----Examples-----
Input
2
1 5
3 2
Output
2
Input
3
2 4 4
1 1 1
Output
0
Input
6
2 2 1 1 3 3
4 3 5 5 2 1
Output
8
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
def main():
n = int(input())
hh = list(map(int, input().split()))
ee = list(map(int, input().split()))
dd = defaultdict(set)
for i, h in enumerate(hh):
dd[h].add(i)
idx = sorted(list(range(n)), key=ee.__getitem__, reverse=True)
res = 0
for h, s in list(dd.items()):
x = sum(ee[i] for i in s)
le = len(s) - 1
if le:
for i in idx:
if hh[i] < h and i not in s:
x += ee[i]
le -= 1
if not le:
break
if res < x:
res = x
print(sum(ee) - res)
def __starting_point():
main()
__starting_point()
``` | vfc_15910 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/557/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 5\n3 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 4 4\n1 1 1\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1541 | Solve the following coding problem using the programming language python:
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar. If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar. If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
-----Input-----
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 10^6), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
-----Output-----
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
-----Examples-----
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
-----Note-----
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
[Image]
[Image]
[Image]
$\Delta \Delta \Delta \Delta$
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = input()
suc = 0
p = 0
kde = 0
for i in range(len(s)):
c = s[i]
if c == '^':
kde = i
for i in range(len(s)):
c = s[i]
if '1' <= c <= '9':
suc+=((kde-i)*int(c))
p+=1
if suc < 0:
print("right")
elif suc > 0:
print("left")
else:
print("balance")
``` | vfc_15918 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/376/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "=^==\n",
"output": "balance\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9===^==1\n",
"output": "left\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2==^7==\n",
"output": "right\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "41^52==\n",
"output": "balance\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1542 | Solve the following coding problem using the programming language python:
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to x_{i} coins.
Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent m_{i} coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink.
The second line contains n integers x_{i} (1 ≤ x_{i} ≤ 100 000) — prices of the bottles of the drink in the i-th shop.
The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink.
Then follow q lines each containing one integer m_{i} (1 ≤ m_{i} ≤ 10^9) — the number of coins Vasiliy can spent on the i-th day.
-----Output-----
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
-----Example-----
Input
5
3 10 8 6 11
4
1
10
3
11
Output
0
4
1
5
-----Note-----
On the first day, Vasiliy won't be able to buy a drink in any of the shops.
On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.
On the third day, Vasiliy can buy a drink only in the shop number 1.
Finally, on the last day Vasiliy can buy a drink in any shop.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import bisect
n = int(input())
p = list(map(int, input().split()))
p.sort()
q = int(input())
for i in range(q):
c = int(input())
print(bisect.bisect_right(p, c))
``` | vfc_15922 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/706/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n3 10 8 6 11\n4\n1\n10\n3\n11\n",
"output": "0\n4\n1\n5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1543 | Solve the following coding problem using the programming language python:
The cities of Byteland and Berland are located on the axis $Ox$. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line $Ox$ there are three types of cities: the cities of Byteland, the cities of Berland, disputed cities.
Recently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected.
The countries agreed to connect the pairs of cities with BNET cables in such a way that: If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables, If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables.
Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities.
The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected.
Each city is a point on the line $Ox$. It is technically possible to connect the cities $a$ and $b$ with a cable so that the city $c$ ($a < c < b$) is not connected to this cable, where $a$, $b$ and $c$ are simultaneously coordinates of the cities $a$, $b$ and $c$.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 2 \cdot 10^{5}$) — the number of cities.
The following $n$ lines contains an integer $x_i$ and the letter $c_i$ ($-10^{9} \le x_i \le 10^{9}$) — the coordinate of the city and its type. If the city belongs to Byteland, $c_i$ equals to 'B'. If the city belongs to Berland, $c_i$ equals to «R». If the city is disputed, $c_i$ equals to 'P'.
All cities have distinct coordinates. Guaranteed, that the cities are given in the increasing order of their coordinates.
-----Output-----
Print the minimal total length of such set of cables, that if we delete all Berland cities ($c_i$='R'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables. Similarly, if we delete all Byteland cities ($c_i$='B'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables.
-----Examples-----
Input
4
-5 R
0 P
3 P
7 B
Output
12
Input
5
10 R
14 B
16 B
21 R
32 R
Output
24
-----Note-----
In the first example, you should connect the first city with the second, the second with the third, and the third with the fourth. The total length of the cables will be $5 + 3 + 4 = 12$.
In the second example there are no disputed cities, so you need to connect all the neighboring cities of Byteland and all the neighboring cities of Berland. The cities of Berland have coordinates $10, 21, 32$, so to connect them you need two cables of length $11$ and $11$. The cities of Byteland have coordinates $14$ and $16$, so to connect them you need one cable of length $2$. Thus, the total length of all cables is $11 + 11 + 2 = 24$.
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, stdout
input, print = stdin.readline, stdout.write
n = int(input())
r, g, b = [], [], []
ans = 0
for i in range(n):
x, t = [i for i in input().split()]
x = int(x)
if t == 'P':
g.append(x)
elif t == 'R':
r.append(x)
else:
b.append(x)
if len(g) == 0:
if len(r):
ans += r[-1] - r[0]
if len(b):
ans += b[-1] - b[0]
print(str(ans))
return
if not len(r):
r.append(g[0])
if not len(b):
b.append(g[0])
if r[0] < g[0]:
ans += g[0] - r[0]
if b[0] < g[0]:
ans += g[0] - b[0]
if r[-1] > g[-1]:
ans += r[-1] - g[-1]
if b[-1] > g[-1]:
ans += b[-1] - g[-1]
bi, ri = 0, 0
for i in range(len(g) - 1):
while bi < len(b) - 1 and b[bi] < g[i]:
bi += 1
while ri < len(r) - 1 and r[ri] < g[i]:
ri += 1
a1, a2 = (g[i + 1] - g[i]) * 3, (g[i + 1] - g[i]) * 2
mr, mb, cbi, cri = r[ri] - g[i], b[bi] - g[i], bi, ri
while cbi + 1 < len(b) and b[cbi + 1] < g[i + 1]:
mb = max(mb, b[cbi + 1] - b[cbi])
cbi += 1
mb = max(mb, g[i + 1] - b[cbi])
while cri + 1 < len(r) and r[cri + 1] < g[i + 1]:
mr = max(mr, r[cri + 1] - r[cri])
cri += 1
mr = max(mr, g[i + 1] - r[cri])
if b[bi] < g[i] or b[bi] > g[i + 1]:
a2 = 100000000000000
a1 -= g[i + 1] - g[i]
mb = 0
if r[ri] < g[i] or r[ri] > g[i + 1]:
a2 = 100000000000000
a1 -= g[i + 1] - g[i]
mr = 0
ans += min(a1 - mr - mb, a2)
print(str(ans))
``` | vfc_15926 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/962/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n-5 R\n0 P\n3 P\n7 B\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n10 R\n14 B\n16 B\n21 R\n32 R\n",
"output": "24\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n66 R\n67 R\n72 R\n73 R\n76 R\n78 B\n79 B\n83 B\n84 B\n85 P\n",
"output": "26\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n61 R\n64 R\n68 R\n71 R\n72 R\n73 R\n74 P\n86 P\n87 B\n90 B\n",
"output": "29\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1544 | Solve the following coding problem using the programming language python:
Because of budget cuts one IT company established new non-financial reward system instead of bonuses.
Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table.
Because of the limited budget of the new reward system only 5 "I fixed a critical bug" pennants and 3 "I suggested a new feature" pennants were bought.
In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table.
One man can have several pennants of one type and of course he can have pennants of both types on his table. There are n tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.
-----Input-----
The only line of the input contains one integer n (1 ≤ n ≤ 500) — the number of tables in the IT company.
-----Output-----
Output one integer — the amount of ways to place the pennants on n tables.
-----Examples-----
Input
2
Output
24
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())
c1 = n
c2 = (n * (n-1)) // 2
c3 = (n * (n-1) * (n-2)) // (2*3)
c4 = (n * (n-1) * (n-2) * (n-3)) // (2*3*4)
c5 = (n * (n-1) * (n-2) * (n-3) * (n-4)) // (2*3*4*5)
w1 = 0
w1 += c1
w1 += c2 * 2
w1 += c3
w2 = 0
w2 += c1
w2 += c2 * 4
w2 += c3 * 6
w2 += c4 * 4
w2 += c5
print(w1*w2)
``` | vfc_15930 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/G",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n",
"output": "24",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "210",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1548 | Solve the following coding problem using the programming language python:
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.
The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $(0, 0)$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $OX$ or $OY$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.
Alexey wants to make a polyline in such a way that its end is as far as possible from $(0, 0)$. Please help him to grow the tree this way.
Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 100\,000$) — the number of sticks Alexey got as a present.
The second line contains $n$ integers $a_1, \ldots, a_n$ ($1 \le a_i \le 10\,000$) — the lengths of the sticks.
-----Output-----
Print one integer — the square of the largest possible distance from $(0, 0)$ to the tree end.
-----Examples-----
Input
3
1 2 3
Output
26
Input
4
1 1 2 2
Output
20
-----Note-----
The following pictures show optimal trees for example tests. The squared distance in the first example equals $5 \cdot 5 + 1 \cdot 1 = 26$, and in the second example $4 \cdot 4 + 2 \cdot 2 = 20$.
[Image]
[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())
l = list(map(int,input().split()))
l.sort()
a = l[:n//2]
b = l[n//2:]
print(sum(a)**2+sum(b)**2)
``` | vfc_15946 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1248/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "26",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1550 | Solve the following coding problem using the programming language python:
You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.
You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display.
The second line contains n digits — the initial state of the display.
-----Output-----
Print a single line containing n digits — the desired state of the display containing the smallest possible number.
-----Examples-----
Input
3
579
Output
024
Input
4
2014
Output
0142
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def modify(string, index):
if string[index] == '0':
key = 0
else:
key = 10 - int(string[index])
bad = ''
for i in string:
bad += str((int(i) + key) % 10)
return bad[index:] + bad[:index]
x = int(input())
y = input()
minx = 'zzzzzzzzz'
for i in range(x):
minx = min(minx, modify(y, i))
print(minx)
``` | vfc_15954 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/496/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n579\n",
"output": "024\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2014\n",
"output": "0142\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n039\n",
"output": "014\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n4444\n",
"output": "0000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1552 | Solve the following coding problem using the programming language python:
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value t_{i}: t_{i} = 1, if the i-th child is good at programming, t_{i} = 2, if the i-th child is good at maths, t_{i} = 3, if the i-th child is good at PE
Each child happens to be good at exactly one of these three subjects.
The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.
What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
-----Input-----
The first line contains integer n (1 ≤ n ≤ 5000) — the number of children in the school. The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 3), where t_{i} describes the skill of the i-th child.
-----Output-----
In the first line output integer w — the largest possible number of teams.
Then print w lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to n in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them.
If no teams can be compiled, print the only line with value w equal to 0.
-----Examples-----
Input
7
1 3 1 3 2 1 2
Output
2
3 5 2
6 7 4
Input
4
2 1 1 2
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 = int(input())
m = list(map(int, input().split()))
a = []
b = []
c = []
for i in range(n):
if m[i] == 1:
a.append(i + 1)
if m[i] == 2:
b.append(i + 1)
if m[i] == 3:
c.append(i + 1)
ans = min(len(a), len(b), len(c))
print(ans)
for i in range(ans):
print(a[i], b[i], c[i])
``` | vfc_15962 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/490/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\n1 3 1 3 2 1 2\n",
"output": "2\n3 5 2\n6 7 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2 1 1 2\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1554 | Solve the following coding problem using the programming language python:
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type a_{i}.
Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.
Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 3·10^5) — the number of pearls in a row.
The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) – the type of the i-th pearl.
-----Output-----
On the first line print integer k — the maximal number of segments in a partition of the row.
Each of the next k lines should contain two integers l_{j}, r_{j} (1 ≤ l_{j} ≤ r_{j} ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment.
Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type.
If there are several optimal solutions print any of them. You can print the segments in any order.
If there are no correct partitions of the row print the number "-1".
-----Examples-----
Input
5
1 2 3 4 1
Output
1
1 5
Input
5
1 2 3 4 5
Output
-1
Input
7
1 2 1 3 1 2 1
Output
2
1 3
4 7
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())
cnt = 0
gems = list(map(int, input().split()))
pearls = set()
for i in range(n):
if gems[i] not in pearls:
pearls.add(gems[i])
else:
cnt += 1
pearls = set()
if cnt:
print(cnt)
first = 0
second = 0
pearls = set()
for i in range(n):
if gems[i] not in pearls:
pearls.add(gems[i])
else:
if second:
print(first + 1, second + 1)
first = second + 1
second = i
pearls = set()
print(first + 1, n)
else:
print('-1')
``` | vfc_15970 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/620/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 3 4 1\n",
"output": "1\n1 5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 2 3 4 5\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n1 2 1 3 1 2 1\n",
"output": "2\n1 3\n4 7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9\n1 2 1 2 1 2 1 2 1\n",
"output": "3\n1 3\n4 6\n7 9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11\n1 1 2 1 2 1 2 1 2 1 1\n",
"output": "4\n1 2\n3 5\n6 8\n9 11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n576560149\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1555 | Solve the following coding problem using the programming language python:
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.
Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.
The gourmet tasted a set of $n$ dishes on the first day and a set of $m$ dishes on the second day. He made a table $a$ of size $n \times m$, in which he described his impressions. If, according to the expert, dish $i$ from the first set was better than dish $j$ from the second set, then $a_{ij}$ is equal to ">", in the opposite case $a_{ij}$ is equal to "<". Dishes also may be equally good, in this case $a_{ij}$ is "=".
Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $a_{ij}$ is "<", then the number assigned to dish $i$ from the first set should be less than the number of dish $j$ from the second set, if $a_{ij}$ is ">", then it should be greater, and finally if $a_{ij}$ is "=", then the numbers should be the same.
Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
-----Input-----
The first line contains integers $n$ and $m$ ($1 \leq n, m \leq 1000$) — the number of dishes in both days.
Each of the next $n$ lines contains a string of $m$ symbols. The $j$-th symbol on $i$-th line is $a_{ij}$. All strings consist only of "<", ">" and "=".
-----Output-----
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise.
If case an answer exist, on the second line print $n$ integers — evaluations of dishes from the first set, and on the third line print $m$ integers — evaluations of dishes from the second set.
-----Examples-----
Input
3 4
>>>>
>>>>
>>>>
Output
Yes
2 2 2
1 1 1 1
Input
3 3
>>>
<<<
>>>
Output
Yes
3 1 3
2 2 2
Input
3 2
==
=<
==
Output
No
-----Note-----
In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $2$, for all dishes of the first day.
In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
'''input
3 3
>>>
<<<
>>>
'''
#print(input().split())
n, m = list(map(int, input().split()))
#return
g = []
for i in range(n):
g += [input()]
# print(g)
memo = {}
def dfs(u):
if u not in memo:
memo[u] = res = 1
if u < n:
for v in range(m):
if g[u][v] == '>':
res = max(res, dfs(n + v) + 1)
for v in range(m):
if g[u][v] == '=':
res = max(res, dfs(n + v))
for v in range(m):
if g[u][v] == '=':
memo[n + v] = max(memo[n + v], res)
else:
for v in range(n):
if g[v][u - n] == '<':
res = max(res, dfs(v) + 1)
for v in range(n):
if g[v][u - n] == '=':
res = max(res, dfs(v))
for v in range(n):
if g[v][u - n] == '=':
memo[v] = max(memo[v], res)
memo[u] = res
return memo[u]
ans = [0] * (n + m)
for i in range(n + m):
ans[i] = dfs(i)
for i in range(n):
for j in range(m):
if g[i][j] == '=' and ans[i] != ans[n + j]:
print("No")
return
if g[i][j] == '<' and ans[i] >= ans[n + j]:
print("No")
return
if g[i][j] == '>' and ans[i] <= ans[n + j]:
print("No")
return
print("Yes")
print(*ans[:n])
print(*ans[n:])
``` | vfc_15974 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1131/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4\n>>>>\n>>>>\n>>>>\n",
"output": "Yes\n2 2 2 \n1 1 1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n>>>\n<<<\n>>>\n",
"output": "Yes\n3 1 3 \n2 2 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n==\n=<\n==\n",
"output": "No\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n<\n",
"output": "Yes\n1 \n2 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1556 | Solve the following coding problem using the programming language python:
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array a_{i} either with a_{i} + x or with a_{i} - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. $\prod_{i = 1}^{n} a_{i}$) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
-----Input-----
The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 10^9) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a_1, a_2, ..., a_{n} ($|a_{i}|\leq 10^{9}$) — the elements of the array found by Maxim.
-----Output-----
Print n integers b_1, b_2, ..., b_{n} in the only line — the array elements after applying no more than k operations to the array. In particular, $a_{i} \equiv b_{i} \operatorname{mod} x$ should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
-----Examples-----
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import heapq as hq
from math import ceil
n, k, x = [int(i) for i in input().strip().split(' ')]
arr = [int(i) for i in input().strip().split(' ')]
is_neg = False
for i in arr:
if i < 0:
is_neg = True if is_neg == False else False
narr = [[abs(i), pos, i < 0] for pos, i in enumerate(arr)]
hq.heapify(narr)
if is_neg:
while k > 0:
hq.heapreplace(narr, [narr[0][0]+x, narr[0][1], narr[0][2]])
k -= 1
else:
minode = hq.heappop(narr)
mi = minode[0]
kswitch = ceil(mi/x) #make the off number of negatives
if kswitch > k:
kswitch = k
else:
minode[2] = False if minode[2] == True else True
k -= kswitch
hq.heappush(narr, [abs(mi-kswitch*x), minode[1], minode[2]])
while k > 0:
hq.heapreplace(narr, [narr[0][0]+x, narr[0][1], narr[0][2]])
k -= 1
narr = sorted(narr, key=lambda x:x[1])
arr = [str(i[0]*(-1 if i[2] else 1)) for i in narr]
print(" ".join(arr))
``` | vfc_15978 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/721/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 3 1\n5 4 3 5 2\n",
"output": "5 4 3 5 -1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3 1\n5 4 3 5 5\n",
"output": "5 4 0 5 5 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3 1\n5 4 4 5 5\n",
"output": "5 1 4 5 5 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 7\n5 4 2\n",
"output": "5 11 -5 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1557 | Solve the following coding problem using the programming language python:
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h_2 health points and an attack power of a_2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h_1 health points and an attack power of a_1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c_1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c_1 > a_2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a_1) or drink a healing potion (it increases Vova's health by c_1; Vova's health can exceed h_1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a_2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
-----Input-----
The first line contains three integers h_1, a_1, c_1 (1 ≤ h_1, a_1 ≤ 100, 2 ≤ c_1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h_2, a_2 (1 ≤ h_2 ≤ 100, 1 ≤ a_2 < c_1) — the Modcrab's health and his attack power.
-----Output-----
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
-----Examples-----
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
-----Note-----
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
h1, a1, c1 = list(map(int, input().split()))
h2, a2 = list(map(int, input().split()))
d = []
while h2 > 0:
if h2 <= a1:
h2 -= a1
d.append('STRIKE')
else:
if h1 <= a2:
d.append('HEAL')
h1 += c1
else:
d.append('STRIKE')
h2 -= a1
h1 -= a2
print(len(d))
for i in d:
print(i)
``` | vfc_15982 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/903/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 6 100\n17 5\n",
"output": "4\nSTRIKE\nHEAL\nSTRIKE\nSTRIKE\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11 6 100\n12 5\n",
"output": "2\nSTRIKE\nSTRIKE\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "25 27 91\n10 87\n",
"output": "1\nSTRIKE\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1558 | Solve the following coding problem using the programming language python:
Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade a_{i} for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write b_{i} essays. He can raise the exam grade multiple times.
What is the minimum number of essays that Vanya needs to write to get scholarship?
-----Input-----
The first line contains three integers n, r, avg (1 ≤ n ≤ 10^5, 1 ≤ r ≤ 10^9, 1 ≤ avg ≤ min(r, 10^6)) — the number of exams, the maximum grade and the required grade point average, respectively.
Each of the following n lines contains space-separated integers a_{i} and b_{i} (1 ≤ a_{i} ≤ r, 1 ≤ b_{i} ≤ 10^6).
-----Output-----
In the first line print the minimum number of essays.
-----Examples-----
Input
5 5 4
5 2
4 7
3 1
3 2
2 5
Output
4
Input
2 5 4
5 2
5 2
Output
0
-----Note-----
In the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.
In the second sample, Vanya doesn't need to write any essays as his general point average already is above average.
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,r,avg=list(map(int,input().split()))
L=[]
tot=0
for i in range(n):
L.append(list(map(int,input().split())))
L[i][0],L[i][1]=L[i][1],L[i][0]
tot+=L[i][1]
L[i][1]=r-L[i][1]
req=avg*n
L.sort()
ind=0
ans=0
while(ind<n and req>tot):
diff=req-tot
if(L[ind][1]>=diff):
ans+=diff*L[ind][0]
tot+=diff
L[ind][1]-=diff
else:
ans+=L[ind][1]*L[ind][0]
tot+=L[ind][1]
L[ind][1]=0
ind+=1
print(ans)
``` | vfc_15986 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/492/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 5 4\n5 2\n4 7\n3 1\n3 2\n2 5\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 5 4\n5 2\n5 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 5 5\n1 7\n2 4\n3 5\n4 6\n5 6\n4 7\n",
"output": "63\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1000000000 1000000\n1 1000000\n",
"output": "999999000000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1559 | Solve the following coding problem using the programming language python:
Alice became interested in periods of integer numbers. We say positive $X$ integer number is periodic with length $L$ if there exists positive integer number $P$ with $L$ digits such that $X$ can be written as $PPPP…P$. For example:
$X = 123123123$ is periodic number with length $L = 3$ and $L = 9$
$X = 42424242$ is periodic number with length $L = 2,L = 4$ and $L = 8$
$X = 12345$ is periodic number with length $L = 5$
For given positive period length $L$ and positive integer number $A$, Alice wants to find smallest integer number $X$ strictly greater than $A$ that is periodic with length L.
-----Input-----
First line contains one positive integer number $L \ (1 \leq L \leq 10^5)$ representing length of the period. Second line contains one positive integer number $A \ (1 \leq A \leq 10^{100 000})$.
-----Output-----
One positive integer number representing smallest positive number that is periodic with length $L$ and is greater than $A$.
-----Examples-----
Input
3
123456
Output
124124
Input
3
12345
Output
100100
-----Note-----
In first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).
In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
l = int(input())
a = input()
la = len(a)
if la % l != 0:
per = la//l+1
ans = '1'+'0'*(l-1)
ans *= per
print(ans)
else:
ans = a[:l]
per = la//l
if ans*per > a:print(ans*per)
else:
temp = str(int(ans)+1)
if len(temp) == l:print(temp*per)
else:
temp = '1'+'0'*(l-1)
temp *= (per+1)
print(temp)
``` | vfc_15990 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1219/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n123456\n",
"output": "124124\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1560 | Solve the following coding problem using the programming language python:
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
-----Output-----
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
-----Examples-----
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
-----Note-----
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def f(first, s):
second = 'r' if first == 'b' else 'b'
alt = [first, second]
error = [0, 0]
for i,ch in enumerate(s):
shouldbe = alt[i % 2]
if ch != shouldbe:
error[i % 2] += 1
return max(error)
def main():
n = int(input())
s = input()
print(min(f('r', s), f('b', s)))
main()
``` | vfc_15994 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/719/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\nrbbrr\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\nbbbbb\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nrbr\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1562 | Solve the following coding problem using the programming language python:
You are on the island which can be represented as a $n \times m$ table. The rows are numbered from $1$ to $n$ and the columns are numbered from $1$ to $m$. There are $k$ treasures on the island, the $i$-th of them is located at the position $(r_i, c_i)$.
Initially you stand at the lower left corner of the island, at the position $(1, 1)$. If at any moment you are at the cell with a treasure, you can pick it up without any extra time. In one move you can move up (from $(r, c)$ to $(r+1, c)$), left (from $(r, c)$ to $(r, c-1)$), or right (from position $(r, c)$ to $(r, c+1)$). Because of the traps, you can't move down.
However, moving up is also risky. You can move up only if you are in a safe column. There are $q$ safe columns: $b_1, b_2, \ldots, b_q$. You want to collect all the treasures as fast as possible. Count the minimum number of moves required to collect all the treasures.
-----Input-----
The first line contains integers $n$, $m$, $k$ and $q$ ($2 \le n, \, m, \, k, \, q \le 2 \cdot 10^5$, $q \le m$) — the number of rows, the number of columns, the number of treasures in the island and the number of safe columns.
Each of the next $k$ lines contains two integers $r_i, c_i$, ($1 \le r_i \le n$, $1 \le c_i \le m$) — the coordinates of the cell with a treasure. All treasures are located in distinct cells.
The last line contains $q$ distinct integers $b_1, b_2, \ldots, b_q$ ($1 \le b_i \le m$) — the indices of safe columns.
-----Output-----
Print the minimum number of moves required to collect all the treasures.
-----Examples-----
Input
3 3 3 2
1 1
2 1
3 1
2 3
Output
6
Input
3 5 3 2
1 2
2 3
3 1
1 5
Output
8
Input
3 6 3 2
1 6
2 2
3 4
1 6
Output
15
-----Note-----
In the first example you should use the second column to go up, collecting in each row treasures from the first column. [Image]
In the second example, it is optimal to use the first column to go up. [Image]
In the third example, it is optimal to collect the treasure at cell $(1;6)$, go up to row $2$ at column $6$, then collect the treasure at cell $(2;2)$, go up to the top row at column $1$ and collect the last treasure at cell $(3;4)$. That's a total of $15$ moves. [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
input = sys.stdin.readline
n,m,k,q=list(map(int,input().split()))
TR=[list(map(int,input().split())) for i in range(k)]
SAFE=list(map(int,input().split()))
SAFE.sort()
TRLIST=[[] for i in range(n+1)]
for x,y in TR:
TRLIST[x].append(y)
while TRLIST[-1]==[]:
TRLIST.pop()
n-=1
START={1:0} #place,step
import bisect
for step in range(1,n):
if TRLIST[step]==[] and step!=1:
continue
elif TRLIST[step]==[] and step==1:
MIN=MAX=1
else:
MIN=min(TRLIST[step])
MAX=max(TRLIST[step])
MINind=max(0,bisect.bisect_left(SAFE,MIN)-1)
MIN_L=SAFE[MINind]
if MINind==q-1:
MIN_R=MIN_L
else:
MIN_R=SAFE[MINind+1]
MAXind=max(0,bisect.bisect_left(SAFE,MAX)-1)
MAX_L=SAFE[MAXind]
if MAXind==q-1:
MAX_R=MAX_L
else:
MAX_R=SAFE[MAXind+1]
NEXT=dict()
for start in START:
st=START[start]
NEXT[MIN_L]=min(st+abs(MAX-start)+abs(MAX-MIN)+abs(MIN_L-MIN),NEXT.get(MIN_L,1<<50))
NEXT[MIN_R]=min(st+abs(MAX-start)+abs(MAX-MIN)+abs(MIN_R-MIN),NEXT.get(MIN_R,1<<50))
NEXT[MAX_L]=min(st+abs(MIN-start)+abs(MAX-MIN)+abs(MAX_L-MAX),NEXT.get(MAX_L,1<<50))
NEXT[MAX_R]=min(st+abs(MIN-start)+abs(MAX-MIN)+abs(MAX_R-MAX),NEXT.get(MAX_R,1<<50))
START=NEXT
#print(START)
LAST=1<<50
if TRLIST[n]==[]:
print(min(START.values())+n-1)
return
MIN=min(TRLIST[n])
MAX=max(TRLIST[n])
#print(START)
for start in START:
st=START[start]
LAST=min(LAST,st+abs(MAX-start)+abs(MAX-MIN),st+abs(MIN-start)+abs(MAX-MIN))
print(LAST+n-1)
``` | vfc_16002 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1201/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3 3 2\n1 1\n2 1\n3 1\n2 3\n",
"output": "6",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 5 3 2\n1 2\n2 3\n3 1\n1 5\n",
"output": "8",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 6 3 2\n1 6\n2 2\n3 4\n1 6\n",
"output": "15",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2 2 2\n1 1\n1 2\n1 2\n",
"output": "1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1565 | Solve the following coding problem using the programming language python:
Dima worked all day and wrote down on a long paper strip his favorite number $n$ consisting of $l$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.
To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.
Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain.
-----Input-----
The first line contains a single integer $l$ ($2 \le l \le 100\,000$) — the length of the Dima's favorite number.
The second line contains the positive integer $n$ initially written on the strip: the Dima's favorite number.
The integer $n$ consists of exactly $l$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip.
-----Output-----
Print a single integer — the smallest number Dima can obtain.
-----Examples-----
Input
7
1234567
Output
1801
Input
3
101
Output
11
-----Note-----
In the first example Dima can split the number $1234567$ into integers $1234$ and $567$. Their sum is $1801$.
In the second example Dima can split the number $101$ into integers $10$ and $1$. Their sum is $11$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
l = int(input())
n = input()
best = int(n)
p = (l - 1) // 2
for i in range(p, -1, -1):
if (n[i + 1] == '0'):
continue
best = min(best, int(n[0:(i + 1)]) + int(n[i + 1:]))
break
p = l // 2
for i in range(p, l):
if (n[i] == '0'):
continue
best = min(best, int(n[0:i]) + int(n[i:]))
break
print(best)
``` | vfc_16014 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1181/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\n1234567\n",
"output": "1801\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n101\n",
"output": "11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20\n67378957561978988538\n",
"output": "8716884294\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1566 | Solve the following coding problem using the programming language python:
The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good.
Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle.
As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides). [Image]
-----Input-----
The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 50). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.
Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).
-----Output-----
The first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.
-----Example-----
Input
6
000000
000000
012100
024200
012100
000000
Output
Yes
-----Note-----
The lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (x_1, y_1), (x_1, y_2), (x_2, y_1), (x_2, y_2)), has a non-zero area and be contained inside of the grid (that is, 0 ≤ x_1 < x_2 ≤ N, 0 ≤ y_1 < y_2 ≤ N), and result in the levels of Zombie Contamination as reported in the input.
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())
grid = []
x1 = 50
y1 = 50
x2 = -1
y2 = -1
for y in range(N):
grid.append(list(map(int, input())))
for x, num in enumerate(grid[-1]):
if num == 4:
x1 = min(x1, x)
y1 = min(y1, y)
x2 = max(x2, x)
y2 = max(y2, y)
if x1 == 51:
print('No')
else:
for y in range(N):
for x in range(N):
ex = 0
if x1 <= x <= x2 and y1 <= y <= y2:
ex = 4
elif (x == x1-1 or x == x2+1) and y1 <= y <= y2:
ex = 2
elif (y == y1-1 or y == y2+1) and x1 <= x <= x2:
ex = 2
elif (x == x1-1 or x == x2+1) and (y == y1-1 or y == y2+1):
ex = 1
if ex != grid[y][x]:
print('No')
break
else:
continue
break
else:
print('Yes')
``` | vfc_16018 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/690/B1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n000000\n000000\n012100\n024200\n012100\n000000\n",
"output": "Yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n000000\n012210\n024420\n012210\n000000\n000000\n",
"output": "Yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n000100\n001210\n002420\n001210\n000000\n000000\n",
"output": "No\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n0000000000\n0122210000\n0244420100\n0122210000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n",
"output": "No\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0012100000\n0024200000\n0012100000\n0000000000\n",
"output": "Yes\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1567 | Solve the following coding problem using the programming language python:
We define $x \bmod y$ as the remainder of division of $x$ by $y$ ($\%$ operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers $[a_1, a_2, \dots, a_k]$ stable if for every permutation $p$ of integers from $1$ to $k$, and for every non-negative integer $x$, the following condition is met:
$ (((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k = (((x \bmod a_{p_1}) \bmod a_{p_2}) \dots \bmod a_{p_{k - 1}}) \bmod a_{p_k} $
That is, for each non-negative integer $x$, the value of $(((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k$ does not change if we reorder the elements of the array $a$.
For two given integers $n$ and $k$, calculate the number of stable arrays $[a_1, a_2, \dots, a_k]$ such that $1 \le a_1 < a_2 < \dots < a_k \le n$.
-----Input-----
The only line contains two integers $n$ and $k$ ($1 \le n, k \le 5 \cdot 10^5$).
-----Output-----
Print one integer — the number of stable arrays $[a_1, a_2, \dots, a_k]$ such that $1 \le a_1 < a_2 < \dots < a_k \le n$. Since the answer may be large, print it modulo $998244353$.
-----Examples-----
Input
7 3
Output
16
Input
3 7
Output
0
Input
1337 42
Output
95147305
Input
1 1
Output
1
Input
500000 1
Output
500000
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def modfac(n, MOD):
f = 1
factorials = [1]
for m in range(1, n + 1):
f *= m
f %= MOD
factorials.append(f)
inv = pow(f, MOD - 2, MOD)
invs = [1] * (n + 1)
invs[n] = inv
for m in range(n, 1, -1):
inv *= m
inv %= MOD
invs[m - 1] = inv
return factorials, invs
def modnCr(n,r,mod,fac,inv):
return fac[n] * inv[n-r] * inv[r] % mod
n,k = map(int,input().split())
mod = 998244353
fac,inv = modfac(n+10,mod)
ans = 0
for i in range(1,n+1):
rem = n // i - 1
if rem >= k-1:
ans += modnCr(rem,k-1,mod,fac,inv)
ans %= mod
print (ans)
``` | vfc_16022 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1359/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 3\n",
"output": "16\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1568 | Solve the following coding problem using the programming language python:
There are n incoming messages for Vasya. The i-th message is going to be received after t_{i} minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.
Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.
Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.
Determine the maximum amount of money Vasya's bank account can hold after T minutes.
-----Input-----
The first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000).
The second string contains n integers t_{i} (1 ≤ t_{i} ≤ T).
-----Output-----
Output one integer — the answer to the problem.
-----Examples-----
Input
4 5 5 3 5
1 5 5 4
Output
20
Input
5 3 1 1 3
2 2 2 1 1
Output
15
Input
5 5 3 4 5
1 2 3 4 5
Output
35
-----Note-----
In the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total.
In the second sample the messages can be read at any integer moment.
In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 = - 5 points. This is 35 in total.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, a, b, c, t = list(map(int, input().split()))
lst = []
for x in input().split():
lst.append(int(x))
if b > c:
print(n * a)
else:
acc = 0
for x in lst:
acc += (t - x)
acc *= (c - b)
acc += n * a
print(acc)
``` | vfc_16026 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/964/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 5 5 3 5\n1 5 5 4\n",
"output": "20\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3 1 1 3\n2 2 2 1 1\n",
"output": "15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5 3 4 5\n1 2 3 4 5\n",
"output": "35\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 6 4 3 9\n2\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 9 7 5 3\n3 3 3 3 2 3 2 2 3 3\n",
"output": "90\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "44 464 748 420 366\n278 109 293 161 336 9 194 203 13 226 303 303 300 131 134 47 235 110 263 67 185 337 360 253 270 97 162 190 143 267 18 311 329 138 322 167 324 33 3 104 290 260 349 89\n",
"output": "20416\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1570 | Solve the following coding problem using the programming language python:
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
-----Input-----
The first line contains three positive integers k, n, w (1 ≤ k, w ≤ 1000, 0 ≤ n ≤ 10^9), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants.
-----Output-----
Output one integer — the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.
-----Examples-----
Input
3 17 4
Output
13
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
k,n,w = map(int,input().split())
x = (w)*(w+1)//2 * k
y = x - n
if(y >= 0):
print(y)
else:
print(0)
``` | vfc_16034 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/546/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 17 4\n",
"output": "13",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1571 | Solve the following coding problem using the programming language python:
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. [Image]
Kaavi has a string $T$ of length $m$ and all the strings with the prefix $T$ are magic spells. Kaavi also has a string $S$ of length $n$ and an empty string $A$.
During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: Delete the first character of $S$ and add it at the front of $A$. Delete the first character of $S$ and add it at the back of $A$.
Kaavi can perform no more than $n$ operations. To finish the divination, she wants to know the number of different operation sequences to make $A$ a magic spell (i.e. with the prefix $T$). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo $998\,244\,353$.
Two operation sequences are considered different if they are different in length or there exists an $i$ that their $i$-th operation is different.
A substring is a contiguous sequence of characters within a string. A prefix of a string $S$ is a substring of $S$ that occurs at the beginning of $S$.
-----Input-----
The first line contains a string $S$ of length $n$ ($1 \leq n \leq 3000$).
The second line contains a string $T$ of length $m$ ($1 \leq m \leq n$).
Both strings contain only lowercase Latin letters.
-----Output-----
The output contains only one integer — the answer modulo $998\,244\,353$.
-----Examples-----
Input
abab
ba
Output
12
Input
defineintlonglong
signedmain
Output
0
Input
rotator
rotator
Output
4
Input
cacdcdbbbb
bdcaccdbbb
Output
24
-----Note-----
The first test:
$\text{baba abab bbaa baab baab}$
The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of $A$, although the results are the same, they are considered as different operations. So the answer is $6\times2=12$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
S = input()
T = input()
base = 998244353
dp = [[0 for _ in range(len(S) + 1)] for _ in range(len(S) + 1)]
for j in range(1, len(S) + 1):
if (j > len(T)) or (S[0] == T[j - 1]):
dp[1][j] = 2
for i in range(2, len(S) + 1):
for j in range(1, len(S) - i + 1 + 1):
if (j > len(T)) or (S[i - 1] == T[j - 1]):
dp[i][j] = (dp[i][j] + dp[i - 1][j + 1]) % base
if (j + i - 1 > len(T)) or (S[i - 1] == T[j + i - 1 - 1]):
dp[i][j] = (dp[i][j] + dp[i - 1][j]) % base
ans = 0
for i in range(len(T), len(S) + 1):
ans = (ans + dp[i][1]) % base
print(ans)
``` | vfc_16038 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1337/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "abab\nba\n",
"output": "12",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "defineintlonglong\nsignedmain\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "rotator\nrotator\n",
"output": "4",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1572 | Solve the following coding problem using the programming language python:
You have array a_1, a_2, ..., a_{n}. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good if a_{i} = a_{i} - 1 + a_{i} - 2, for all i (l + 2 ≤ i ≤ r).
Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l_1, r_1], is longer than segment [l_2, r_2], if len([l_1, r_1]) > len([l_2, r_2]).
Your task is to find a good segment of the maximum length in array a. Note that a segment of length 1 or 2 is always good.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of elements in the array. The second line contains integers: a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9).
-----Output-----
Print the length of the longest good segment in array a.
-----Examples-----
Input
10
1 2 3 5 8 13 21 34 55 89
Output
10
Input
5
1 1 1 1 1
Output
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())
L=list(map(int,input().split()))
if(n==1 or n==2):
print(n)
else:
length=2
i=2
maxx=2
while(i<n):
if(L[i]==L[i-1]+L[i-2]):
length+=1
else:
if(length>maxx):
maxx=length
length=2
i+=1
if(length>maxx):
maxx=length
print(maxx)
``` | vfc_16042 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/365/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10\n1 2 3 5 8 13 21 34 55 89\n",
"output": "10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1573 | Solve the following coding problem using the programming language python:
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
-----Input-----
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 10^5, $1 \leq d \leq 10^{9}$) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type m_{i}, s_{i} (0 ≤ m_{i}, s_{i} ≤ 10^9) — the amount of money and the friendship factor, respectively.
-----Output-----
Print the maximum total friendship factir that can be reached.
-----Examples-----
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
-----Note-----
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
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 namedtuple
from operator import itemgetter
Friend = namedtuple("Friend", "m s")
n, d = list(map(int, input().split()))
f = [ ]
for i in range(n):
f.append(Friend(*list(map(int, input().split()))))
f.sort(key=itemgetter(0))
left = 0
cur = f[0].s
result = cur
for i, fr in enumerate(f[1:], 1):
while left < i and f[left].m + d <= fr.m:
cur -= f[left].s
left += 1
cur += fr.s
result = max(result, cur)
print(result)
``` | vfc_16046 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/580/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 5\n75 5\n0 100\n150 20\n75 1\n",
"output": "100\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 100\n0 7\n11 32\n99 10\n46 8\n87 54\n",
"output": "111\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1000000000\n15 12\n",
"output": "12\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1575 | Solve the following coding problem using the programming language python:
Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow.
He knows that the receptionist starts working after t_{s} minutes have passed after midnight and closes after t_{f} minutes have passed after midnight (so that (t_{f} - 1) is the last minute when the receptionist is still working). The receptionist spends exactly t minutes on each person in the queue. If the receptionist would stop working within t minutes, he stops serving visitors (other than the one he already serves).
Vasya also knows that exactly n visitors would come tomorrow. For each visitor Vasya knows the point of time when he would come to the passport office. Each visitor queues up and doesn't leave until he was served. If the receptionist is free when a visitor comes (in particular, if the previous visitor was just served and the queue is empty), the receptionist begins to serve the newcomer immediately. [Image] "Reception 1"
For each visitor, the point of time when he would come to the passport office is positive. Vasya can come to the office at the time zero (that is, at midnight) if he needs so, but he can come to the office only at integer points of time. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and stand in the queue after the last of them.
Vasya wants to come at such point of time that he will be served by the receptionist, and he would spend the minimum possible time in the queue. Help him!
-----Input-----
The first line contains three integers: the point of time when the receptionist begins to work t_{s}, the point of time when the receptionist stops working t_{f} and the time the receptionist spends on each visitor t. The second line contains one integer n — the amount of visitors (0 ≤ n ≤ 100 000). The third line contains positive integers in non-decreasing order — the points of time when the visitors arrive to the passport office.
All times are set in minutes and do not exceed 10^12; it is guaranteed that t_{s} < t_{f}. It is also guaranteed that Vasya can arrive at the passport office at such a point of time that he would be served by the receptionist.
-----Output-----
Print single non-negative integer — the point of time when Vasya should arrive at the passport office. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and queues up the last. If there are many answers, you can print any of them.
-----Examples-----
Input
10 15 2
2
10 13
Output
12
Input
8 17 3
4
3 4 5 8
Output
2
-----Note-----
In the first example the first visitor comes exactly at the point of time when the receptionist begins to work, and he is served for two minutes. At 12 minutes after the midnight the receptionist stops serving the first visitor, and if Vasya arrives at this moment, he will be served immediately, because the next visitor would only come at 13 minutes after midnight.
In the second example, Vasya has to come before anyone else to be served.
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
arrival, departure, time_per_client = [int(x) for x in input().split()]
num_clients = int(input())
if num_clients > 0:
clients_arrival = [int(x) for x in input().split()]
else:
print(arrival)
return
best_time = None
current_time = arrival
clients_at_queue = 0
client_to_arrive = 0
client_wait_time = [math.inf for client in clients_arrival]
client_to_leave = 0
while current_time <= departure - time_per_client:
while client_to_arrive < num_clients and clients_arrival[client_to_arrive] <= current_time:
clients_at_queue += 1
client_to_arrive += 1
if clients_at_queue == 0:
best_time = current_time
break
else:
clients_at_queue -= 1
client_wait_time[client_to_leave] = current_time - clients_arrival[client_to_leave]
client_to_leave += 1
current_time += time_per_client
while (best_time is None or best_time < 0) and len(client_wait_time) > 0:
happiest_client = client_wait_time.index(min(client_wait_time))
best_time = clients_arrival[happiest_client] - 1
if best_time < 0:
client_wait_time = client_wait_time[happiest_client+1:]
clients_arrival = clients_arrival[happiest_client+1:]
print(best_time)
``` | vfc_16054 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/767/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 15 2\n2\n10 13\n",
"output": "12",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1576 | Solve the following coding problem using the programming language python:
Polycarp loves ciphers. He has invented his own cipher called Right-Left.
Right-Left cipher is used for strings. To encrypt the string $s=s_{1}s_{2} \dots s_{n}$ Polycarp uses the following algorithm: he writes down $s_1$, he appends the current word with $s_2$ (i.e. writes down $s_2$ to the right of the current result), he prepends the current word with $s_3$ (i.e. writes down $s_3$ to the left of the current result), he appends the current word with $s_4$ (i.e. writes down $s_4$ to the right of the current result), he prepends the current word with $s_5$ (i.e. writes down $s_5$ to the left of the current result), and so on for each position until the end of $s$.
For example, if $s$="techno" the process is: "t" $\to$ "te" $\to$ "cte" $\to$ "cteh" $\to$ "ncteh" $\to$ "ncteho". So the encrypted $s$="techno" is "ncteho".
Given string $t$ — the result of encryption of some string $s$. Your task is to decrypt it, i.e. find the string $s$.
-----Input-----
The only line of the input contains $t$ — the result of encryption of some string $s$. It contains only lowercase Latin letters. The length of $t$ is between $1$ and $50$, inclusive.
-----Output-----
Print such string $s$ that after encryption it equals $t$.
-----Examples-----
Input
ncteho
Output
techno
Input
erfdcoeocs
Output
codeforces
Input
z
Output
z
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
def main():
s = deque(input())
res = []
for i in range(len(s) - 1, -1, -1):
if i % 2 == 1:
res.append(s.pop())
else:
res.append(s.popleft())
print(''.join(res[::-1]))
main()
``` | vfc_16058 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1085/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "ncteho\n",
"output": "techno\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "erfdcoeocs\n",
"output": "codeforces\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "z\n",
"output": "z\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "bz\n",
"output": "bz\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "tea\n",
"output": "eat\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1577 | Solve the following coding problem using the programming language python:
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played.
The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.
-----Output-----
If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output.
If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output.
If Anton and Danik won the same number of games, print "Friendship" (without quotes).
-----Examples-----
Input
6
ADAAAA
Output
Anton
Input
7
DDDAADA
Output
Danik
Input
6
DADADA
Output
Friendship
-----Note-----
In the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".
In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".
In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".
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()
a = s.count('A')
d = s.count('D')
if a > d:
print("Anton")
elif d > a:
print("Danik")
else:
print("Friendship")
``` | vfc_16062 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/734/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\nADAAAA\n",
"output": "Anton\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1588 | Solve the following coding problem using the programming language python:
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.
There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds: $\sum_{x \in X}(x - 1) = \sum_{y \in Y}(s - y)$ "Are you kidding me?", asks Chris.
For example, consider a case where s = 8 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7.
$\left. \begin{array}{l l l l l l}{1} & {2} & {3} & {4} & {5} & {6} & {7} & {8} \end{array} \right.$
However, now Chris has exactly s = 10^6 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!
-----Input-----
The first line of input contains a single integer n (1 ≤ n ≤ 5·10^5), the number of blocks in the set X. The next line contains n distinct space-separated integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^6), the numbers of the blocks in X.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
-----Output-----
In the first line of output print a single integer m (1 ≤ m ≤ 10^6 - n), the number of blocks in the set Y. In the next line output m distinct space-separated integers y_1, y_2, ..., y_{m} (1 ≤ y_{i} ≤ 10^6), such that the required equality holds. The sets X and Y should not intersect, i.e. x_{i} ≠ y_{j} for all i, j (1 ≤ i ≤ n; 1 ≤ j ≤ m). It is guaranteed that at least one solution always exists. If there are multiple solutions, output any of them.
-----Examples-----
Input
3
1 4 5
Output
2
999993 1000000
Input
1
1
Output
1
1000000
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 solve():
n = int(input())
s = 1000000
xset = set(map(int, input().split()))
res = set()
wantother = 0
for i in range(1, s + 1):
opposite = s - i + 1
if i in xset:
if opposite not in xset:
res.add(opposite)
else:
wantother+=1
wantother /= 2
for i in range(1, s + 1):
if wantother == 0: break
opposite = s - i + 1
if i not in res and opposite not in res and i not in xset and opposite not in xset:
res.add(i)
res.add(opposite)
wantother-=1
print(len(res))
return " ".join(map(str, res))
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())
``` | vfc_16106 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/405/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 4 5\n",
"output": "3\n999996 999997 1000000 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "1\n1000000 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000\n",
"output": "1\n1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 999999\n",
"output": "2\n1 1000000 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1590 | Solve the following coding problem using the programming language python:
You are given an array $a_1, a_2, \dots, a_n$. All $a_i$ are pairwise distinct.
Let's define function $f(l, r)$ as follows: let's define array $b_1, b_2, \dots, b_{r - l + 1}$, where $b_i = a_{l - 1 + i}$; sort array $b$ in increasing order; result of the function $f(l, r)$ is $\sum\limits_{i = 1}^{r - l + 1}{b_i \cdot i}$.
Calculate $\left(\sum\limits_{1 \le l \le r \le n}{f(l, r)}\right) \mod (10^9+7)$, i.e. total sum of $f$ for all subsegments of $a$ modulo $10^9+7$.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 5 \cdot 10^5$) — the length of array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$, $a_i \neq a_j$ for $i \neq j$) — array $a$.
-----Output-----
Print one integer — the total sum of $f$ for all subsegments of $a$ modulo $10^9+7$
-----Examples-----
Input
4
5 2 4 7
Output
167
Input
3
123456789 214365879 987654321
Output
582491518
-----Note-----
Description of the first example: $f(1, 1) = 5 \cdot 1 = 5$; $f(1, 2) = 2 \cdot 1 + 5 \cdot 2 = 12$; $f(1, 3) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 = 25$; $f(1, 4) = 2 \cdot 1 + 4 \cdot 2 + 5 \cdot 3 + 7 \cdot 4 = 53$; $f(2, 2) = 2 \cdot 1 = 2$; $f(2, 3) = 2 \cdot 1 + 4 \cdot 2 = 10$; $f(2, 4) = 2 \cdot 1 + 4 \cdot 2 + 7 \cdot 3 = 31$; $f(3, 3) = 4 \cdot 1 = 4$; $f(3, 4) = 4 \cdot 1 + 7 \cdot 2 = 18$; $f(4, 4) = 7 \cdot 1 = 7$;
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
MOD = (int)(1e9+7)
def add(a, b):
a += b
if a >= MOD: a -= MOD
return a
def mul(a, b):
return (a * b) % MOD
class fenwickTree:
def __init__(self, max_val):
self.max_val = max_val + 5
self.tree = [0] * self.max_val
def update(self, idx, value):
idx += 1
while idx < self.max_val:
self.tree[idx] = add(self.tree[idx], value)
idx += (idx & (-idx))
def read(self, idx):
idx += 1
res = 0
while idx > 0:
res = add(res, self.tree[idx])
idx -= (idx & (-idx))
return res
inp = [int(x) for x in sys.stdin.read().split()]
n = inp[0]
a = []
for i in range(1, n + 1):
a.append(inp[i])
sorted_array = sorted(a)
dict = {}
for i in range(n):
dict[sorted_array[i]] = i
factor = [0] * n
for i in range(0, n):
factor[i] = mul(i + 1, n - i)
left_tree = fenwickTree(n)
for i in range(0, n):
element_idx = dict[a[i]]
factor[i] = add(factor[i], mul(n - i, left_tree.read(element_idx)))
left_tree.update(element_idx, i + 1)
right_tree = fenwickTree(n)
for i in range(n - 1, -1, -1):
element_idx = dict[a[i]]
factor[i] = add(factor[i], mul(i + 1, right_tree.read(element_idx)))
right_tree.update(element_idx, n - i)
ans = 0
for i in range(n):
ans = add(ans, mul(a[i], factor[i]))
print(ans)
``` | vfc_16114 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1167/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n5 2 4 7\n",
"output": "167\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n123456789 214365879 987654321\n",
"output": "582491518\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1591 | Solve the following coding problem using the programming language python:
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?
There are $n$ students living in a building, and for each of them the favorite drink $a_i$ is known. So you know $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ ($1 \le a_i \le k$) is the type of the favorite drink of the $i$-th student. The drink types are numbered from $1$ to $k$.
There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $k$ types of drink sets, the $j$-th type contains two portions of the drink $j$. The available number of sets of each of the $k$ types is infinite.
You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $\lceil \frac{n}{2} \rceil$, where $\lceil x \rceil$ is $x$ rounded up.
After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $n$ is odd then one portion will remain unused and the students' teacher will drink it.
What is the maximum number of students that can get their favorite drink if $\lceil \frac{n}{2} \rceil$ sets will be chosen optimally and students will distribute portions between themselves optimally?
-----Input-----
The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 1\,000$) — the number of students in the building and the number of different drinks.
The next $n$ lines contain student's favorite drinks. The $i$-th line contains a single integer from $1$ to $k$ — the type of the favorite drink of the $i$-th student.
-----Output-----
Print exactly one integer — the maximum number of students that can get a favorite drink.
-----Examples-----
Input
5 3
1
3
1
1
2
Output
4
Input
10 3
2
1
3
2
3
3
1
3
1
2
Output
9
-----Note-----
In the first example, students could choose three sets with drinks $1$, $1$ and $2$ (so they will have two sets with two drinks of the type $1$ each and one set with two drinks of the type $2$, so portions will be $1, 1, 1, 1, 2, 2$). This way all students except the second one will get their favorite drinks.
Another possible answer is sets with drinks $1$, $2$ and $3$. In this case the portions will be $1, 1, 2, 2, 3, 3$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $a_i = 1$ (i.e. the first, the third or the fourth).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
cnt = [0] * k
for i in range(n):
cnt[int(input()) - 1] += 1
dead = 0
ans = 0
for i in cnt:
if i & 1:
dead += 1
ans += i - 1
else:
ans += i
if n & 1:
print(ans + (dead + 1) // 2)
else:
print(ans + dead // 2)
return 0
main()
``` | vfc_16118 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1195/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 3\n1\n3\n1\n1\n2\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 3\n2\n1\n3\n2\n3\n3\n1\n3\n1\n2\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n1\n9\n7\n6\n2\n4\n7\n8\n1\n3\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1000\n548\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1592 | Solve the following coding problem using the programming language python:
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers t_{i} and c_{i} — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^3) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers t_{i} and c_{i} (1 ≤ t_{i}, c_{i} ≤ 10^6) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, t_{i} < t_{i} + 1 for all integer i (1 ≤ i < n).
-----Output-----
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
-----Examples-----
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
-----Note-----
In the first test sample:
second 1: the first message has appeared in the queue, the queue's size is 1; second 2: the first message is sent, the second message has been received, the queue's size is 1; second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import re
import itertools
from collections import Counter, deque
class Task:
tasks = []
answer = ""
def getData(self):
numberOfTasks = int(input())
for i in range(0, numberOfTasks):
self.tasks += [[int(x) for x in input().split(' ')]]
#inFile = open('input.txt', 'r')
#inFile.readline().rstrip()
#self.childs = inFile.readline().rstrip()
def solve(self):
queueSize, maxQueueSize = 0, 0
time, timeOfLastMessage = 1, 1
currentTask = 0
while currentTask < len(self.tasks) or queueSize > 0:
maxQueueSize = max(maxQueueSize, queueSize)
if currentTask < len(self.tasks):
timeDelta = self.tasks[currentTask][0] - time
queueSize -= min(queueSize, timeDelta)
time += timeDelta
else:
timeOfLastMessage = time + queueSize
break
if currentTask < len(self.tasks) and \
self.tasks[currentTask][0] == time:
queueSize += self.tasks[currentTask][1]
currentTask += 1
self.answer = str(timeOfLastMessage) + " " + str(maxQueueSize)
def printAnswer(self):
print(self.answer)
#outFile = open('output.txt', 'w')
#outFile.write(self.answer)
task = Task()
task.getData()
task.solve()
task.printAnswer()
``` | vfc_16122 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/292/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 1\n2 1\n",
"output": "3 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000 10\n",
"output": "1000010 10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1595 | Solve the following coding problem using the programming language python:
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.
Fortunately, Picks remembers something about his set S: its elements were distinct integers from 1 to limit; the value of $\sum_{x \in S} \text{lowbit}(x)$ was equal to sum; here lowbit(x) equals 2^{k} where k is the position of the first one in the binary representation of x. For example, lowbit(10010_2) = 10_2, lowbit(10001_2) = 1_2, lowbit(10000_2) = 10000_2 (binary representation).
Can you help Picks and find any set S, that satisfies all the above conditions?
-----Input-----
The first line contains two integers: sum, limit (1 ≤ sum, limit ≤ 10^5).
-----Output-----
In the first line print an integer n (1 ≤ n ≤ 10^5), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them.
If it's impossible to find a suitable set, print -1.
-----Examples-----
Input
5 5
Output
2
4 5
Input
4 3
Output
3
2 3 1
Input
5 1
Output
-1
-----Note-----
In sample test 1: lowbit(4) = 4, lowbit(5) = 1, 4 + 1 = 5.
In sample test 2: lowbit(1) = 1, lowbit(2) = 2, lowbit(3) = 1, 1 + 2 + 1 = 4.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
(a, b), x, y = list(map(int, input().split())), [], 0
def bin(s):
return str(s) if s <= 1 else bin(s >> 1) + str(s & 1)
def lowbit(s):
return int('1' + bin(s).split('1')[-1], 2)
for i in reversed(range(b + 1)):
if y == a:
break
if a >= y + lowbit(i):
x.append(i)
y += lowbit(i)
if y == a:
print( len(x) )
print( ' '.join(str(i) for i in x) )
else:
print( -1 )
``` | vfc_16134 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/437/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 5\n",
"output": "2\n4 5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3\n",
"output": "3\n2 3 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 1\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 100000\n",
"output": "1\n99999\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "96024 12472\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "21741 3575\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1596 | Solve the following coding problem using the programming language python:
Constanze is the smartest girl in her village but she has bad eyesight.
One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe "code" onto the paper. Thanks to this machine, she can finally write messages without using her glasses.
However, her dumb friend Akko decided to play a prank on her. Akko tinkered with the machine so that if you pronounce 'w', it will inscribe "uu" instead of "w", and if you pronounce 'm', it will inscribe "nn" instead of "m"! Since Constanze had bad eyesight, she was not able to realize what Akko did.
The rest of the letters behave the same as before: if you pronounce any letter besides 'w' and 'm', the machine will just inscribe it onto a piece of paper.
The next day, I received a letter in my mailbox. I can't understand it so I think it's either just some gibberish from Akko, or Constanze made it using her machine. But since I know what Akko did, I can just list down all possible strings that Constanze's machine would have turned into the message I got and see if anything makes sense.
But I need to know how much paper I will need, and that's why I'm asking you for help. Tell me the number of strings that Constanze's machine would've turned into the message I got.
But since this number can be quite large, tell me instead its remainder when divided by $10^9+7$.
If there are no strings that Constanze's machine would've turned into the message I got, then print $0$.
-----Input-----
Input consists of a single line containing a string $s$ ($1 \leq |s| \leq 10^5$) — the received message. $s$ contains only lowercase Latin letters.
-----Output-----
Print a single integer — the number of strings that Constanze's machine would've turned into the message $s$, modulo $10^9+7$.
-----Examples-----
Input
ouuokarinn
Output
4
Input
banana
Output
1
Input
nnn
Output
3
Input
amanda
Output
0
-----Note-----
For the first example, the candidate strings are the following: "ouuokarinn", "ouuokarim", "owokarim", and "owokarinn".
For the second example, there is only one: "banana".
For the third example, the candidate strings are the following: "nm", "mn" and "nnn".
For the last example, there are no candidate strings that the machine can turn into "amanda", since the machine won't inscribe 'm'.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from itertools import groupby
s = input()
n = len(s)
if "w" in s or "m" in s:
print("0")
return
mod = 10**9+7
fib = [1, 1]
for i in range(2, n+1):
fib.append((fib[-1]+fib[-2])%mod)
res = 1
for k, g in groupby(s):
if k=="u" or k=="n":
l = len(list(g))
res *= fib[l]
res %= mod
print(res)
``` | vfc_16138 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1245/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "ouuokarinn\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "banana\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "nnn\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "amanda\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "a\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "uuunnnuuunnn\n",
"output": "81\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1597 | Solve the following coding problem using the programming language python:
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.
There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as $\operatorname{lcp}(a, b)$. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.
Find the matching between students and pseudonyms with the maximum quality.
-----Input-----
The first line contains number n (1 ≤ n ≤ 100 000) — the number of students in the summer school.
Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.
The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.
The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
-----Output-----
In the first line print the maximum possible quality of matching pseudonyms to students.
In the next n lines describe the optimal matching. Each line must have the form a b (1 ≤ a, b ≤ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.
The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
-----Examples-----
Input
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel
Output
11
4 1
2 5
1 3
5 2
3 4
-----Note-----
The first test from the statement the match looks as follows: bill → bilbo (lcp = 3) galya → galadriel (lcp = 3) gennady → gendalf (lcp = 3) toshik → torin (lcp = 2) boris → smaug (lcp = 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
SIGMA = 26
nodes = []
pairs = []
res = 0
class Node:
def __init__(self):
self.ch = {}
self.a = []
self.b = []
self.d = 0
def add(self, s, i):
t = self
for c in s:
v = ord(c) - ord('a')
if not v in t.ch:
t.ch[v] = Node()
t.ch[v].d = t.d + 1
nodes.append(t.ch[v])
t = t.ch[v]
t.a.append(i)
def inc(self, s, i):
t = self
for c in s:
v = ord(c) - ord('a')
if not v in t.ch:
break
t = t.ch[v]
t.b.append(i)
def solve(self):
nonlocal pairs
nonlocal res
for i in range(SIGMA):
if i in self.ch:
self.a.extend(self.ch[i].a)
self.b.extend(self.ch[i].b)
k = min(len(self.a), len(self.b))
for i in range(k):
pairs.append(str(self.a[-1]) + ' ' + str(self.b[-1]))
self.a.pop()
self.b.pop()
res += self.d
return res
sys.setrecursionlimit(2000000)
_input = sys.stdin.readlines()
_input = [s[:-1] for s in _input]
N = int(_input[0])
A = _input[1 : N + 1]
B = _input[N + 1 :]
T = Node()
nodes.append(T)
for i, s in enumerate(A):
T.add(s, i + 1)
for i, s in enumerate(B):
T.inc(s, i + 1)
for n in reversed(nodes):
n.solve()
print(res)
print('\n'.join(pairs))
``` | vfc_16142 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/566/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\ngennady\ngalya\nboris\nbill\ntoshik\nbilbo\ntorin\ngendalf\nsmaug\ngaladriel\n",
"output": "11\n4 1\n2 5\n1 3\n5 2\n3 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\na\na\n",
"output": "1\n1 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\na\na\na\na\n",
"output": "2\n1 1\n2 2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1598 | Solve the following coding problem using the programming language python:
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string $s$ (a string which consists of zeroes and ones) of length $n$ and he is asking you to find a binary string $t$ of the same length which satisfies the following conditions:
For any $l$ and $r$ ($1 \leq l \leq r \leq n$) the length of the longest non-decreasing subsequence of the substring $s_{l}s_{l+1} \ldots s_{r}$ is equal to the length of the longest non-decreasing subsequence of the substring $t_{l}t_{l+1} \ldots t_{r}$;
The number of zeroes in $t$ is the maximum possible.
A non-decreasing subsequence of a string $p$ is a sequence of indices $i_1, i_2, \ldots, i_k$ such that $i_1 < i_2 < \ldots < i_k$ and $p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$. The length of the subsequence is $k$.
If there are multiple substrings which satisfy the conditions, output any.
-----Input-----
The first line contains a binary string of length not more than $2\: 000$.
-----Output-----
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
-----Examples-----
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
-----Note-----
In the first example:
For the substrings of the length $1$ the length of the longest non-decreasing subsequnce is $1$; For $l = 1, r = 2$ the longest non-decreasing subsequnce of the substring $s_{1}s_{2}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{2}$ is $01$; For $l = 1, r = 3$ the longest non-decreasing subsequnce of the substring $s_{1}s_{3}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{3}$ is $00$; For $l = 2, r = 3$ the longest non-decreasing subsequnce of the substring $s_{2}s_{3}$ is $1$ and the longest non-decreasing subsequnce of the substring $t_{2}t_{3}$ is $1$;
The second example is similar to the first one.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = list(map(int, input()))
ans = []
cnt = 0
if s[0] == 1:
cnt += 1
else:
ans.append('0')
for i in range(1, len(s)):
if s[i] == 0 and s[i - 1] == 0:
ans.append('0')
elif s[i] == 1:
cnt += 1
else:
maba = 0
b = 0
for x in range(i, len(s)):
if s[x] == 1:
b -= 1
else:
b += 1
maba = max(maba, b)
maba = min(maba, cnt)
for _ in range(cnt - maba):
ans.append('0')
for _ in range(maba):
ans.append('1')
cnt = 0
ans.append('0')
for _ in range(len(s) - len(ans)):
ans.append('0')
print(''.join(ans))
``` | vfc_16146 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1204/D1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "110\n",
"output": "010\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "010\n",
"output": "010\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0001111\n",
"output": "0000000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1599 | Solve the following coding problem using the programming language python:
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string s = s_1s_2... s_{n} (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers l_{i}, r_{i} (1 ≤ l_{i} < r_{i} ≤ n). The answer to the query l_{i}, r_{i} is the number of such integers i (l_{i} ≤ i < r_{i}), that s_{i} = s_{i} + 1.
Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
-----Input-----
The first line contains string s of length n (2 ≤ n ≤ 10^5). It is guaranteed that the given string only consists of characters "." and "#".
The next line contains integer m (1 ≤ m ≤ 10^5) — the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers l_{i}, r_{i} (1 ≤ l_{i} < r_{i} ≤ n).
-----Output-----
Print m integers — the answers to the queries in the order in which they are given in the input.
-----Examples-----
Input
......
4
3 4
2 3
1 6
2 6
Output
1
1
5
4
Input
#..###
5
1 3
5 6
1 5
3 6
3 4
Output
1
1
2
2
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s=input()
t=int(input())
ans=[]
n=len(s)
clue=[0]*n
for i in range(n-1):
if(s[i]==s[i+1]):
clue[i]+=1
L=[clue[0]]
for i in range(1,n):
L.append(L[i-1]+clue[i])
for i in range(t):
A,B=input().split()
A=int(A)-1
B=int(B)-1
r=0
x=L[B-1]
y=L[A-1]
if(A-1<0):
y=0
ans.append(x-y)
for i in range(t):
print(ans[i])
``` | vfc_16150 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/313/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "......\n4\n3 4\n2 3\n1 6\n2 6\n",
"output": "1\n1\n5\n4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1600 | Solve the following coding problem using the programming language python:
One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.
At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the height of the i-th castle is equal to h_{i}. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition h_{i} ≤ h_{i} + 1 holds for all i from 1 to n - 1.
Squidward suggested the following process of sorting castles: Castles are split into blocks — groups of consecutive castles. Therefore the block from i to j will include castles i, i + 1, ..., j. A block may consist of a single castle. The partitioning is chosen in such a way that every castle is a part of exactly one block. Each block is sorted independently from other blocks, that is the sequence h_{i}, h_{i} + 1, ..., h_{j} becomes sorted. The partitioning should satisfy the condition that after each block is sorted, the sequence h_{i} becomes sorted too. This may always be achieved by saying that the whole sequence is a single block.
Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of castles Spongebob, Patrick and Squidward made from sand during the day.
The next line contains n integers h_{i} (1 ≤ h_{i} ≤ 10^9). The i-th of these integers corresponds to the height of the i-th castle.
-----Output-----
Print the maximum possible number of blocks in a valid partitioning.
-----Examples-----
Input
3
1 2 3
Output
3
Input
4
2 1 3 2
Output
2
-----Note-----
In the first sample the partitioning looks like that: [1][2][3].
[Image]
In the second sample the partitioning is: [2, 1][3, 2]
[Image]
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 collections import Counter
n = int(input())
h_u = tuple(map(int, input().split()))
h_s = sorted(h_u)
i = 0
a = Counter()
b = Counter()
num_partitions = 0
for i in range(n):
a[h_u[i]] += 1
b[h_s[i]] += 1
if (a == b):
num_partitions += 1
a = Counter()
b = Counter()
print(num_partitions)
``` | vfc_16154 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/599/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2 1 3 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "17\n1 45 22 39 28 23 23 100 500 778 777 778 1001 1002 1005 1003 1005\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "101\n1 50 170 148 214 153 132 234 181 188 180 225 226 200 197 122 181 168 87 220 223 160 235 94 257 145 199 235 102 146 119 60 109 134 209 260 210 191 180 271 236 195 155 169 166 143 246 102 208 137 278 269 156 251 198 165 111 198 151 213 256 121 276 163 179 285 104 99 139 122 188 184 215 242 244 115 304 259 135 149 104 72 303 291 124 237 112 165 183 168 71 139 85 131 137 107 120 267 235 337 69\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 2 2 2 2 2 2 2 2 1\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1602 | Solve the following coding problem using the programming language python:
Anu has created her own function $f$: $f(x, y) = (x | y) - y$ where $|$ denotes the bitwise OR operation. For example, $f(11, 6) = (11|6) - 6 = 15 - 6 = 9$. It can be proved that for any nonnegative numbers $x$ and $y$ value of $f(x, y)$ is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array $[a_1, a_2, \dots, a_n]$ is defined as $f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$). Elements of the array are not guaranteed to be different.
-----Output-----
Output $n$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
-----Examples-----
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
-----Note-----
In the first testcase, value of the array $[11, 6, 4, 0]$ is $f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$.
$[11, 4, 0, 6]$ is also a valid answer.
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 = int(sys.stdin.readline().strip())
a = list(map(int, sys.stdin.readline().strip().split()))
b = a[:]
C = [0] * n
x = [0] * n
for i in range (0, 40):
for j in range (0, n):
x[j] = b[j] % 2
b[j] = b[j] // 2
if sum(x) == 1:
for j in range (0, n):
if x[j] == 1:
C[j] = C[j] + 2 ** i
l = C.index(max(C))
print(" ".join(list(map(str, [a[l]]+a[0:l]+a[l+1:]))))
``` | vfc_16162 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1300/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n4 0 11 6\n",
"output": "11 6 4 0 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n13\n",
"output": "13 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n315479581 954336048 124252105 880492165 179952043\n",
"output": "124252105 880492165 954336048 315479581 179952043 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n151282707 316934479\n",
"output": "316934479 151282707 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1603 | Solve the following coding problem using the programming language python:
Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is v_{i}. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her $\sum_{i = l}^{r} v_{i}$. Let u_{i} be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her $\sum_{i = l}^{r} u_{i}$.
For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.
-----Input-----
The first line contains an integer n (1 ≤ n ≤ 10^5). The second line contains n integers: v_1, v_2, ..., v_{n} (1 ≤ v_{i} ≤ 10^9) — costs of the stones.
The third line contains an integer m (1 ≤ m ≤ 10^5) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.
-----Output-----
Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.
-----Examples-----
Input
6
6 4 2 7 2 7
3
2 3 6
1 3 4
1 1 6
Output
24
9
28
Input
4
5 5 2 3
10
1 2 4
2 1 4
1 1 1
2 1 4
2 1 2
1 1 1
1 3 3
1 1 3
1 4 4
1 2 2
Output
10
15
5
15
5
5
2
12
3
5
-----Note-----
Please note that the answers to the questions may overflow 32-bit integer type.
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())
v = list(map(int, input().split()))
u = sorted(v)
dv, du = [0] * (n + 1), [0] * (n + 1)
ans = list()
for i in range(1, n + 1):
dv[i] = dv[i-1] + v[i-1]
du[i] = du[i-1] + u[i-1]
for i in range(int(input())):
(t, l, r) = list(map(int, input().split()))
d = dv if t == 1 else du
ans.append(str(d[r] - d[l-1]))
print('\n'.join(ans))
``` | vfc_16166 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/433/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n6 4 2 7 2 7\n3\n2 3 6\n1 3 4\n1 1 6\n",
"output": "24\n9\n28\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n5 5 2 3\n10\n1 2 4\n2 1 4\n1 1 1\n2 1 4\n2 1 2\n1 1 1\n1 3 3\n1 1 3\n1 4 4\n1 2 2\n",
"output": "10\n15\n5\n15\n5\n5\n2\n12\n3\n5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1604 | Solve the following coding problem using the programming language python:
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.
Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.
There are $n$ lamps with Spirit Tree's light. Sein knows the time of turning on and off for the $i$-th lamp — $l_i$ and $r_i$ respectively. To open the door you have to choose $k$ lamps in such a way that there will be a moment of time when they all will be turned on.
While Sein decides which of the $k$ lamps to pick, Ori is interested: how many ways there are to pick such $k$ lamps that the door will open? It may happen that Sein may be wrong and there are no such $k$ lamps. The answer might be large, so print it modulo $998\,244\,353$.
-----Input-----
First line contains two integers $n$ and $k$ ($1 \le n \le 3 \cdot 10^5$, $1 \le k \le n$) — total number of lamps and the number of lamps that must be turned on simultaneously.
Next $n$ lines contain two integers $l_i$ ans $r_i$ ($1 \le l_i \le r_i \le 10^9$) — period of time when $i$-th lamp is turned on.
-----Output-----
Print one integer — the answer to the task modulo $998\,244\,353$.
-----Examples-----
Input
7 3
1 7
3 8
4 5
6 7
1 3
5 10
8 9
Output
9
Input
3 1
1 1
2 2
3 3
Output
3
Input
3 2
1 1
2 2
3 3
Output
0
Input
3 3
1 3
2 3
3 3
Output
1
Input
5 2
1 3
2 4
3 5
4 6
5 7
Output
7
-----Note-----
In first test case there are nine sets of $k$ lamps: $(1, 2, 3)$, $(1, 2, 4)$, $(1, 2, 5)$, $(1, 2, 6)$, $(1, 3, 6)$, $(1, 4, 6)$, $(2, 3, 6)$, $(2, 4, 6)$, $(2, 6, 7)$.
In second test case $k=1$, so the answer is 3.
In third test case there are no such pairs of lamps.
In forth test case all lamps are turned on in a time $3$, so the answer is 1.
In fifth test case there are seven sets of $k$ lamps: $(1, 2)$, $(1, 3)$, $(2, 3)$, $(2, 4)$, $(3, 4)$, $(3, 5)$, $(4, 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
MOD = 998244353
MAX = 5 * 10 ** 5 + 5
fact = [1]
for i in range(1, MAX + 1):
new = fact[-1] * i
fact.append(new % MOD)
invL = pow(fact[MAX],MOD-2,MOD)
factInv = [invL] * (MAX + 1)
for i in range(MAX - 1, -1, -1):
old = factInv[i + 1]
new = old * (i + 1)
factInv[i] = new % MOD
def choose(a,b):
if a < b:
return 0
res = fact[a]
res *= factInv[b]
res %= MOD
res *= factInv[a - b]
res %= MOD
return res
n, k = list(map(int, input().split()))
events = []
for i in range(n):
s, e = list(map(int, input().split()))
events.append(2*s+0)
events.append(2*e+1)
events.sort()
count = 0
out = 0
for t in events:
if t&1== 0:
out += choose(count, k - 1)
count += 1
out %= MOD
else:
count -= 1
print(out)
``` | vfc_16170 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1420/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 3\n1 7\n3 8\n4 5\n6 7\n1 3\n5 10\n8 9\n",
"output": "9",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1\n1 1\n2 2\n3 3\n",
"output": "3",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1605 | Solve the following coding problem using the programming language python:
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values: the number of good substrings of even length; the number of good substrings of odd length.
-----Input-----
The first line of the input contains a single string of length n (1 ≤ n ≤ 10^5). Each character of the string will be either 'a' or 'b'.
-----Output-----
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
-----Examples-----
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
-----Note-----
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s_1s_2... s_{n} is string s_{l}s_{l} + 1... s_{r}.
A string s = s_1s_2... s_{n} is a palindrome if it is equal to string s_{n}s_{n} - 1... s_1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
string=input()
length=len(string)
goodbad=[[1, 0, 0, 0] for x in range(length)]
#good odd
#bad odd
#good even
#bad even
for i in range(length-1):
if string[i]==string[i+1]:
goodbad[i+1][0]+=goodbad[i][2]
goodbad[i+1][2]+=goodbad[i][0]
goodbad[i+1][1]+=goodbad[i][3]
goodbad[i+1][3]+=goodbad[i][1]
else:
goodbad[i+1][3]+=goodbad[i][0]
goodbad[i+1][0]+=goodbad[i][3]
goodbad[i+1][1]+=goodbad[i][2]
goodbad[i+1][2]+=goodbad[i][1]
oddct=0
evenct=0
for i in range(len(goodbad)):
oddct+=goodbad[i][0]
evenct+=goodbad[i][2]
print(evenct, oddct)
``` | vfc_16174 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/451/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "bb\n",
"output": "1 2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1607 | Solve the following coding problem using the programming language python:
You are given a grid, consisting of $2$ rows and $n$ columns. Each cell of this grid should be colored either black or white.
Two cells are considered neighbours if they have a common border and share the same color. Two cells $A$ and $B$ belong to the same component if they are neighbours, or if there is a neighbour of $A$ that belongs to the same component with $B$.
Let's call some bicoloring beautiful if it has exactly $k$ components.
Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $998244353$.
-----Input-----
The only line contains two integers $n$ and $k$ ($1 \le n \le 1000$, $1 \le k \le 2n$) — the number of columns in a grid and the number of components required.
-----Output-----
Print a single integer — the number of beautiful bicolorings modulo $998244353$.
-----Examples-----
Input
3 4
Output
12
Input
4 1
Output
2
Input
1 2
Output
2
-----Note-----
One of possible bicolorings in sample $1$: [Image]
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()))
mod=998244353
NEXT={(0,1):2,(1,2):2}#ww or wh,point k,場合の数
for i in range(1,n):
NOW=NEXT
NEXT=dict()
for key in NOW:
if key[0]==0:
if k-(n-i)*2<=key[1]<=k:
NEXT[key]=NEXT.get(key,0)+NOW[key]
if k-(n-i)*2<key[1]+1<=k:
NEXT[(0,key[1]+1)]=NEXT.get((0,key[1]+1),0)+NOW[key]
NEXT[(1,key[1]+1)]=NEXT.get((1,key[1]+1),0)+NOW[key]*2%mod
else:
if k-(n-i)*2<=key[1]<=k:
NEXT[key]=NEXT.get(key,0)+NOW[key]
NEXT[(0,key[1])]=NEXT.get((0,key[1]),0)+NOW[key]*2%mod
if k-(n-i)*2<key[1]+2<=k:
NEXT[(1,key[1]+2)]=NEXT.get((1,key[1]+2),0)+NOW[key]
#print(NOW,NEXT)
ANS=0
for key in NEXT:
if key[1]==k:
ANS=(ANS+NEXT[key])%mod
print(ANS)
``` | vfc_16182 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1051/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1609 | Solve the following coding problem using the programming language python:
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.
During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.
You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.
-----Input-----
The first line contains a single integer n — the number of items (1 ≤ n ≤ 10^5).
The second line contains n numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — the initial inventory numbers of the items.
-----Output-----
Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.
-----Examples-----
Input
3
1 3 2
Output
1 3 2
Input
4
2 2 3 3
Output
2 1 3 4
Input
1
2
Output
1
-----Note-----
In the first test the numeration is already a permutation, so there is no need to change anything.
In the second test there are two pairs of equal numbers, in each pair you need to replace one number.
In the third test you need to replace 2 by 1, as the numbering should start from one.
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())
lst = [int(x) for x in input().split()]
tmp = [False] * 100007
tmp2 = [False] * 100007
for x in lst:
tmp[x] = True
answer, index = [], 1
for x in lst:
if not tmp2[x] and x <= len(lst):
answer.append(x)
tmp2[x] = True
else:
while tmp[index]:
index += 1
tmp[index] = True
answer.append(index)
print(' '.join(map(str, answer)))
``` | vfc_16190 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/569/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 3 2\n",
"output": "1 3 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2 2 3 3\n",
"output": "2 1 3 4 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2\n",
"output": "1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3 3 1\n",
"output": "3 2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 1 1 1 1\n",
"output": "1 2 3 4 5 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1610 | Solve the following coding problem using the programming language python:
Permutation p is an ordered set of integers p_1, p_2, ..., p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the length of permutation p_1, p_2, ..., p_{n}.
The decreasing coefficient of permutation p_1, p_2, ..., p_{n} is the number of such i (1 ≤ i < n), that p_{i} > p_{i} + 1.
You have numbers n and k. Your task is to print the permutation of length n with decreasing coefficient k.
-----Input-----
The single line contains two space-separated integers: n, k (1 ≤ n ≤ 10^5, 0 ≤ k < n) — the permutation length and the decreasing coefficient.
-----Output-----
In a single line print n space-separated integers: p_1, p_2, ..., p_{n} — the permutation of length n with decreasing coefficient k.
If there are several permutations that meet this condition, print any of them. It is guaranteed that the permutation with the sought parameters exists.
-----Examples-----
Input
5 2
Output
1 5 2 4 3
Input
3 0
Output
1 2 3
Input
3 2
Output
3 2 1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
rd = lambda: list(map(int, input().split()))
n, k = rd()
print(' '.join(map(str, list(range(n, n-k,-1))+list(range(1,n-k+1)))))
``` | vfc_16194 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/285/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 2\n",
"output": "1 5 2 4 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 0\n",
"output": "1 2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n",
"output": "3 2 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 0\n",
"output": "1 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n",
"output": "2 1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1611 | Solve the following coding problem using the programming language python:
[Image]
As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.
A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.
Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length l_{i}.
The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle $180^{\circ}$.
Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing.
Help sculptor!
-----Input-----
The first line contains an integer n (3 ≤ n ≤ 10^5) — a number of rod-blanks.
The second line contains n integers l_{i} (1 ≤ l_{i} ≤ 10^9) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.
-----Output-----
Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.
-----Examples-----
Input
3
1 2 1
Output
1
Input
5
20 4 3 2 1
Output
11
-----Note-----
In the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}.
In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.
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()))
total = sum(l)
gap = 0
for rod in l:
gap = max(gap, rod - (total - rod))
print(gap + 1)
``` | vfc_16198 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/667/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n20 4 3 2 1\n",
"output": "11\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1612 | Solve the following coding problem using the programming language python:
Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains m_{i} numbers.
During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct.
You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 100) — the number of the players. Then follow n lines, each line describes a player's card. The line that describes a card starts from integer m_{i} (1 ≤ m_{i} ≤ 100) that shows how many numbers the i-th player's card has. Then follows a sequence of integers a_{i}, 1, a_{i}, 2, ..., a_{i}, m_{i} (1 ≤ a_{i}, k ≤ 100) — the numbers on the i-th player's card. The numbers in the lines are separated by single spaces.
It is guaranteed that all the numbers on each card are distinct.
-----Output-----
Print n lines, the i-th line must contain word "YES" (without the quotes), if the i-th player can win, and "NO" (without the quotes) otherwise.
-----Examples-----
Input
3
1 1
3 2 4 1
2 10 11
Output
YES
NO
YES
Input
2
1 1
1 1
Output
NO
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())
p = list()
for i in range(n):
p.append(set([int(x) for x in input().split()[1:]]))
for i in range(n):
for j in range(n):
if i != j:
if p[i].issuperset(p[j]):
print("NO")
break
else:
print("YES")
``` | vfc_16202 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/370/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 1\n3 2 4 1\n2 10 11\n",
"output": "YES\nNO\nYES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1\n1 1\n",
"output": "NO\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 1\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 2\n1 3\n",
"output": "YES\nYES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1\n2 1 2\n",
"output": "YES\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 1 2\n1 1\n",
"output": "NO\nYES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1613 | Solve the following coding problem using the programming language python:
Память компьютера состоит из n ячеек, которые выстроены в ряд. Пронумеруем ячейки от 1 до n слева направо. Про каждую ячейку известно, свободна она или принадлежит какому-либо процессу (в таком случае известен процесс, которому она принадлежит).
Для каждого процесса известно, что принадлежащие ему ячейки занимают в памяти непрерывный участок. С помощью операций вида «переписать данные из занятой ячейки в свободную, а занятую теперь считать свободной» требуется расположить все принадлежащие процессам ячейки в начале памяти компьютера. Другими словами, любая свободная ячейка должна располагаться правее (иметь больший номер) любой занятой.
Вам необходимо найти минимальное количество операций переписывания данных из одной ячейки в другую, с помощью которых можно достичь описанных условий. Допустимо, что относительный порядок ячеек в памяти для каждого из процессов изменится после дефрагментации, но относительный порядок самих процессов должен остаться без изменений. Это значит, что если все ячейки, принадлежащие процессу i, находились в памяти раньше всех ячеек процесса j, то и после перемещений это условие должно выполняться.
Считайте, что номера всех процессов уникальны, хотя бы одна ячейка памяти занята каким-либо процессом.
-----Входные данные-----
В первой строке входных данных записано число n (1 ≤ n ≤ 200 000) — количество ячеек в памяти компьютера.
Во второй строке входных данных следуют n целых чисел a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n), где a_{i} равно либо 0 (это означает, что i-я ячейка памяти свободна), либо номеру процесса, которому принадлежит i-я ячейка памяти. Гарантируется, что хотя бы одно значение a_{i} не равно 0.
Процессы пронумерованы целыми числами от 1 до n в произвольном порядке. При этом процессы не обязательно пронумерованы последовательными числами.
-----Выходные данные-----
Выведите одно целое число — минимальное количество операций, которое нужно сделать для дефрагментации памяти.
-----Примеры-----
Входные данные
4
0 2 2 1
Выходные данные
2
Входные данные
8
0 8 8 8 0 4 4 2
Выходные данные
4
-----Примечание-----
В первом тестовом примере достаточно двух операций: Переписать данные из третьей ячейки в первую. После этого память компьютера примет вид: 2 2 0 1. Переписать данные из четвертой ячейки в третью. После этого память компьютера примет вид: 2 2 1 0.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
input()
memory = list(map(int, input().split()))
proc_data = {p: (-1, -1) for p in memory}
for i, c in enumerate(memory):
d1, d2 = proc_data[c]
if d1 == -1: d1 = i
d2 = i
proc_data[c] = (d1, d2)
try: del proc_data[0]
except KeyError:
print("0")
return
data = list(proc_data.values())
data.sort()
ans = 0
first_free = 0
for a, b in data:
c = a - first_free
ans += min(c, b-a+1)
b -= c
first_free = b + 1
print(ans)
``` | vfc_16206 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/649/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n0 2 2 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n0 8 8 8 0 4 4 2\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1615 | Solve the following coding problem using the programming language python:
Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r).
He has a set that consists of n integer segments: [l_1; r_1], [l_2; r_2], ..., [l_{n}; r_{n}]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].
The value of a set of segments that consists of n segments [l_1; r_1], [l_2; r_2], ..., [l_{n}; r_{n}] is the number of integers x, such that there is integer j, for which the following inequality holds, l_{j} ≤ x ≤ r_{j}.
Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.
-----Input-----
The first line contains two integers n and k (1 ≤ n, k ≤ 10^5). Each of the following n lines contain a segment as a pair of integers l_{i} and r_{i} ( - 10^5 ≤ l_{i} ≤ r_{i} ≤ 10^5), separated by a space.
It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(r_{i}, r_{j}) < max(l_{i}, l_{j}).
-----Output-----
In a single line print a single integer — the answer to the problem.
-----Examples-----
Input
2 3
1 2
3 4
Output
2
Input
3 7
1 2
3 3
4 7
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=input().split()
N=int(N)
k=int(k)
x=0
for i in range(N):
A,B=input().split()
A=int(A)
B=int(B)
x+=(max(A,B)-min(A,B)+1)
answer=(x%k)
if(answer!=0):
answer=k-answer
print(answer)
``` | vfc_16214 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/289/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3\n1 2\n3 4\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 7\n1 2\n3 3\n4 7\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 7\n1 10\n11 47\n74 128\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 4\n1 1\n2 2\n3 3\n4 4\n5 5\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 4\n2 2\n-1 -1\n0 1\n7 8\n-3 -2\n9 9\n4 6\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 2\n92 92\n55 59\n70 73\n78 81\n62 65\n95 99\n74 75\n85 87\n51 51\n60 60\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1616 | Solve the following coding problem using the programming language python:
You are given an array $a$ of length $n$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 10^5$) — the length of $a$.
The second line contains $n$ integers $a_1$, $a_2$, $\ldots$, $a_{n}$ ($1 \le a_i \le 10^6$) — the elements of the array $a$.
-----Output-----
Output the length of the shortest non-empty subsequence of $a$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
-----Examples-----
Input
3
1 4 6
Output
1
Input
4
2 3 6 6
Output
2
Input
3
6 15 10
Output
3
Input
4
2 3 5 7
Output
-1
-----Note-----
In the first sample, you can choose a subsequence $[1]$.
In the second sample, you can choose a subsequence $[6, 6]$.
In the third sample, you can choose a subsequence $[6, 15, 10]$.
In the fourth sample, there is no such subsequence.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
MAX = 1_000_005
lp = [0] * MAX
pr = []
pid = {1: 0}
for i in range(2, MAX):
if not lp[i]:
lp[i] = i
pr.append(i)
pid[i] = len(pr)
for p in pr:
if p > lp[i] or i * p >= MAX:
break
lp[i * p] = p
n = int(input())
a = list(map(int, input().split()))
g = [[] for _ in range(len(pid))]
ec = 0
for x in a:
f = []
while x > 1:
p, c = lp[x], 0
while lp[x] == p:
x //= p
c ^= 1
if c:
f.append(p)
if not f:
print(1)
import sys
return
f += [1] * (2 - len(f))
u, v = pid[f[0]], pid[f[1]]
g[u].append((v, ec))
g[v].append((u, ec))
ec += 1
def bfs(p):
d = [-1] * len(pid)
d[p] = 0
q = [(p, -1)]
while q:
q2 = []
for u, peid in q:
for v, eid in g[u]:
if d[v] != -1:
if eid != peid:
return d[u] + d[v] + 1
else:
d[v] = d[u] + 1
q2.append((v, eid))
q = q2
ans = -1
for i in range(len(pid)):
if i > 0 and pr[i - 1] ** 2 >= MAX:
break
cyc = bfs(i) or ans
if ans == -1 or cyc < ans:
ans = cyc
print(ans)
``` | vfc_16218 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1325/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 4 6\n",
"output": "1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1617 | Solve the following coding problem using the programming language python:
There are $n$ people sitting in a circle, numbered from $1$ to $n$ in the order in which they are seated. That is, for all $i$ from $1$ to $n-1$, the people with id $i$ and $i+1$ are adjacent. People with id $n$ and $1$ are adjacent as well.
The person with id $1$ initially has a ball. He picks a positive integer $k$ at most $n$, and passes the ball to his $k$-th neighbour in the direction of increasing ids, that person passes the ball to his $k$-th neighbour in the same direction, and so on until the person with the id $1$ gets the ball back. When he gets it back, people do not pass the ball any more.
For instance, if $n = 6$ and $k = 4$, the ball is passed in order $[1, 5, 3, 1]$.
Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $1 + 5 + 3 = 9$.
Find and report the set of possible fun values for all choices of positive integer $k$. It can be shown that under the constraints of the problem, the ball always gets back to the $1$-st player after finitely many steps, and there are no more than $10^5$ possible fun values for given $n$.
-----Input-----
The only line consists of a single integer $n$ ($2 \leq n \leq 10^9$) — the number of people playing with the ball.
-----Output-----
Suppose the set of all fun values is $f_1, f_2, \dots, f_m$.
Output a single line containing $m$ space separated integers $f_1$ through $f_m$ in increasing order.
-----Examples-----
Input
6
Output
1 5 9 21
Input
16
Output
1 10 28 64 136
-----Note-----
In the first sample, we've already shown that picking $k = 4$ yields fun value $9$, as does $k = 2$. Picking $k = 6$ results in fun value of $1$. For $k = 3$ we get fun value $5$ and with $k = 1$ or $k = 5$ we get $21$. [Image]
In the second sample, the values $1$, $10$, $28$, $64$ and $136$ are achieved for instance for $k = 16$, $8$, $4$, $10$ and $11$, respectively.
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 f(x):
y = N//x
return y + x * y * (y-1) // 2
ans = set()
for i in range(1,32000):
if N % i == 0:
ans.add(f(i))
ans.add(f(N//i))
print(" ".join(str(x) for x in sorted(ans)))
``` | vfc_16222 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1091/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n",
"output": "1 5 9 21\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "16\n",
"output": "1 10 28 64 136\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "1 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "25\n",
"output": "1 55 325\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1618 | Solve the following coding problem using the programming language python:
Dima's got a staircase that consists of n stairs. The first stair is at height a_1, the second one is at a_2, the last one is at a_{n} (1 ≤ a_1 ≤ a_2 ≤ ... ≤ a_{n}).
Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width w_{i} and height h_{i}. Dima throws each box vertically down on the first w_{i} stairs of the staircase, that is, the box covers stairs with numbers 1, 2, ..., w_{i}. Each thrown box flies vertically down until at least one of the two following events happen: the bottom of the box touches the top of a stair; the bottom of the box touches the top of a box, thrown earlier.
We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width w_{i} cannot touch the stair number w_{i} + 1.
You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5) — the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of n integers, a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9; a_{i} ≤ a_{i} + 1).
The next line contains integer m (1 ≤ m ≤ 10^5) — the number of boxes. Each of the following m lines contains a pair of integers w_{i}, h_{i} (1 ≤ w_{i} ≤ n; 1 ≤ h_{i} ≤ 10^9) — the size of the i-th thrown box.
The numbers in the lines are separated by spaces.
-----Output-----
Print m integers — for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
5
1 2 3 6 6
4
1 1
3 1
1 1
4 3
Output
1
3
4
6
Input
3
1 2 3
2
1 1
3 1
Output
1
3
Input
1
1
5
1 2
1 10
1 10
1 10
1 10
Output
1
3
13
23
33
-----Note-----
The first sample are shown on the picture. [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
__author__ = "runekri3"
stairs_amount = int(input())
stair_heights = list(map(int, input().split()))
boxes_amount = int(input())
boxes = []
for _ in range(boxes_amount):
boxes.append(list(map(int, input().split())))
for width, height in boxes:
box_bottom = max(stair_heights[0], stair_heights[width - 1])
print(box_bottom)
stair_heights[0] = box_bottom + height
``` | vfc_16226 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/272/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 3 6 6\n4\n1 1\n3 1\n1 1\n4 3\n",
"output": "1\n3\n4\n6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 2 3\n2\n1 1\n3 1\n",
"output": "1\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n5\n1 2\n1 10\n1 10\n1 10\n1 10\n",
"output": "1\n3\n13\n23\n33\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1619 | Solve the following coding problem using the programming language python:
Cowboy Beblop is a funny little boy who likes sitting at his computer. He somehow obtained two elastic hoops in the shape of 2D polygons, which are not necessarily convex. Since there's no gravity on his spaceship, the hoops are standing still in the air. Since the hoops are very elastic, Cowboy Beblop can stretch, rotate, translate or shorten their edges as much as he wants.
For both hoops, you are given the number of their vertices, as well as the position of each vertex, defined by the X , Y and Z coordinates. The vertices are given in the order they're connected: the 1st vertex is connected to the 2nd, which is connected to the 3rd, etc., and the last vertex is connected to the first one. Two hoops are connected if it's impossible to pull them to infinity in different directions by manipulating their edges, without having their edges or vertices intersect at any point – just like when two links of a chain are connected. The polygons' edges do not intersect or overlap.
To make things easier, we say that two polygons are well-connected, if the edges of one polygon cross the area of the other polygon in two different directions (from the upper and lower sides of the plane defined by that polygon) a different number of times.
Cowboy Beblop is fascinated with the hoops he has obtained and he would like to know whether they are well-connected or not. Since he’s busy playing with his dog, Zwei, he’d like you to figure it out for him. He promised you some sweets if you help him!
-----Input-----
The first line of input contains an integer n (3 ≤ n ≤ 100 000), which denotes the number of edges of the first polygon. The next N lines each contain the integers x, y and z ( - 1 000 000 ≤ x, y, z ≤ 1 000 000) — coordinates of the vertices, in the manner mentioned above. The next line contains an integer m (3 ≤ m ≤ 100 000) , denoting the number of edges of the second polygon, followed by m lines containing the coordinates of the second polygon’s vertices.
It is guaranteed that both polygons are simple (no self-intersections), and in general that the obtained polygonal lines do not intersect each other. Also, you can assume that no 3 consecutive points of a polygon lie on the same line.
-----Output-----
Your output should contain only one line, with the words "YES" or "NO", depending on whether the two given polygons are well-connected.
-----Example-----
Input
4
0 0 0
2 0 0
2 2 0
0 2 0
4
1 1 -1
1 1 1
1 3 1
1 3 -1
Output
YES
-----Note-----
On the picture below, the two polygons are well-connected, as the edges of the vertical polygon cross the area of the horizontal one exactly once in one direction (for example, from above to below), and zero times in the other (in this case, from below to above). Note that the polygons do not have to be parallel to any of the xy-,xz-,yz- planes in general. [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""Cowboy Beblop at his computer, problem 717I from https://codeforces.com/problemset/problem/717/I"""
# from fractions import Fraction
# def convert_to_fractions(poly):
# """convert polygon vertex to fractional type"""
# poly_frac = []
# for x, y, z in poly:
# vertex = (Fraction(x),
# Fraction(y),
# Fraction(z))
# poly_frac.append(vertex)
# return poly_frac
def convert_to_float(poly):
"""convert polygon vertex to float type"""
poly_float = []
for x, y, z in poly:
vertex = (float(x),
float(y),
float(z))
poly_float.append(vertex)
return poly_float
def cross_product(a, b):
"""3-vector product"""
return (a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0])
def dot_product(a, b):
"""scalar product of 3-vectors"""
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def vect_diff(a, b):
"""vector difference"""
return a[0] - b[0], a[1] - b[1], a[2] - b[2]
def poly_normal(poly):
"""return normal vector for first three vertex"""
assert len(poly) >= 3
x, y, z = poly[:3]
u = vect_diff(y, x)
v = vect_diff(z, y)
return cross_product(u, v)
def intersect_list(poly, plain_norm, plain_point, proj_dir):
"""list of intersection points
find points where the edges enter or leave upper half-space over the plain
:return list of points projection on proj_dir
"""
# vertex projection
u = [dot_product(vert, proj_dir) for vert in poly]
# plain anchor
vr = dot_product(plain_point, plain_norm)
# polygon vertex
v = [dot_product(vert, plain_norm) for vert in poly]
u_list = []
for i in range(len(poly)):
if (v[i-1] > vr) != (v[i] > vr):
ur = ((vr - v[i-1]) * u[i] + (v[i] - vr) * u[i-1]) / (v[i] - v[i-1])
u_list.append(ur)
return u_list
def points_to_str(a_points, b_points):
"""string representing the order of points 'a' and 'b'"""
a_pairs = [('a', val) for val in a_points]
b_pairs = [('b', val) for val in b_points]
pairs = sorted(a_pairs + b_pairs, key=lambda pair: pair[1])
letters = [ch for ch, _ in pairs]
return ''.join(letters)
def recognize_str(s):
"""return True if string s belong to the grammar
The context-free grammar is given
S -> SS
S -> a S a
S -> b S b
S -> e
The recognising automaton is implemented
"""
toggle = {'a':'b', 'b':'a'}
cross_num = 0
top = None
for ch in s:
if not cross_num:
cross_num = 1
top = ch
continue
if ch == top:
cross_num -= 1
else:
cross_num += 1
if cross_num:
top = toggle[top]
else:
top = None
return not cross_num
def is_well_connected(a, b):
"""Two planar polygons are bind together in 3D
Arguments:
a_poly,
b_poly -- lists of vertex triples
"""
a = convert_to_float(a)
b = convert_to_float(b)
a_norm = poly_normal(a)
b_norm = poly_normal(b)
common_dir = cross_product(a_norm, b_norm)
if not any(common_dir):
return False
a_list = intersect_list(a, b_norm, b[0], common_dir)
b_list = intersect_list(b, a_norm, a[0], common_dir)
char_str = points_to_str(a_list, b_list)
return not recognize_str(char_str)
def run_from_console():
a_len, = [int(num) for num in input().split()]
a = []
for _ in range(a_len):
vertex = tuple(int(num) for num in input().split())
a.append(vertex)
b_len, = [int(num) for num in input().split()]
b = []
for _ in range(b_len):
vertex = tuple(int(num) for num in input().split())
b.append(vertex)
if is_well_connected(a, b):
print('YES')
else:
print('NO')
def __starting_point():
run_from_console()
__starting_point()
``` | vfc_16230 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/717/I",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n0 0 0\n2 0 0\n2 2 0\n0 2 0\n4\n1 1 -1\n1 1 1\n1 3 1\n1 3 -1\n",
"output": "YES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1620 | Solve the following coding problem using the programming language python:
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
-----Input-----
The first line contains single integer n (1 ≤ n ≤ 2·10^5) — the length of the string.
-----Output-----
Print the string that satisfies all the constraints.
If there are multiple answers, print any of them.
-----Examples-----
Input
2
Output
aa
Input
3
Output
bba
-----Note-----
A palindrome is a sequence of characters which reads the same backward and forward.
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 = "aabb" * ((n+4)//4)
s = s[:n]
print(s)
``` | vfc_16234 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/805/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n",
"output": "aa\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "aab\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1623 | Solve the following coding problem using the programming language python:
Mislove had an array $a_1$, $a_2$, $\cdots$, $a_n$ of $n$ positive integers, but he has lost it. He only remembers the following facts about it:
The number of different numbers in the array is not less than $l$ and is not greater than $r$;
For each array's element $a_i$ either $a_i = 1$ or $a_i$ is even and there is a number $\dfrac{a_i}{2}$ in the array.
For example, if $n=5$, $l=2$, $r=3$ then an array could be $[1,2,2,4,4]$ or $[1,1,1,1,2]$; but it couldn't be $[1,2,2,4,8]$ because this array contains $4$ different numbers; it couldn't be $[1,2,2,3,3]$ because $3$ is odd and isn't equal to $1$; and it couldn't be $[1,1,2,2,16]$ because there is a number $16$ in the array but there isn't a number $\frac{16}{2} = 8$.
According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array.
-----Input-----
The only input line contains three integers $n$, $l$ and $r$ ($1 \leq n \leq 1\,000$, $1 \leq l \leq r \leq \min(n, 20)$) — an array's size, the minimal number and the maximal number of distinct elements in an array.
-----Output-----
Output two numbers — the minimal and the maximal possible sums of all elements in an array.
-----Examples-----
Input
4 2 2
Output
5 7
Input
5 1 5
Output
5 31
-----Note-----
In the first example, an array could be the one of the following: $[1,1,1,2]$, $[1,1,2,2]$ or $[1,2,2,2]$. In the first case the minimal sum is reached and in the last case the maximal sum is reached.
In the second example, the minimal sum is reached at the array $[1,1,1,1,1]$, and the maximal one is reached at the array $[1,2,4,8,16]$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
import sys
input = sys.stdin.readline
n, l, r = map(int, input().split())
mi = 0
curr = 1 << l - 1
for i in range(n):
mi += curr
if curr != 1:
curr >>= 1
ma = 0
curr = 1
for i in range(n):
ma += curr
if curr != 1 << r - 1:
curr <<= 1
print(mi, ma)
return 0
main()
``` | vfc_16246 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1204/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2 2\n",
"output": "5 7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 1 5\n",
"output": "5 31\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "106 16 18\n",
"output": "65625 11796479\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "114 18 19\n",
"output": "262239 25427967\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "655 3 18\n",
"output": "659 83755007\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1624 | Solve the following coding problem using the programming language python:
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.
There are $n$ positive integers $a_1, a_2, \ldots, a_n$ on Bob's homework paper, where $n$ is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least $2$ numbers. Suppose the numbers are divided into $m$ groups, and the sum of the numbers in the $j$-th group is $s_j$. Bob's aim is to minimize the sum of the square of $s_j$, that is $$\sum_{j = 1}^{m} s_j^2.$$
Bob is puzzled by this hard problem. Could you please help him solve it?
-----Input-----
The first line contains an even integer $n$ ($2 \leq n \leq 3 \cdot 10^5$), denoting that there are $n$ integers on Bob's homework paper.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^4$), describing the numbers you need to deal with.
-----Output-----
A single line containing one integer, denoting the minimum of the sum of the square of $s_j$, which is $$\sum_{i = j}^{m} s_j^2,$$ where $m$ is the number of groups.
-----Examples-----
Input
4
8 5 2 3
Output
164
Input
6
1 1 1 2 2 2
Output
27
-----Note-----
In the first sample, one of the optimal solutions is to divide those $4$ numbers into $2$ groups $\{2, 8\}, \{5, 3\}$. Thus the answer is $(2 + 8)^2 + (5 + 3)^2 = 164$.
In the second sample, one of the optimal solutions is to divide those $6$ numbers into $3$ groups $\{1, 2\}, \{1, 2\}, \{1, 2\}$. Thus the answer is $(1 + 2)^2 + (1 + 2)^2 + (1 + 2)^2 = 27$.
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 = []
a = input().split()
a = [int(i) for i in a]
a.sort()
ans = 0
for i in range(n // 2):
ans += (a[i] + a[n - i - 1]) ** 2
print(ans)
``` | vfc_16250 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1106/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n8 5 2 3\n",
"output": "164\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n1 1 1 2 2 2\n",
"output": "27\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n9540 7069 4914 2241\n",
"output": "282384250\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50\n9 16 3 3 12 2 9 13 6 11 18 15 6 20 14 13 20 5 19 4 10 2 10 19 20 3 15 3 9 1 9 4 16 3 19 14 12 13 12 5 9 16 4 1 8 20 8 2 11 5\n",
"output": "10075\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20\n8 10 10 1 1 5 9 2 1 5 4 3 4 4 2 10 3 9 9 4\n",
"output": "1096\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1625 | Solve the following coding problem using the programming language python:
Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.
He's got a square 2^{n} × 2^{n}-sized matrix and 4^{n} integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that the beauty of the resulting matrix with numbers is maximum.
The beauty of a 2^{n} × 2^{n}-sized matrix is an integer, obtained by the following algorithm: Find the maximum element in the matrix. Let's denote it as m. If n = 0, then the beauty of the matrix equals m. Otherwise, a matrix can be split into 4 non-intersecting 2^{n} - 1 × 2^{n} - 1-sized submatrices, then the beauty of the matrix equals the sum of number m and other four beauties of the described submatrices.
As you can see, the algorithm is recursive.
Help Ilya, solve the problem and print the resulting maximum beauty of the matrix.
-----Input-----
The first line contains integer 4^{n} (1 ≤ 4^{n} ≤ 2·10^6). The next line contains 4^{n} integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the numbers you need to arrange in the 2^{n} × 2^{n}-sized matrix.
-----Output-----
On a single line print the maximum value of the beauty of the described matrix.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
1
13
Output
13
Input
4
1 2 3 4
Output
14
-----Note-----
Consider the second sample. You need to arrange the numbers in the matrix as follows:
1 2
3 4
Then the beauty of the matrix will equal: 4 + 1 + 2 + 3 + 4 = 14.
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())
arr = list(map(float, input().split()))
if n == 1:
print(int(arr[0]))
return
arr.sort(reverse = True)
res = 0
while arr:
res += sum(arr)
arr = arr[:len(arr)//4]
print(int(res))
``` | vfc_16254 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/313/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n13\n",
"output": "13\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1626 | Solve the following coding problem using the programming language python:
Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits.
Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a_1, a_2, ..., a_{n} / k and b_1, b_2, ..., b_{n} / k. Let's split the phone number into blocks of length k. The first block will be formed by digits from the phone number that are on positions 1, 2,..., k, the second block will be formed by digits from the phone number that are on positions k + 1, k + 2, ..., 2·k and so on. Pasha considers a phone number good, if the i-th block doesn't start from the digit b_{i} and is divisible by a_{i} if represented as an integer.
To represent the block of length k as an integer, let's write it out as a sequence c_1, c_2,...,c_{k}. Then the integer is calculated as the result of the expression c_1·10^{k} - 1 + c_2·10^{k} - 2 + ... + c_{k}.
Pasha asks you to calculate the number of good phone numbers of length n, for the given k, a_{i} and b_{i}. As this number can be too big, print it modulo 10^9 + 7.
-----Input-----
The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ min(n, 9)) — the length of all phone numbers and the length of each block, respectively. It is guaranteed that n is divisible by k.
The second line of the input contains n / k space-separated positive integers — sequence a_1, a_2, ..., a_{n} / k (1 ≤ a_{i} < 10^{k}).
The third line of the input contains n / k space-separated positive integers — sequence b_1, b_2, ..., b_{n} / k (0 ≤ b_{i} ≤ 9).
-----Output-----
Print a single integer — the number of good phone numbers of length n modulo 10^9 + 7.
-----Examples-----
Input
6 2
38 56 49
7 3 4
Output
8
Input
8 2
1 22 3 44
5 4 3 2
Output
32400
-----Note-----
In the first test sample good phone numbers are: 000000, 000098, 005600, 005698, 380000, 380098, 385600, 385698.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math
n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
c = 1
for i in range(n // k):
count = (10 ** k - 1) // a[i] + 1
mmin = b[i] * (10 ** (k-1))
mmax = (b[i] + 1) * (10 ** (k-1)) - 1
mcount = mmax // a[i] - math.ceil(mmin / a[i]) + 1
c = (c * (count - mcount)) % ((10 ** 9) + 7)
print(c)
``` | vfc_16258 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/595/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 2\n38 56 49\n7 3 4\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8 2\n1 22 3 44\n5 4 3 2\n",
"output": "32400\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n9 9\n9 9\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1627 | Solve the following coding problem using the programming language python:
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is the height of the animal occupying the i-th place.
-----Output-----
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers l_{i} and r_{i} (1 ≤ l_{i} < r_{i} ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
-----Examples-----
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
-----Note-----
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def s(arr):
arr2 = arr[:]
arr2.sort()
return arr == arr2
x = int(input())
y = list(map(int, input().split(' ')))
while (not s(y)):
for i in range(x-1):
if y[i] > y[i+1]:
print(i+1, i+2)
y[i], y[i+1] = y[i+1], y[i]
``` | vfc_16262 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/686/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n2 1 4 3\n",
"output": "1 2\n3 4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1628 | Solve the following coding problem using the programming language python:
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime: Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.
The input for the new algorithm is string s, and the algorithm works as follows: If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm.
Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.
-----Input-----
The first line contains a non-empty string s.
It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 10^6 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.
-----Output-----
In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.
-----Examples-----
Input
x
Output
x
Input
yxyxy
Output
y
Input
xxxxxy
Output
xxxx
-----Note-----
In the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.
In the second test the transformation will be like this: string "yxyxy" transforms into string "xyyxy"; string "xyyxy" transforms into string "xyxyy"; string "xyxyy" transforms into string "xxyyy"; string "xxyyy" transforms into string "xyy"; string "xyy" transforms into string "y".
As a result, we've got string "y".
In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = input()
a, b = s.count('x'), s.count('y')
if b > a: print('y' * (b - a))
else: print('x' * (a - b))
``` | vfc_16266 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/255/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "x\n",
"output": "x\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1629 | Solve the following coding problem using the programming language python:
Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.
Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on.
For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.
At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls.
He asks you to help to find the initial arrangement of the balls in the boxes.
-----Input-----
The first line of the input contains two integers n and x (2 ≤ n ≤ 10^5, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a_1, a_2, ..., a_{n}, where integer a_{i} (0 ≤ a_{i} ≤ 10^9, a_{x} ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.
-----Examples-----
Input
4 4
4 3 1 6
Output
3 2 5 4
Input
5 2
3 2 0 2 7
Output
2 1 4 1 6
Input
3 3
2 3 1
Output
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
n, x = map(int, input().split())
t = list(map(int, input().split()))
m = min(t[: x])
if m == 0:
i = x - 1
while t[i]: i -= 1
t[i + 1: x] = [j - 1 for j in t[i + 1: x]]
t[i] = x - i - 1
else:
t[: x] = [i - 1 for i in t[: x]]
m = min(t)
if m: t = [i - m for i in t]
i = n - 1
while t[i]: i -= 1
t[i + 1: ] = [j - 1 for j in t[i + 1: ]]
t[i] = x + m * n + n - i - 1
print(' '.join(map(str, t)))
``` | vfc_16270 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/260/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 4\n4 3 1 6\n",
"output": "3 2 5 4 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n3 2 0 2 7\n",
"output": "2 1 4 1 6 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n2 3 1\n",
"output": "1 2 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 3\n1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000\n",
"output": "0 0 10000000000 0 0 0 0 0 0 0 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 4\n0 554459682 978416312 784688178 954779973\n",
"output": "3 554459681 978416311 784688177 954779973 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1630 | Solve the following coding problem using the programming language python:
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.
Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB".
Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.
Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of clubs in the league.
Each of the next n lines contains two words — the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.
-----Output-----
It it is not possible to choose short names and satisfy all constraints, print a single line "NO".
Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input.
If there are multiple answers, print any of them.
-----Examples-----
Input
2
DINAMO BYTECITY
FOOTBALL MOSCOW
Output
YES
DIN
FOO
Input
2
DINAMO BYTECITY
DINAMO BITECITY
Output
NO
Input
3
PLAYFOOTBALL MOSCOW
PLAYVOLLEYBALL SPB
GOGO TECHNOCUP
Output
YES
PLM
PLS
GOG
Input
3
ABC DEF
ABC EFG
ABD OOO
Output
YES
ABD
ABE
ABO
-----Note-----
In the first sample Innokenty can choose first option for both clubs.
In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.
In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.
In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different.
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())
first = {}
second = set()
s1 = [0] * n
ans = [0] * n
for i in range(n):
a, b = input().split()
a = a[:3]
b = b[0]
s1[i] = b
if a in first.keys():
first[a].append(i)
else:
first[a] = [i]
ans[i] = a
F = True
for name in first.keys():
if not F:
break
if len(first[name]) > 1:
for i in first[name]:
c = name[:2] + s1[i]
if c in second:
F = False
break
else:
second.add(c)
ans[i] = c
first[name] = 0
def process(name):
nonlocal F
if F == False:
return
if first[name] != 0 and name in second:
t = first[name][0]
c = name[:2] + s1[t]
if c in second:
F = False
return
else:
second.add(c)
ans[t] = c
first[name] = 0
if c in first.keys() and first[c] != 0:
process(c)
for name in first.keys():
process(name)
if F:
print('YES')
for i in range(n):
print(ans[i])
else:
print('NO')
``` | vfc_16274 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/780/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\nDINAMO BYTECITY\nFOOTBALL MOSCOW\n",
"output": "YES\nDIN\nFOO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\nDINAMO BYTECITY\nDINAMO BITECITY\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP\n",
"output": "YES\nPLM\nPLS\nGOG\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nABC DEF\nABC EFG\nABD OOO\n",
"output": "YES\nABD\nABE\nABO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nABC DEF\nABC EFG\nABC EEEEE\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nABC DEF\nABC EFG\nABD CABA\n",
"output": "YES\nABD\nABE\nABC\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1631 | Solve the following coding problem using the programming language python:
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.
Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: s_{i} ≠ t_{i}. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters s_{i} and t_{i} according to their order in alphabet.
-----Input-----
The first line contains an integer n (1 ≤ n ≤ 100): number of names.
Each of the following n lines contain one string name_{i} (1 ≤ |name_{i}| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.
-----Output-----
If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).
Otherwise output a single word "Impossible" (without quotes).
-----Examples-----
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#return if sa contains a real prefix: sb
def isPrefix( sa , sb ):
if len(sa) <= len(sb):
return False
return sa[0:len(sb)] == sb
def getOrder( sa , sb ):
for i in range( 0 , min( len(sa) , len(sb) ) ):
if sa[i] != sb[i]:
return sa[i],sb[i]
test = False
if test:
fp = open("C-4.in","r")
n = int(fp.readline().strip())
names = [ fp.readline().strip() for i in range(0,n)]
fp.close()
else:
n = int(input().strip())
names = [ input().strip() for i in range(0,n)]
g = [[False]*26 for i in range(0,26)]
res = True
for i in range(1,n):
if names[i-1] == names[i] or isPrefix( names[i] , names[i-1] ):
continue
elif isPrefix( names[i-1] , names[i] ):
res = False
break
else:
ca,cb = getOrder( names[i-1] , names[i] )
#print(ca,"<",cb)
if g[ord(cb)-ord('a')][ord(ca)-ord('a')]:
res = False
break
else:
g[ord(ca)-ord('a')][ord(cb)-ord('a')] = True
def printG():
print(" abcdefghijklmnopqrstuvwxyz")
for i in range(0,26):
print( chr( ord("a") + i ) , "".join( [ "1" if x else "0" for x in g[i]] ) , sep = "")
#printG()
if not res:
print("Impossible")
else:
def getZeroIndegreeNode():
for i in range(0,26):
if not used[i] and indegree[i] == 0:
return i
return -1
#topo sort
theOrder = []
indegree = [0] * 26
used = [False] * 26
#calc indegree
for i in range(0,26):
ithIndegree = 0
for j in range(0,26):
if g[j][i]: ithIndegree += 1
indegree[i] = ithIndegree
for i in range(0,26):
zeroIndegreeNode = getZeroIndegreeNode()
if zeroIndegreeNode == -1:
res = False
break
else:
used[zeroIndegreeNode] = True
theOrder.append( chr( ord('a') + zeroIndegreeNode ) )
for j in range(0,26):
if g[zeroIndegreeNode][j]:
indegree[j] -= 1
if not res:
print("Impossible")
else:
print( "".join( theOrder ) )
``` | vfc_16278 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/510/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\nrivest\nshamir\nadleman\n",
"output": "bcdefghijklmnopqrsatuvwxyz\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer\n",
"output": "Impossible\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1634 | Solve the following coding problem using the programming language python:
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.
Public transport is not free. There are 4 types of tickets: A ticket for one ride on some bus or trolley. It costs c_1 burles; A ticket for an unlimited number of rides on some bus or on some trolley. It costs c_2 burles; A ticket for an unlimited number of rides on all buses or all trolleys. It costs c_3 burles; A ticket for an unlimited number of rides on all buses and trolleys. It costs c_4 burles.
Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
-----Input-----
The first line contains four integers c_1, c_2, c_3, c_4 (1 ≤ c_1, c_2, c_3, c_4 ≤ 1000) — the costs of the tickets.
The second line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of buses and trolleys Vasya is going to use.
The third line contains n integers a_{i} (0 ≤ a_{i} ≤ 1000) — the number of times Vasya is going to use the bus number i.
The fourth line contains m integers b_{i} (0 ≤ b_{i} ≤ 1000) — the number of times Vasya is going to use the trolley number i.
-----Output-----
Print a single number — the minimum sum of burles Vasya will have to spend on the tickets.
-----Examples-----
Input
1 3 7 19
2 3
2 5
4 4 4
Output
12
Input
4 3 2 1
1 3
798
1 2 3
Output
1
Input
100 100 8 100
3 5
7 94 12
100 1 47 0 42
Output
16
-----Note-----
In the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2·1) + 3 + 7 = 12 burles.
In the second sample the profitable strategy is to buy one ticket of the fourth type.
In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
c = list(map(int, input().split()))
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
sa = sum(a)*c[0]
sb = sum(b)*c[0]
for i in a:
sa = min(sa, sa - i*c[0] + c[1])
for i in b:
sb = min(sb, sb - i*c[0] + c[1])
print(min(sa + sb, sa + c[2], sb + c[2], c[2] + c[2], c[3]))
``` | vfc_16290 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/355/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 3 7 19\n2 3\n2 5\n4 4 4\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3 2 1\n1 3\n798\n1 2 3\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 100 8 100\n3 5\n7 94 12\n100 1 47 0 42\n",
"output": "16\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 103 945 1000\n7 9\n34 35 34 35 34 35 34\n0 0 0 0 0 0 0 0 0\n",
"output": "717\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 11 597 948\n4 1\n5 1 0 11\n7\n",
"output": "40\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 32 109 645\n1 3\n0\n0 0 0\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1635 | Solve the following coding problem using the programming language python:
Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.
-----Input-----
In first line there is one integer n (1 ≤ n ≤ 2·10^5) — number of cafes indices written by Vlad.
In second line, n numbers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 2·10^5) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.
-----Output-----
Print one integer — index of the cafe that Vlad hasn't visited for as long as possible.
-----Examples-----
Input
5
1 3 2 1 2
Output
3
Input
6
2 1 2 2 4 1
Output
2
-----Note-----
In first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer.
In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes.
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 re
import math
import getpass
import sys
debug = False
files = False
if getpass.getuser() == 'frohe':
debug = True
if debug and files:
sys.stdin = open('test.in')
def ria():
return [int(i) for i in input().split()]
n = ria()[0]
ar = ria()
mp = {}
for i in ar:
mp[i] = 0
for n, i in enumerate(ar):
mp[i] = n
mini = ar[0]
for i in mp:
if mp[mini]>mp[i]:
mini=i
print(mini)
``` | vfc_16294 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/886/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 3 2 1 2\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n2 1 2 2 4 1\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1637 | Solve the following coding problem using the programming language python:
Zibi is a competitive programming coach. There are $n$ competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.
Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).
We know that the $i$-th competitor will always have score $x_i$ when he codes the first task and $y_i$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.
Zibi wants all competitors to write a contest with each other. However, there are $m$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?
-----Input-----
The first line contains two integers $n$ and $m$ ($2 \le n \le 300\,000$, $0 \le m \le 300\,000$) — the number of participants and the number of pairs of people who will not write a contest together.
Each of the next $n$ lines contains two integers $x_i$ and $y_i$ ($-10^9 \le x_i, y_i \le 10^9$) — the scores which will the $i$-th competitor get on the first problem and on the second problem. It is guaranteed that there are no two people having both $x_i$ and $y_i$ same.
Each of the next $m$ lines contain two integers $u_i$ and $v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$) — indices of people who don't want to write a contest in one team. Each unordered pair of indices will appear at most once.
-----Output-----
Output $n$ integers — the sum of scores for all participants in the same order as they appear in the input.
-----Examples-----
Input
3 2
1 2
2 3
1 3
1 2
2 3
Output
3 0 3
Input
3 3
1 2
2 3
1 3
1 2
2 3
1 3
Output
0 0 0
Input
5 3
-1 3
2 4
1 1
3 5
2 2
1 4
2 3
3 5
Output
4 14 4 16 10
-----Note-----
In the first example, there will be only one team consisting of persons $1$ and $3$. The optimal strategy for them is to assign the first task to the $3$-rd person and the second task to the $1$-st person, this will lead to score equal to $1 + 2 = 3$.
In the second example, nobody likes anyone, so there won't be any trainings. It seems that Zibi won't be titled coach in that case...
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()]
inp = []
s = sys.stdin.read()
i = 0
while True:
while i<len(s) and s[i]<'-':i+=1
if i==len(s):break
j = i
while j<len(s) and not(s[j]<'-'):j+=1
inp.append(int(s[i:j]))
i = j
order = sorted(range(n),key=lambda i:inp[2*i]-inp[2*i+1])
score = [0]*n
val = sum(inp[1:2*n:2])
for ind in range(n):
i = order[ind]
# Do second problem together with order[:ind]
# Do first problem together with order[ind:]
score[i] += val + inp[2*i+1]*(ind-1) + inp[2*i]*(n-ind-1)
val += inp[2*i]-inp[2*i+1]
for _ in range(m):
u = inp[2*n+2*_]-1
v = inp[2*n+2*_+1]-1
s = min(inp[2*u]+inp[2*v+1],inp[2*v]+inp[2*u+1])
score[u] -= s
score[v] -= s
sys.stdout.write(' '.join(str(x) for x in score))
``` | vfc_16302 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1043/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n1 2\n2 3\n1 3\n1 2\n2 3\n",
"output": "3 0 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n1 2\n2 3\n1 3\n1 2\n2 3\n1 3\n",
"output": "0 0 0 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1638 | Solve the following coding problem using the programming language python:
This is an easier version of the problem. In this version $n \le 1000$
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $n$ plots along the highway and is preparing to build $n$ skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from $1$ to $n$. Then if the skyscraper on the $i$-th plot has $a_i$ floors, it must hold that $a_i$ is at most $m_i$ ($1 \le a_i \le m_i$). Also there mustn't be integers $j$ and $k$ such that $j < i < k$ and $a_j > a_i < a_k$. Plots $j$ and $k$ are not required to be adjacent to $i$.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 1000$) — the number of plots.
The second line contains the integers $m_1, m_2, \ldots, m_n$ ($1 \leq m_i \leq 10^9$) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
-----Output-----
Print $n$ integers $a_i$ — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
-----Examples-----
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
-----Note-----
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer $[10, 6, 6]$ is optimal. Note that the answer of $[6, 6, 8]$ also satisfies all restrictions, but is not optimal.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
S = -1
for mid in range(N):
ans = [0] * N
ans[mid] = A[mid]
prev = A[mid]
for j in range(mid-1, -1, -1):
ans[j] = min(prev, A[j])
prev = ans[j]
prev = A[mid]
for j in range(mid+1, N):
ans[j] = min(prev, A[j])
prev = ans[j]
if sum(ans) > S:
S = sum(ans)
ans_best = ans
print(*ans_best)
def __starting_point():
main()
__starting_point()
``` | vfc_16306 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1313/C1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 3 2 1\n",
"output": "1 2 3 2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n10 6 8\n",
"output": "10 6 6 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n1 2 1 2 1 2 1\n",
"output": "1 2 1 1 1 1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n1 2 1 2 1 3 1\n",
"output": "1 1 1 1 1 3 1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1639 | Solve the following coding problem using the programming language python:
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes a_{i} money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence a_{i}. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.
-----Examples-----
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
-----Note-----
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = input()
v = list(map(int, input().split()))
best = 1
current = 1
for i in range(1, len(v)):
if v[i-1] <= v[i]:
current += 1
else:
current = 1
best = max(best, current)
print(best)
``` | vfc_16310 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/580/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n2 2 1 3 4 1\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 2 9\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n10 100 111 1 2\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 2 3 4 1 2 3 4 5 6\n",
"output": "6",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
"output": "50",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1640 | Solve the following coding problem using the programming language python:
Let's denote a function
$d(x, y) = \left\{\begin{array}{ll}{y - x,} & {\text{if}|x - y|> 1} \\{0,} & {\text{if}|x - y|\leq 1} \end{array} \right.$
You are given an array a consisting of n integers. You have to calculate the sum of d(a_{i}, a_{j}) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — elements of the array.
-----Output-----
Print one integer — the sum of d(a_{i}, a_{j}) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
-----Examples-----
Input
5
1 2 3 1 3
Output
4
Input
4
6 6 5 5
Output
0
Input
4
6 6 4 4
Output
-8
-----Note-----
In the first example:
d(a_1, a_2) = 0; d(a_1, a_3) = 2; d(a_1, a_4) = 0; d(a_1, a_5) = 2; d(a_2, a_3) = 0; d(a_2, a_4) = 0; d(a_2, a_5) = 0; d(a_3, a_4) = - 2; d(a_3, a_5) = 0; d(a_4, a_5) = 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())
line = list(map(int, input().split()))
m = dict()
ans = 0
for i in range(n):
if line[i] not in m:
m[line[i]] = 1
else:
m[line[i]] += 1
var = m[line[i]]
if line[i] - 1 in m:
var += m[line[i]-1]
if line[i] + 1 in m:
var += m[line[i]+1]
ans += (i+1-var) * line[i]
x = dict()
for j in range(n):
i = n - j - 1
if line[i] not in x:
x[line[i]] = 1
else:
x[line[i]] += 1
var = x[line[i]]
if line[i] - 1 in x:
var += x[line[i]-1]
if line[i] + 1 in x:
var += x[line[i]+1]
ans -= (j+1-var) * line[i]
print(ans)
``` | vfc_16314 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/903/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 3 1 3\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n6 6 5 5\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n6 6 4 4\n",
"output": "-8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000000\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1000000000\n",
"output": "999999999\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1641 | Solve the following coding problem using the programming language python:
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.
There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.
There are n cars in the rental service, i-th of them is characterized with two integers c_{i} and v_{i} — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity v_{i}. All cars are completely fueled at the car rental service.
Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.
Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
-----Input-----
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·10^5, 1 ≤ k ≤ 2·10^5, 2 ≤ s ≤ 10^9, 1 ≤ t ≤ 2·10^9) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.
Each of the next n lines contains two positive integers c_{i} and v_{i} (1 ≤ c_{i}, v_{i} ≤ 10^9) — the price of the i-th car and its fuel tank capacity.
The next line contains k distinct integers g_1, g_2, ..., g_{k} (1 ≤ g_{i} ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
-----Output-----
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
-----Examples-----
Input
3 1 8 10
10 8
5 7
11 9
3
Output
10
Input
2 2 10 18
10 4
20 6
5 3
Output
20
-----Note-----
In the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# Question B. Road to Cinema
import sys
def roadToCinema(V, S, T, stations): # O(M)
"""
V : volume of fuel tank
S : total distance
T : time limit
stations: fuel stations' locations
rtype : boolean, whether this aircraft can travel within the time limit
"""
m = len(stations)
t = 0
stations.append(S) # destination
prev = 0
for cur in stations:
dis = cur - prev
# let Sa, Sb as the distance of accelerated mode/ normal mode respectively
# then the task is:
# min t = (Sa + 2 * Sb)
# s.t. Sa + Sb = dis
# 2 * Sa + Sb <= V
if dis > V:
# Sa <= V - dis < 0
return False
else:
# t = Sa + 2Sb = 3(Sa + Sb) - (2Sa + Sb)
# >= 3 * dis - V
# on the other hand, Sb is non-negative
# Sb = t - dis
t += max(dis * 3 - V, dis)
if t > T:
return False
prev = cur
return True
def binSearch(S, T, stations): # O(logS * M)
"""
to find the least tank volume to enable the aircraft to complete the journey
the fastest way is to complete the whole journey with the speed of 2km/min, at 2L/km
V <= 2S
"""
l = stations[0]
r = S * 2
for i in range(1, len(stations)):
l = max(stations[i] - stations[i - 1], l)
l = max(l, S - stations[-1])
r = 2 * l
if T < S:
return float("inf")
while l + 1 < r:
m = l + (r - l) // 2
if roadToCinema(m, S, T, stations) == True:
r = m
else:
l = m
if roadToCinema(l, S, T, stations):
return l
if roadToCinema(r, S, T, stations):
return r
return float("inf")
def __starting_point(): # O(logS * M + N)
line = sys.stdin.readline()
[N, M, S, T] = list(map(int, line.split(" ")))
aircrafts = []
for i in range(N):
[c, v] = list(map(int, sys.stdin.readline().split(" ")))
aircrafts.append([c, v])
stations = list(map(int, sys.stdin.readline().split(" ")))
stations.sort()
minVolume = binSearch(S, T, stations)
if minVolume == float("inf"):
# no aircraft can complete the journey
print(-1)
else:
res = float("inf")
for i in range(N):
if aircrafts[i][1] >= minVolume:
res = min(res, aircrafts[i][0])
if res == float('inf'):
# no given aircraft can complete the journey
print(-1)
else:
print(res)
__starting_point()
``` | vfc_16318 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/729/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 1 8 10\n10 8\n5 7\n11 9\n3\n",
"output": "10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1643 | Solve the following coding problem using the programming language python:
The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
Kirk has a binary string $s$ (a string which consists of zeroes and ones) of length $n$ and he is asking you to find a binary string $t$ of the same length which satisfies the following conditions: For any $l$ and $r$ ($1 \leq l \leq r \leq n$) the length of the longest non-decreasing subsequence of the substring $s_{l}s_{l+1} \ldots s_{r}$ is equal to the length of the longest non-decreasing subsequence of the substring $t_{l}t_{l+1} \ldots t_{r}$; The number of zeroes in $t$ is the maximum possible.
A non-decreasing subsequence of a string $p$ is a sequence of indices $i_1, i_2, \ldots, i_k$ such that $i_1 < i_2 < \ldots < i_k$ and $p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$. The length of the subsequence is $k$.
If there are multiple substrings which satisfy the conditions, output any.
-----Input-----
The first line contains a binary string of length not more than $10^5$.
-----Output-----
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
-----Examples-----
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
-----Note-----
In the first example: For the substrings of the length $1$ the length of the longest non-decreasing subsequnce is $1$; For $l = 1, r = 2$ the longest non-decreasing subsequnce of the substring $s_{1}s_{2}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{2}$ is $01$; For $l = 1, r = 3$ the longest non-decreasing subsequnce of the substring $s_{1}s_{3}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{3}$ is $00$; For $l = 2, r = 3$ the longest non-decreasing subsequnce of the substring $s_{2}s_{3}$ is $1$ and the longest non-decreasing subsequnce of the substring $t_{2}t_{3}$ is $1$;
The second example is similar to the first one.
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
s=stdin.readline().strip()
dp=[0 for i in range(len(s)+2)]
ons=[0 for i in range(len(s)+2)]
zs=[0 for i in range(len(s)+2)]
for i in range(len(s)-1,-1,-1):
if s[i]=="1":
ons[i]+=1
if(i!=len(s)-1):
ons[i]+=ons[i+1]
z=0
for i in range(len(s)-1,-1,-1):
if(s[i]=="1"):
dp[i]=max(1+ons[i+1],z)
else:
dp[i]=max(dp[i+1]+1,1+ons[i+1])
z=dp[i]
zs[i]=z
ans=""
for i in range(len(s)):
if s[i]=="1":
x=dp[i]
y=1+dp[i+1]
if x==y:
ans+="0"
else:
ans+="1"
else:
ans+="0"
print(ans)
``` | vfc_16326 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1204/D2",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "110\n",
"output": "010\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1644 | Solve the following coding problem using the programming language python:
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius a_{i}, outer radius b_{i} and height h_{i}. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied: Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if b_{j} ≤ b_{i}. Rings should not fall one into the the other. That means one can place ring j on the ring i only if b_{j} > a_{i}. The total height of all rings used should be maximum possible.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of rings in factory's stock.
The i-th of the next n lines contains three integers a_{i}, b_{i} and h_{i} (1 ≤ a_{i}, b_{i}, h_{i} ≤ 10^9, b_{i} > a_{i}) — inner radius, outer radius and the height of the i-th ring respectively.
-----Output-----
Print one integer — the maximum height of the tower that can be obtained.
-----Examples-----
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
-----Note-----
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from operator import attrgetter, itemgetter
n = int(input());
arr = [[int(x) for x in input().split(' ')] for y in range(n)];
arr = sorted(arr, key=itemgetter(1,0,2), reverse=True);
dp = [0 for x in range(n)];
s = [];
for i in range(n):
while (s != [] and arr[s[-1]][0] >= arr[i][1]):
s.pop();
if (s != []):
dp[i] = dp[s[-1]];
dp[i] += arr[i][2];
s.append(i);
print(max(dp));
``` | vfc_16330 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/777/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 5 1\n2 6 2\n3 7 3\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 2 1\n1 3 3\n4 6 2\n5 7 1\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 2 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n6 10 4\n9 20 19\n8 11 18\n18 20 1\n19 20 8\n",
"output": "50\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n21 25 26\n14 30 22\n6 29 30\n13 23 21\n10 11 5\n",
"output": "99\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n45 73 26\n59 73 29\n30 74 9\n59 63 72\n73 84 79\n",
"output": "215\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1645 | Solve the following coding problem using the programming language python:
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array $c$ is a subarray of an array $b$ if $c$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array $[-1, 2, -3]$ is good, as all arrays $[-1]$, $[-1, 2]$, $[-1, 2, -3]$, $[2]$, $[2, -3]$, $[-3]$ have nonzero sums of elements. However, array $[-1, 2, -1, -3]$ isn't good, as his subarray $[-1, 2, -1]$ has sum of elements equal to $0$.
Help Eugene to calculate the number of nonempty good subarrays of a given array $a$.
-----Input-----
The first line of the input contains a single integer $n$ ($1 \le n \le 2 \times 10^5$) — the length of array $a$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$) — the elements of $a$.
-----Output-----
Output a single integer — the number of good subarrays of $a$.
-----Examples-----
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
-----Note-----
In the first sample, the following subarrays are good: $[1]$, $[1, 2]$, $[2]$, $[2, -3]$, $[-3]$. However, the subarray $[1, 2, -3]$ isn't good, as its subarray $[1, 2, -3]$ has sum of elements equal to $0$.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray $[41, -41, 41]$ isn't good, as its subarray $[41, -41]$ has sum of elements equal to $0$.
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(int(i) for i in input().split())
p=[0]*(n+1)
for i in range(0,n) :
p[i+1]+=p[i]+a[i]
ok=dict()
ans,l=0,0
for i in range(n+1) :
if p[i] in ok :
ok[p[i]]+=1
else :
ok[p[i]]=1
while ok[p[i]]>1:
ok[p[l]]-=1
l+=1
ans+=(i-l+1)
print(ans-n-1)
``` | vfc_16334 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1333/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 -3\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n41 -41 41\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n-1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1646 | Solve the following coding problem using the programming language python:
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".
You are given a correct string s.
You can perform two different operations on this string: swap any pair of adjacent characters (for example, "101" $\rightarrow$ "110"); replace "11" with "1" (for example, "110" $\rightarrow$ "10").
Let val(s) be such a number that s is its binary representation.
Correct string a is less than some other correct string b iff val(a) < val(b).
Your task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).
-----Input-----
The first line contains integer number n (1 ≤ n ≤ 100) — the length of string s.
The second line contains the string s consisting of characters "0" and "1". It is guaranteed that the string s is correct.
-----Output-----
Print one string — the minimum correct string that you can obtain from the given one.
-----Examples-----
Input
4
1001
Output
100
Input
1
1
Output
1
-----Note-----
In the first example you can obtain the answer by the following sequence of operations: "1001" $\rightarrow$ "1010" $\rightarrow$ "1100" $\rightarrow$ "100".
In the second example you can't obtain smaller answer no matter what operations you use.
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()
if s == '0':
print(0)
else:
print('1'+'0'*s.count('0'))
``` | vfc_16338 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/976/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1001\n",
"output": "100\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n1110111100001111011111111010110011111111011110000111101101011100110110001011000000101010110101011100\n",
"output": "1000000000000000000000000000000000000000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1647 | Solve the following coding problem using the programming language python:
Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long.
This story could be very sad but fairy godmother (Tolya's grandmother) decided to help them and restore their relationship. She secretly took Tolya's t-shirt and Valya's pullover and wants to make the letterings on them same. In order to do this, for one unit of mana she can buy a spell that can change some letters on the clothes. Your task is calculate the minimum amount of mana that Tolya's grandmother should spend to rescue love of Tolya and Valya.
More formally, letterings on Tolya's t-shirt and Valya's pullover are two strings with same length n consisting only of lowercase English letters. Using one unit of mana, grandmother can buy a spell of form (c_1, c_2) (where c_1 and c_2 are some lowercase English letters), which can arbitrary number of times transform a single letter c_1 to c_2 and vise-versa on both Tolya's t-shirt and Valya's pullover. You should find the minimum amount of mana that grandmother should spend to buy a set of spells that can make the letterings equal. In addition you should output the required set of spells.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the letterings.
The second line contains a string with length n, consisting of lowercase English letters — the lettering on Valya's pullover.
The third line contains the lettering on Tolya's t-shirt in the same format.
-----Output-----
In the first line output a single integer — the minimum amount of mana t required for rescuing love of Valya and Tolya.
In the next t lines output pairs of space-separated lowercase English letters — spells that Tolya's grandmother should buy. Spells and letters in spells can be printed in any order.
If there are many optimal answers, output any.
-----Examples-----
Input
3
abb
dad
Output
2
a d
b a
Input
8
drpepper
cocacola
Output
7
l e
e d
d c
c p
p o
o r
r a
-----Note-----
In first example it's enough to buy two spells: ('a','d') and ('b','a'). Then first letters will coincide when we will replace letter 'a' with 'd'. Second letters will coincide when we will replace 'b' with 'a'. Third letters will coincide when we will at first replace 'b' with 'a' and then 'a' with 'd'.
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('in.txt', 'r')
_ = input()
s = input()
t = input()
par = [i for i in range(26)]
def find(x):
if par[x] != x:
par[x] = find(par[x])
return par[x]
else:
return x
for i in range(len(s)):
a, b = find(ord(s[i])-97), find(ord(t[i])-97)
if a != b:
par[a] = b
res = 0
for i in range(26):
find(i)
for i in range(26):
res += max(0, par.count(i) - 1)
print(res)
for i in range(26):
d = []
for j in range(26):
if par[j] == i:
d.append(chr(j+97))
for j in range(len(d)-1):
print(d[j], d[j+1])
``` | vfc_16342 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/939/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\nabb\ndad\n",
"output": "2\nb d\nd a\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\ndrpepper\ncocacola\n",
"output": "7\nl e\ne d\nd c\nc p\np o\no r\nr a\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nh\np\n",
"output": "1\np h\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\nxc\nda\n",
"output": "2\nc a\nx d\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nbab\naab\n",
"output": "1\nb a\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15\nxrezbaoiksvhuww\ndcgcjrkafntbpbl\n",
"output": "15\nz c\nc r\nr i\ni a\nj h\nh l\nl w\nw b\nx d\ng e\no k\nk f\ns n\nu p\nv t\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1653 | Solve the following coding problem using the programming language python:
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A $\rightarrow$ BC B $\rightarrow$ AC C $\rightarrow$ AB AAA $\rightarrow$ empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
-----Input-----
The first line contains a string S (1 ≤ |S| ≤ 10^5). The second line contains a string T (1 ≤ |T| ≤ 10^5), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 10^5).
The following Q lines describe queries. The i-th of these lines contains four space separated integers a_{i}, b_{i}, c_{i}, d_{i}. These represent the i-th query: is it possible to create T[c_{i}..d_{i}] from S[a_{i}..b_{i}] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
-----Output-----
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
-----Example-----
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
-----Note-----
In the first query we can achieve the result, for instance, by using transitions $A A B \rightarrow A A A C \rightarrow \operatorname{AAA} A B \rightarrow A B$.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# python3
import sys
def read_all_following_lines():
lines = sys.stdin.readlines()
return (tuple(map(int, line.split())) for line in lines)
class AbcString(object):
def __init__(self, string):
self.prefix_bc = [0]
self.a_strike = [0]
bc, strike = 0, 0
for symbol in string:
if symbol == 'A':
strike += 1
else:
strike = 0
bc += 1
self.prefix_bc.append(bc)
self.a_strike.append(strike)
def get_info(self, begin, end):
bc = self.prefix_bc[end] - self.prefix_bc[begin]
trailing_a = min(self.a_strike[end], end - begin)
return bc, trailing_a
def can_mutate(start, finish):
from_bc, from_a = start
to_bc, to_a = finish
if (from_bc & 1) != (to_bc & 1): return False
if from_bc > to_bc: return False
if from_a < to_a: return False
if from_bc == to_bc: return (from_a - to_a) % 3 == 0
if from_a == to_a: return from_bc != 0
# from_bc < to_bc
# from_a > to_a
return True
def main():
s = AbcString(input())
t = AbcString(input())
input() # skip one line
requests = read_all_following_lines()
answer = ""
for (a, b, c, d) in requests:
can = can_mutate(s.get_info(a - 1, b), t.get_info(c - 1, d))
answer += "1" if can else "0"
print(answer)
main()
``` | vfc_16366 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/923/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3\n",
"output": "10011\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "AAAAAA\nAAAAAA\n30\n3 4 1 2\n3 3 4 4\n5 6 3 4\n3 3 2 3\n6 6 1 5\n2 4 4 6\n1 6 2 5\n6 6 3 4\n3 5 1 4\n4 5 3 6\n2 3 2 4\n3 4 4 4\n6 6 4 6\n3 3 2 5\n1 5 3 3\n4 6 1 2\n6 6 6 6\n3 3 3 4\n6 6 6 6\n5 6 4 4\n6 6 5 5\n2 3 1 4\n3 6 4 5\n3 5 6 6\n4 5 2 6\n5 6 6 6\n1 4 2 5\n4 5 2 5\n4 5 1 3\n2 2 4 6\n",
"output": "111001000000000010101000001000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "A\nA\n1\n1 1 1 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "CCBACACBCCCBBAAC\nCACCAAABAACBBBBAC\n20\n7 7 2 15\n3 11 14 15\n4 9 6 12\n10 15 13 17\n10 16 5 14\n14 15 12 16\n16 16 16 16\n3 15 9 14\n10 12 8 12\n15 15 9 10\n14 15 8 15\n7 14 17 17\n15 15 17 17\n15 15 5 9\n4 14 12 17\n13 15 8 12\n1 4 2 2\n6 13 17 17\n11 14 5 11\n15 16 2 9\n",
"output": "00001100101000010000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1655 | Solve the following coding problem using the programming language python:
Hands that shed innocent blood!
There are n guilty people in a line, the i-th of them holds a claw with length L_{i}. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - L_{i}.
You are given lengths of the claws. You need to find the total number of alive people after the bell rings.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of guilty people.
Second line contains n space-separated integers L_1, L_2, ..., L_{n} (0 ≤ L_{i} ≤ 10^9), where L_{i} is the length of the i-th person's claw.
-----Output-----
Print one integer — the total number of alive people after the bell rings.
-----Examples-----
Input
4
0 1 0 10
Output
1
Input
2
0 0
Output
2
Input
10
1 1 3 0 0 0 2 1 0 3
Output
3
-----Note-----
In first sample the last person kills everyone in front of him.
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()]
alive = 0
left = n
for i in range(n - 1, -1, -1):
if i < left:
alive += 1
left = min(left, i - a[i])
print(alive)
``` | vfc_16374 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/892/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n0 1 0 10\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n0 0\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1 3 0 0 0 2 1 0 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n0 0 2 0 0 3 3 2 2 0\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n0\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1656 | Solve the following coding problem using the programming language python:
Recall that string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly zero or all) characters. For example, for the string $a$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".
The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead.
Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv"
For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv"
Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.
For a given string $s$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $s$ from another string replacing "w" with "vv". For example, $s$ can be equal to "vov".
-----Input-----
The input contains a single non-empty string $s$, consisting only of characters "v" and "o". The length of $s$ is at most $10^6$.
-----Output-----
Output a single integer, the wow factor of $s$.
-----Examples-----
Input
vvvovvv
Output
4
Input
vvovooovovvovoovoovvvvovovvvov
Output
100
-----Note-----
The first example is explained in the legend.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = input()
n = len(s)
p = [0] * (n+1)
for x in range(1, n):
y = 0
if s[x] == 'v' and s[x-1] == 'v':
y = 1
p[x+1] = p[x] + y
q = 0
sol = 0
for x in range(n-3, -1, -1):
if s[x+1] == 'v' and s[x+2] == 'v':
q += 1
if s[x] == 'o':
sol += q*p[x]
print(sol)
``` | vfc_16378 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1178/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "vvvovvv\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
Subsets and Splits