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 | 2006 | Solve the following coding problem using the programming language python:
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".
The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs:
some dwarf in one of the chosen lines is located in the rightmost cell of his row; some dwarf in the chosen lines is located in the cell with the candy.
The point of the game is to transport all the dwarves to the candy cells.
Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.
-----Input-----
The first line of the input contains two integers n and m (1 ≤ n ≤ 1000; 2 ≤ m ≤ 1000).
Next n lines each contain m characters — the game field for the "Candy Martix 2: Reload". Character "*" represents an empty cell of the field, character "G" represents a dwarf and character "S" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character "G" and one character "S".
-----Output-----
In a single line print a single integer — either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field.
-----Examples-----
Input
3 4
*G*S
G**S
*G*S
Output
2
Input
1 3
S*G
Output
-1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
H, W = list(map(int, input().split()))
L = set()
for y in range(H):
row = input().strip()
i_sweet = row.find('S')
i_gnome = row.find('G')
if i_sweet == -1 or i_gnome > i_sweet:
print(-1)
return
L.add(i_sweet - i_gnome)
print(len(L))
``` | vfc_17778 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/400/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4\n*G*S\nG**S\n*G*S\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 3\nS*G\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2007 | Solve the following coding problem using the programming language python:
You are given a graph with $n$ nodes and $m$ directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is $3$. Your task is find a path whose value is the largest.
-----Input-----
The first line contains two positive integers $n, m$ ($1 \leq n, m \leq 300\,000$), denoting that the graph has $n$ nodes and $m$ directed edges.
The second line contains a string $s$ with only lowercase English letters. The $i$-th character is the letter assigned to the $i$-th node.
Then $m$ lines follow. Each line contains two integers $x, y$ ($1 \leq x, y \leq n$), describing a directed edge from $x$ to $y$. Note that $x$ can be equal to $y$ and there can be multiple edges between $x$ and $y$. Also the graph can be not connected.
-----Output-----
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
-----Examples-----
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
-----Note-----
In the first sample, the path with largest value is $1 \to 3 \to 4 \to 5$. The value is $3$ because the letter 'a' appears $3$ times.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# NOT MY CODE
# https://codeforces.com/contest/919/submission/80857731
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
to = f(*args, **kwargs)
if stack:
return to
else:
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
return to
to = stack[-1].send(to)
return wrappedfunc
import sys
input=sys.stdin.readline
from collections import defaultdict as dd
'''
def iscyclic(g):
for i in range(1,n+1):
if(
'''
n,m=list(map(int,input().split()))
s=input()
d=dd(list)
lol=0
for i in range(m):
u,v=list(map(int,input().split()))
if(u==v):
lol=1
print(-1)
return
d[u].append(v)
'''
if(iscyclic(d)):
lol=1
print(-1)
return
'''
vis=[0]*(n+1)
rvis=[0]*(n+1)
cou=[0]
dp=[dd(int) for i in range(n+1)]
mx=[0]
h=[0]
#print(d)
@bootstrap
def dfs(u):
if(h[0]==1):
yield
vis[u]=1
rvis[u]=1
for i in d[u]:
if(h[0]==1):
yield
if(vis[i]==0):
yield dfs(i)
if(h[0]==1):
yield
elif(rvis[i]==True):
h[0]=1
yield
rvis[u]=0
if(h[0]==1):
yield
for i in d[u]:
for j in dp[i]:
dp[u][j]=max(dp[u][j],dp[i][j])
mx[0]=max(mx[0],dp[u][j])
dp[u][s[u-1]]+=1
#print(u,dp[u])
mx[0]=max(mx[0],dp[u][s[u-1]])
yield
#print(dp)
for i in range(1,n+1):
if(vis[i]==0):
cou=[0]
dfs(i)
if(h[0]):
print(-1)
else:
print(mx[0])
``` | vfc_17782 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/919/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 4\nabaca\n1 2\n1 3\n3 4\n4 5\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 6\nxzyabc\n1 2\n3 1\n2 3\n5 4\n4 3\n6 4\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 14\nxzyzyzyzqx\n1 2\n2 4\n3 5\n4 5\n2 6\n6 8\n6 5\n2 10\n3 9\n10 9\n4 6\n1 10\n2 8\n3 7\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\nf\n1 1\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2008 | Solve the following coding problem using the programming language python:
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $n$ high school students numbered from $1$ to $n$. Initially, each student $i$ is on position $i$. Each student $i$ is characterized by two numbers — $a_i$ and $b_i$. Dissatisfaction of the person $i$ equals the product of $a_i$ by the number of people standing to the left of his position, add the product $b_i$ by the number of people standing to the right of his position. Formally, the dissatisfaction of the student $i$, which is on the position $j$, equals $a_i \cdot (j-1) + b_i \cdot (n-j)$.
The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.
Although Stas is able to solve such problems, this was not given to him. He turned for help to you.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of people in the queue.
Each of the following $n$ lines contains two integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq 10^8$) — the characteristic of the student $i$, initially on the position $i$.
-----Output-----
Output one integer — minimum total dissatisfaction which can be achieved by rearranging people in the queue.
-----Examples-----
Input
3
4 2
2 3
6 1
Output
12
Input
4
2 4
3 3
7 1
2 3
Output
25
Input
10
5 10
12 4
31 45
20 55
30 17
29 30
41 32
7 1
5 5
3 15
Output
1423
-----Note-----
In the first example it is optimal to put people in this order: ($3, 1, 2$). The first person is in the position of $2$, then his dissatisfaction will be equal to $4 \cdot 1+2 \cdot 1=6$. The second person is in the position of $3$, his dissatisfaction will be equal to $2 \cdot 2+3 \cdot 0=4$. The third person is in the position of $1$, his dissatisfaction will be equal to $6 \cdot 0+1 \cdot 2=2$. The total dissatisfaction will be $12$.
In the second example, you need to put people in this order: ($3, 2, 4, 1$). The total dissatisfaction will be $25$.
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 = []
for i in range(n):
a, b = map(int, input().split())
S.append([a, b])
S.sort(key=lambda x: (x[1] - x[0]))
cnt = 0
for i in range(n):
cnt += S[i][0] * i + S[i][1] * (n - i - 1)
print(cnt)
``` | vfc_17786 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1151/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n4 2\n2 3\n6 1\n",
"output": "12",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2 4\n3 3\n7 1\n2 3\n",
"output": "25",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n5 10\n12 4\n31 45\n20 55\n30 17\n29 30\n41 32\n7 1\n5 5\n3 15\n",
"output": "1423",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "18\n29 15\n31 7\n6 30\n42 2\n28 11\n45 36\n45 6\n45 33\n41 10\n41 32\n44 34\n24 25\n7 31\n4 45\n41 16\n40 5\n6 20\n37 36\n",
"output": "6057",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "18\n19 24\n49 18\n15 24\n22 50\n30 4\n38 33\n22 14\n22 15\n27 40\n44 30\n34 17\n18 30\n13 44\n43 4\n21 11\n42 12\n37 28\n41 42\n",
"output": "6561",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2009 | Solve the following coding problem using the programming language python:
Alice lives on a flat planet that can be modeled as a square grid of size $n \times n$, with rows and columns enumerated from $1$ to $n$. We represent the cell at the intersection of row $r$ and column $c$ with ordered pair $(r, c)$. Each cell in the grid is either land or water.
[Image] An example planet with $n = 5$. It also appears in the first sample test.
Alice resides in land cell $(r_1, c_1)$. She wishes to travel to land cell $(r_2, c_2)$. At any moment, she may move to one of the cells adjacent to where she is—in one of the four directions (i.e., up, down, left, or right).
Unfortunately, Alice cannot swim, and there is no viable transportation means other than by foot (i.e., she can walk only on land). As a result, Alice's trip may be impossible.
To help Alice, you plan to create at most one tunnel between some two land cells. The tunnel will allow Alice to freely travel between the two endpoints. Indeed, creating a tunnel is a lot of effort: the cost of creating a tunnel between cells $(r_s, c_s)$ and $(r_t, c_t)$ is $(r_s-r_t)^2 + (c_s-c_t)^2$.
For now, your task is to find the minimum possible cost of creating at most one tunnel so that Alice could travel from $(r_1, c_1)$ to $(r_2, c_2)$. If no tunnel needs to be created, the cost is $0$.
-----Input-----
The first line contains one integer $n$ ($1 \leq n \leq 50$) — the width of the square grid.
The second line contains two space-separated integers $r_1$ and $c_1$ ($1 \leq r_1, c_1 \leq n$) — denoting the cell where Alice resides.
The third line contains two space-separated integers $r_2$ and $c_2$ ($1 \leq r_2, c_2 \leq n$) — denoting the cell to which Alice wishes to travel.
Each of the following $n$ lines contains a string of $n$ characters. The $j$-th character of the $i$-th such line ($1 \leq i, j \leq n$) is 0 if $(i, j)$ is land or 1 if $(i, j)$ is water.
It is guaranteed that $(r_1, c_1)$ and $(r_2, c_2)$ are land.
-----Output-----
Print an integer that is the minimum possible cost of creating at most one tunnel so that Alice could travel from $(r_1, c_1)$ to $(r_2, c_2)$.
-----Examples-----
Input
5
1 1
5 5
00001
11111
00111
00110
00110
Output
10
Input
3
1 3
3 1
010
101
010
Output
8
-----Note-----
In the first sample, a tunnel between cells $(1, 4)$ and $(4, 5)$ should be created. The cost of doing so is $(1-4)^2 + (4-5)^2 = 10$, which is optimal. This way, Alice could walk from $(1, 1)$ to $(1, 4)$, use the tunnel from $(1, 4)$ to $(4, 5)$, and lastly walk from $(4, 5)$ to $(5, 5)$.
In the second sample, clearly a tunnel between cells $(1, 3)$ and $(3, 1)$ needs to be created. The cost of doing so is $(1-3)^2 + (3-1)^2 = 8$.
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())
r1, c1 = map(int, input().split())
r2, c2 = map(int, input().split())
a = [['1'] * (n + 2)]
for _ in range(n):
s = input()
d = ['1']
for i in s:
d.append(i)
d.append('1')
a.append(d)
a.append(['1'] * (n + 2))
s = []
f = []
q = [[r1, c1]]
while q:
x, y = q.pop()
a[x][y] = '1'
s.append([x, y])
if a[x - 1][y] == '0':
q.append([x - 1, y])
if a[x][y - 1] == '0':
q.append([x, y - 1])
if a[x + 1][y] == '0':
q.append([x + 1, y])
if a[x][y + 1] == '0':
q.append([x, y + 1])
if [r2, c2] in s:
print(0)
else:
q = [[r2, c2]]
while q:
x, y = q.pop()
a[x][y] = '1'
f.append([x, y])
if a[x - 1][y] == '0':
q.append([x - 1, y])
if a[x][y - 1] == '0':
q.append([x, y - 1])
if a[x + 1][y] == '0':
q.append([x + 1, y])
if a[x][y + 1] == '0':
q.append([x, y + 1])
res = 10**10
for i in s:
for j in f:
res = min(res, (i[0] - j[0])**2 + (i[1] - j[1])**2)
print(res)
``` | vfc_17790 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1130/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 1\n5 5\n00001\n11111\n00111\n00110\n00110\n",
"output": "10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2011 | Solve the following coding problem using the programming language python:
There are $n$ people in this world, conveniently numbered $1$ through $n$. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let $d(a,b)$ denote the debt of $a$ towards $b$, or $0$ if there is no such debt.
Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money.
When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done: Let $d(a,b) > 0$ and $d(c,d) > 0$ such that $a \neq c$ or $b \neq d$. We can decrease the $d(a,b)$ and $d(c,d)$ by $z$ and increase $d(c,b)$ and $d(a,d)$ by $z$, where $0 < z \leq \min(d(a,b),d(c,d))$. Let $d(a,a) > 0$. We can set $d(a,a)$ to $0$.
The total debt is defined as the sum of all debts:
$$\Sigma_d = \sum_{a,b} d(a,b)$$
Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.
-----Input-----
The first line contains two space separated integers $n$ ($1 \leq n \leq 10^5$) and $m$ ($0 \leq m \leq 3\cdot 10^5$), representing the number of people and the number of debts, respectively.
$m$ lines follow, each of which contains three space separated integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n, u_i \neq v_i$), $d_i$ ($1 \leq d_i \leq 10^9$), meaning that the person $u_i$ borrowed $d_i$ burles from person $v_i$.
-----Output-----
On the first line print an integer $m'$ ($0 \leq m' \leq 3\cdot 10^5$), representing the number of debts after the consolidation. It can be shown that an answer always exists with this additional constraint.
After that print $m'$ lines, $i$-th of which contains three space separated integers $u_i, v_i, d_i$, meaning that the person $u_i$ owes the person $v_i$ exactly $d_i$ burles. The output must satisfy $1 \leq u_i, v_i \leq n$, $u_i \neq v_i$ and $0 < d_i \leq 10^{18}$.
For each pair $i \neq j$, it should hold that $u_i \neq u_j$ or $v_i \neq v_j$. In other words, each pair of people can be included at most once in the output.
-----Examples-----
Input
3 2
1 2 10
2 3 5
Output
2
1 2 5
1 3 5
Input
3 3
1 2 10
2 3 15
3 1 10
Output
1
2 3 5
Input
4 2
1 2 12
3 4 8
Output
2
1 2 12
3 4 8
Input
3 4
2 3 1
2 3 2
2 3 4
2 3 8
Output
1
2 3 15
-----Note-----
In the first example the optimal sequence of operations can be the following: Perform an operation of the first type with $a = 1$, $b = 2$, $c = 2$, $d = 3$ and $z = 5$. The resulting debts are: $d(1, 2) = 5$, $d(2, 2) = 5$, $d(1, 3) = 5$, all other debts are $0$; Perform an operation of the second type with $a = 2$. The resulting debts are: $d(1, 2) = 5$, $d(1, 3) = 5$, all other debts are $0$.
In the second example the optimal sequence of operations can be the following: Perform an operation of the first type with $a = 1$, $b = 2$, $c = 3$, $d = 1$ and $z = 10$. The resulting debts are: $d(3, 2) = 10$, $d(2, 3) = 15$, $d(1, 1) = 10$, all other debts are $0$; Perform an operation of the first type with $a = 2$, $b = 3$, $c = 3$, $d = 2$ and $z = 10$. The resulting debts are: $d(2, 2) = 10$, $d(3, 3) = 10$, $d(2, 3) = 5$, $d(1, 1) = 10$, all other debts are $0$; Perform an operation of the second type with $a = 2$. The resulting debts are: $d(3, 3) = 10$, $d(2, 3) = 5$, $d(1, 1) = 10$, all other debts are $0$; Perform an operation of the second type with $a = 3$. The resulting debts are: $d(2, 3) = 5$, $d(1, 1) = 10$, all other debts are $0$; Perform an operation of the second type with $a = 1$. The resulting debts are: $d(2, 3) = 5$, all other debts are $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
import math
input = sys.stdin.readline
n,m=map(int,input().split())
arr=[0]*n
for i in range(m):
u,v,d=map(int,input().split())
arr[u-1]-=d
arr[v-1]+=d
pos=[]
neg=[]
for i in range(n):
if arr[i]>0:
pos.append([i,arr[i]])
elif arr[i]<0:
neg.append([i,-arr[i]])
# print(pos,neg)
ans=[]
j=0
for i in range(len(neg)):
while neg[i][1]>0:
# print(j)
if pos[j][1]>=neg[i][1]:
ans.append([neg[i][0]+1,pos[j][0]+1,neg[i][1]])
pos[j][1]-=neg[i][1]
neg[i][1]=0
if pos[j][1]==0:
j+=1
else:
ans.append([neg[i][0]+1,pos[j][0]+1,pos[j][1]])
neg[i][1]-=pos[j][1]
pos[j][1]=0
j+=1
print(len(ans))
for i in range(len(ans)):
print(*ans[i])
``` | vfc_17798 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1266/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n1 2 10\n2 3 5\n",
"output": "2\n1 2 5\n1 3 5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2012 | Solve the following coding problem using the programming language python:
Stepan had a favorite string s which consisted of the lowercase letters of the Latin alphabet.
After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers c_1, c_2, ..., c_{n}, where n equals the length of the string s, and c_{i} equals the number of substrings in the string s with the length i, consisting of the same letters. The substring is a sequence of consecutive characters in the string s.
For example, if the Stepan's favorite string is equal to "tttesst", the sequence c looks like: c = [7, 3, 1, 0, 0, 0, 0].
Stepan asks you to help to repair his favorite string s according to the given sequence c_1, c_2, ..., c_{n}.
-----Input-----
The first line contains the integer n (1 ≤ n ≤ 2000) — the length of the Stepan's favorite string.
The second line contains the sequence of integers c_1, c_2, ..., c_{n} (0 ≤ c_{i} ≤ 2000), where c_{i} equals the number of substrings of the string s with the length i, consisting of the same letters.
It is guaranteed that the input data is such that the answer always exists.
-----Output-----
Print the repaired Stepan's favorite string. If there are several answers, it is allowed to print any of them. The string should contain only lowercase letters of the English alphabet.
-----Examples-----
Input
6
6 3 1 0 0 0
Output
kkrrrq
Input
4
4 0 0 0
Output
abcd
-----Note-----
In the first test Stepan's favorite string, for example, can be the string "kkrrrq", because it contains 6 substrings with the length 1, consisting of identical letters (they begin in positions 1, 2, 3, 4, 5 and 6), 3 substrings with the length 2, consisting of identical letters (they begin in positions 1, 3 and 4), and 1 substring with the length 3, consisting of identical letters (it begins in the position 3).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
n = int(input())
c = list(map(int, input().split()))
cc = ord('a')
ans = ""
cur = n - 1
if 1:
cur = n - 1
while cur >= 0:
while c[cur] > 0:
if chr(cc) > 'z':
cc = ord('a')
ans += chr(cc) * (cur + 1)
c[cur] -= 1
for i in range(cur):
c[i] -= (cur - i + 1)
cc += 1
cur -= 1
print(ans)
``` | vfc_17802 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/774/H",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n6 3 1 0 0 0\n",
"output": "aaabbc\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2013 | Solve the following coding problem using the programming language python:
Petya has a rectangular Board of size $n \times m$. Initially, $k$ chips are placed on the board, $i$-th chip is located in the cell at the intersection of $sx_i$-th row and $sy_i$-th column.
In one action, Petya can move all the chips to the left, right, down or up by $1$ cell.
If the chip was in the $(x, y)$ cell, then after the operation: left, its coordinates will be $(x, y - 1)$; right, its coordinates will be $(x, y + 1)$; down, its coordinates will be $(x + 1, y)$; up, its coordinates will be $(x - 1, y)$.
If the chip is located by the wall of the board, and the action chosen by Petya moves it towards the wall, then the chip remains in its current position.
Note that several chips can be located in the same cell.
For each chip, Petya chose the position which it should visit. Note that it's not necessary for a chip to end up in this position.
Since Petya does not have a lot of free time, he is ready to do no more than $2nm$ actions.
You have to find out what actions Petya should do so that each chip visits the position that Petya selected for it at least once. Or determine that it is not possible to do this in $2nm$ actions.
-----Input-----
The first line contains three integers $n, m, k$ ($1 \le n, m, k \le 200$) — the number of rows and columns of the board and the number of chips, respectively.
The next $k$ lines contains two integers each $sx_i, sy_i$ ($ 1 \le sx_i \le n, 1 \le sy_i \le m$) — the starting position of the $i$-th chip.
The next $k$ lines contains two integers each $fx_i, fy_i$ ($ 1 \le fx_i \le n, 1 \le fy_i \le m$) — the position that the $i$-chip should visit at least once.
-----Output-----
In the first line print the number of operations so that each chip visits the position that Petya selected for it at least once.
In the second line output the sequence of operations. To indicate operations left, right, down, and up, use the characters $L, R, D, U$ respectively.
If the required sequence does not exist, print -1 in the single line.
-----Examples-----
Input
3 3 2
1 2
2 1
3 3
3 2
Output
3
DRD
Input
5 4 3
3 4
3 1
3 3
5 3
1 3
1 4
Output
9
DDLUUUURR
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())
s = 'U' * (n - 1)
s += 'L' * (m - 1)
for i in range(n):
if (i % 2 == 0):
s += 'R' * (m - 1)
else:
s += 'L' * (m - 1)
if i != n - 1:
s += 'D'
print(len(s))
print(s)
``` | vfc_17806 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1327/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3 2\n1 2\n2 1\n3 3\n3 2\n",
"output": "12\nUULLRRDLLDRR",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 4 3\n3 4\n3 1\n3 3\n5 3\n1 3\n1 4\n",
"output": "26\nUUUULLLRRRDLLLDRRRDLLLDRRR",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2014 | Solve the following coding problem using the programming language python:
Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?
You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
-----Input-----
The first line contains two integers n and k (1 ≤ n ≤ 1000; 2 ≤ k ≤ 5). Each of the next k lines contains integers 1, 2, ..., n in some order — description of the current permutation.
-----Output-----
Print the length of the longest common subsequence.
-----Examples-----
Input
4 3
1 4 2 3
4 1 2 3
1 2 4 3
Output
3
-----Note-----
The answer for the first test sample is subsequence [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
def main():
n, k = tuple(map(int, input().split()))
a = [set(range(n)) for _ in range(n)]
for i in range(k):
p = set()
for j in map(int, input().split()):
a[j-1] -= p
p.add(j-1)
sa = sorted(list(range(n)), key=lambda i: len(a[i]))
maxx = [0] * n
res = 0
for i in sa:
m = 1 + maxx[max(a[i], key=lambda e: maxx[e])] if a[i] else 0
maxx[i] = m
res = max(res, m)
print(res)
def __starting_point():
main()
__starting_point()
``` | vfc_17810 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/463/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n1 4 2 3\n4 1 2 3\n1 2 4 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 3\n2 5 1 4 6 3\n5 1 4 3 2 6\n5 4 2 6 3 1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "41 4\n24 15 17 35 13 41 4 14 23 5 8 16 21 18 30 36 6 22 11 29 26 1 40 31 7 3 32 10 28 38 12 20 39 37 34 19 33 27 2 25 9\n22 13 25 24 38 35 29 12 15 8 11 37 3 19 4 23 18 32 30 40 36 21 16 34 27 9 5 41 39 2 14 17 31 33 26 7 1 10 20 6 28\n31 27 39 16 22 12 13 32 6 10 19 29 37 7 18 33 24 21 1 9 36 4 34 41 25 28 17 40 30 35 23 14 11 8 2 15 38 20 26 5 3\n8 18 39 38 7 34 16 31 15 1 40 20 37 4 25 11 17 19 33 26 6 14 13 41 12 32 2 21 10 35 27 9 28 5 30 24 22 23 29 3 36\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\n1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "28 5\n3 14 12 16 13 27 20 8 1 10 24 11 5 9 7 18 17 23 22 25 28 19 4 21 26 6 15 2\n7 12 23 27 22 26 16 18 19 5 6 9 11 28 25 4 10 3 1 14 8 17 15 2 20 13 24 21\n21 20 2 5 19 15 12 4 18 9 23 16 11 14 8 6 25 27 13 17 10 26 7 24 28 1 3 22\n12 2 23 11 20 18 25 21 13 27 14 8 4 6 9 16 7 3 10 1 22 15 26 19 5 17 28 24\n13 2 6 19 22 23 4 1 28 10 18 17 21 8 9 3 26 11 12 27 14 20 24 25 15 5 16 7\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 3\n2 5 1 4 6 3\n5 1 4 6 2 3\n5 4 2 6 3 1\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2015 | Solve the following coding problem using the programming language python:
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide $3$ red, $3$ green and $3$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, $1$ red, $10$ green and $2$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of sets of lamps Polycarp has bought.
Each of the next $t$ lines contains three integers $r$, $g$ and $b$ ($1 \le r, g, b \le 10^9$) — the number of red, green and blue lamps in the set, respectively.
-----Output-----
Print $t$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
-----Example-----
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
-----Note-----
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t=int(input())
for _ in range(t):
a,b,c=list(map(int,input().split()))
a,b,c=sorted([a,b,c])
if a+b>=c-1:
print("Yes")
else:
print("No")
``` | vfc_17814 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1279/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 3 3\n1 10 2\n2 1 1\n",
"output": "Yes\nNo\nYes\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2016 | Solve the following coding problem using the programming language python:
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.
Vova's character can learn new spells during the game. Every spell is characterized by two values x_{i} and y_{i} — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal x·z damage and spend y·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously.
Also Vova can fight monsters. Every monster is characterized by two values t_{j} and h_{j} — monster kills Vova's character in t_{j} seconds and has h_{j} health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones.
Vova's character kills a monster, if he deals h_{j} damage to it in no more than t_{j} seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in t_{j} seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight.
You have to write a program which can answer two types of queries:
1 x y — Vova's character learns new spell which deals x damage per second and costs y mana per second. 2 t h — Vova fights the monster which kills his character in t seconds and has h health points.
Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.
For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.
-----Input-----
The first line contains two integer numbers q and m (2 ≤ q ≤ 10^5, 1 ≤ m ≤ 10^12) — the number of queries and the amount of mana at the beginning of every fight.
i-th of each next q lines contains three numbers k_{i}, a_{i} and b_{i} (1 ≤ k_{i} ≤ 2, 1 ≤ a_{i}, b_{i} ≤ 10^6).
Using them you can restore queries this way: let j be the index of the last query of second type with positive answer (j = 0 if there were none of these). If k_{i} = 1, then character learns spell with x = (a_{i} + j) mod 10^6 + 1, y = (b_{i} + j) mod 10^6 + 1. If k_{i} = 2, then you have to determine if Vova is able to win the fight against monster with t = (a_{i} + j) mod 10^6 + 1, h = (b_{i} + j) mod 10^6 + 1.
-----Output-----
For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise.
-----Example-----
Input
3 100
1 4 9
2 19 49
2 19 49
Output
YES
NO
-----Note-----
In first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana.
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
# solution after hint
# (instead of best hit/mana spell store convex hull of spells)
# O(n^2) instead of O(n log n)
[q, m] = list(map(int, input().strip().split()))
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]
mod = 10**6
j = 0
spell_chull = [(0, 0)] # lower hull _/
def is_right(xy0, xy1, xy):
(x0, y0) = xy0
(x1, y1) = xy1
(x, y) = xy
return (x0 - x) * (y1 - y) >= (x1 - x) * (y0 - y)
def in_chull(x, y):
i = 0
if x > spell_chull[-1][0]:
return False
while spell_chull[i][0] < x:
i += 1
if spell_chull[i][0] == x:
return spell_chull[i][1] <= y
else:
return is_right(spell_chull[i - 1], spell_chull[i], (x, y))
def add_spell(x, y):
nonlocal spell_chull
if in_chull(x, y):
return
i_left = 0
while i_left < len(spell_chull) - 1 and not is_right(spell_chull[i_left + 1], spell_chull[i_left], (x, y)):
i_left += 1
i_right = i_left + 1
while i_right < len(spell_chull) - 1 and is_right(spell_chull[i_right + 1], spell_chull[i_right], (x, y)):
i_right += 1
if i_right == len(spell_chull) - 1 and x >= spell_chull[-1][0]:
i_right += 1
spell_chull = spell_chull[:i_left + 1] + [(x, y)] + spell_chull[i_right:]
for i, qi in enumerate(qis):
(k, a, b) = qi
x = (a + j) % mod + 1
y = (b + j) % mod + 1
if k == 1:
add_spell(x, y)
else: #2
if in_chull(y / x, m / x):
print ('YES')
j = i + 1
else:
print ('NO')
``` | vfc_17818 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/792/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 100\n1 4 9\n2 19 49\n2 19 49\n",
"output": "YES\nNO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2018 | Solve the following coding problem using the programming language python:
Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by $n$ sectors, and the outer area is equally divided by $m$ sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position.
$0$
The inner area's sectors are denoted as $(1,1), (1,2), \dots, (1,n)$ in clockwise direction. The outer area's sectors are denoted as $(2,1), (2,2), \dots, (2,m)$ in the same manner. For a clear understanding, see the example image above.
Amugae wants to know if he can move from one sector to another sector. He has $q$ questions.
For each question, check if he can move between two given sectors.
-----Input-----
The first line contains three integers $n$, $m$ and $q$ ($1 \le n, m \le 10^{18}$, $1 \le q \le 10^4$) — the number of sectors in the inner area, the number of sectors in the outer area and the number of questions.
Each of the next $q$ lines contains four integers $s_x$, $s_y$, $e_x$, $e_y$ ($1 \le s_x, e_x \le 2$; if $s_x = 1$, then $1 \le s_y \le n$, otherwise $1 \le s_y \le m$; constraints on $e_y$ are similar). Amague wants to know if it is possible to move from sector $(s_x, s_y)$ to sector $(e_x, e_y)$.
-----Output-----
For each question, print "YES" if Amugae can move from $(s_x, s_y)$ to $(e_x, e_y)$, and "NO" otherwise.
You can print each letter in any case (upper or lower).
-----Example-----
Input
4 6 3
1 1 2 3
2 6 1 2
2 6 2 4
Output
YES
NO
YES
-----Note-----
Example is shown on the picture in the statement.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from math import gcd
n, m, q = map(int, input().split())
d = gcd(n, m)
x = n // d
y = m // d
for _ in range(q):
sx, sy, ex, ey = map(int, input().split())
p1 = 0
p2 = 0
if sx == 1:
p1 = (sy - 1) // x
else:
p1 = (sy - 1) // y
if ex == 1:
p2 = (ey - 1) // x
else:
p2 = (ey - 1) // y
if p1 == p2:
print('YES')
else:
print('NO')
``` | vfc_17826 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1200/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 6 3\n1 1 2 3\n2 6 1 2\n2 6 2 4\n",
"output": "YES\nNO\nYES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3 5\n2 3 1 2\n2 3 2 3\n1 1 1 1\n1 2 1 2\n2 1 2 1\n",
"output": "YES\nYES\nYES\nYES\nYES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 10\n1 1 1 1\n1 1 1 1\n1 1 2 1\n1 1 1 1\n2 1 2 1\n2 1 1 1\n1 1 2 1\n1 1 2 1\n2 1 1 1\n2 1 1 1\n",
"output": "YES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "999999937 999999929 1\n2 501178581 1 294328591\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "999999929 999999937 1\n2 271242041 1 483802068\n",
"output": "YES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2019 | Solve the following coding problem using the programming language python:
Alica and Bob are playing a game.
Initially they have a binary string $s$ consisting of only characters 0 and 1.
Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $s$ and delete them. For example, if $s = 1011001$ then the following moves are possible: delete $s_1$ and $s_2$: $\textbf{10}11001 \rightarrow 11001$; delete $s_2$ and $s_3$: $1\textbf{01}1001 \rightarrow 11001$; delete $s_4$ and $s_5$: $101\textbf{10}01 \rightarrow 10101$; delete $s_6$ and $s_7$: $10110\textbf{01} \rightarrow 10110$.
If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.
-----Input-----
First line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases.
Only line of each test case contains one string $s$ ($1 \le |s| \le 100$), consisting of only characters 0 and 1.
-----Output-----
For each test case print answer in the single line.
If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.
-----Example-----
Input
3
01
1111
0011
Output
DA
NET
NET
-----Note-----
In the first test case after Alice's move string $s$ become empty and Bob can not make any move.
In the second test case Alice can not make any move initially.
In the third test case after Alice's move string $s$ turn into $01$. Then, after Bob's move string $s$ become empty and Alice can not make any move.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t = int(input())
for _ in range(t):
s = [int(i) for i in input()]
ct0 = 0
ct1 = 0
for i in s:
if i == 1:
ct1 += 1
else:
ct0 += 1
ct = min(ct0, ct1)
if ct%2:
print("DA")
else:
print("NET")
``` | vfc_17830 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1373/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n01\n1111\n0011\n",
"output": "DA\nNET\nNET\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2021 | Solve the following coding problem using the programming language python:
You came to a local shop and want to buy some chocolate bars. There are $n$ bars in the shop, $i$-th of them costs $a_i$ coins (and you want to buy all of them).
You have $m$ different coupons that allow you to buy chocolate bars. $i$-th coupon allows you to buy $q_i$ chocolate bars while you have to pay only for the $q_i - 1$ most expensive ones (so, the cheapest bar of those $q_i$ bars is for free).
You can use only one coupon; if you use coupon $i$, you have to choose $q_i$ bars and buy them using the coupon, and buy all the remaining $n - q_i$ bars without any discounts.
To decide which coupon to choose, you want to know what will be the minimum total amount of money you have to pay if you use one of the coupons optimally.
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of chocolate bars in the shop.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the cost of $i$-th chocolate bar.
The third line contains one integer $m$ ($1 \le m \le n - 1$) — the number of coupons you have.
The fourth line contains $m$ integers $q_1$, $q_2$, ..., $q_m$ ($2 \le q_i \le n$), where $q_i$ is the number of chocolate bars you have to buy using $i$-th coupon so that the least expensive of them will be for free. All values of $q_i$ are pairwise distinct.
-----Output-----
Print $m$ integers, $i$-th of them should be the minimum amount of money you have to pay if you buy $q_i$ bars with $i$-th coupon, and all the remaining bars one by one for their full price.
-----Example-----
Input
7
7 1 3 1 4 10 8
2
3 4
Output
27
30
-----Note-----
Consider the first example.
If we use the first coupon, we may choose chocolate bars having indices $1$, $6$ and $7$, and we pay $18$ coins for them and $9$ coins for all other bars.
If we use the second coupon, we may choose chocolate bars having indices $1$, $5$, $6$ and $7$, and we pay $25$ coins for them and $5$ coins for all other bars.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(map(int, input().split()))
m = int(input())
q = list(map(int, input().split()))
a.sort()
s = sum(a)
for qi in q:
print(s - a[-qi])
``` | vfc_17838 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1132/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\n7 1 3 1 4 10 8\n2\n3 4\n",
"output": "27\n30\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n5 7\n1\n2\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1000000000 1\n1\n2\n",
"output": "1000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9\n7 2 3 3 2 5 6 3 3\n6\n7 5 4 8 9 2\n",
"output": "31\n31\n31\n32\n32\n28\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2023 | Solve the following coding problem using the programming language python:
We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly.
More formally, you've got two arrays of integers a_1, a_2, ..., a_{n} and b_1, b_2, ..., b_{n} of length n. Also, you've got m queries of two types: Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute b_{y} + q = a_{x} + q for all integer q (0 ≤ q < k). The given operation is correct — both subsegments do not touch unexistent elements. Determine the value in position x of array b, that is, find value b_{x}.
For each query of the second type print the result — the value of the corresponding element of array b.
-----Input-----
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 10^5) — the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 10^9). The third line contains an array of integers b_1, b_2, ..., b_{n} (|b_{i}| ≤ 10^9).
Next m lines contain the descriptions of the queries. The i-th line first contains integer t_{i} — the type of the i-th query (1 ≤ t_{i} ≤ 2). If t_{i} = 1, then the i-th query means the copying operation. If t_{i} = 2, then the i-th query means taking the value in array b. If t_{i} = 1, then the query type is followed by three integers x_{i}, y_{i}, k_{i} (1 ≤ x_{i}, y_{i}, k_{i} ≤ n) — the parameters of the copying query. If t_{i} = 2, then the query type is followed by integer x_{i} (1 ≤ x_{i} ≤ n) — the position in array b.
All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b.
-----Output-----
For each second type query print the result on a single line.
-----Examples-----
Input
5 10
1 2 0 -1 3
3 1 5 -2 0
2 5
1 3 3 3
2 5
2 4
2 1
1 2 1 4
2 1
2 4
1 4 2 1
2 2
Output
0
3
-1
3
2
3
-1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
'''
SEGMENT TREE
Assign
'''
class SegmTree():
'''
- modify elements on interval
- get single element
'''
def __init__(self, size):
N = 1
while N < size:
N <<= 1
self.N = N
self.tree = [0] * (2*N)
def modify_range(self, l, r, value):
l += self.N
r += self.N
while l < r:
if l & 1:
self.tree[l] = value
l += 1
if r & 1:
r -= 1
self.tree[r] = value
l >>= 1
r >>= 1
def query(self, i):
i += self.N
latest_change = self.tree[i]
p = i
while p > 1:
p >>= 1
latest_change = max(latest_change, self.tree[p])
return latest_change
# inf = open('input.txt', 'r')
# reader = (map(int, line.split()) for line in inf)
reader = (list(map(int, line.split())) for line in sys.stdin)
input = reader.__next__
n, m = input()
a = list(input())
b = list(input())
st = SegmTree(n)
request = [None] * (m + 1)
for i in range(1, m+1):
t, *arg = input()
if t == 1:
x, y, k = request[i] = arg
st.modify_range(y-1, y-1+k, i)
else:
pos = arg[0] - 1
req_id = st.query(pos)
if req_id > 0:
x, y, k = request[req_id]
ans = a[x+(pos-y)]
else:
ans = b[pos]
sys.stdout.write(f'{ans}\n')
# inf.close()
``` | vfc_17846 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/292/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 10\n1 2 0 -1 3\n3 1 5 -2 0\n2 5\n1 3 3 3\n2 5\n2 4\n2 1\n1 2 1 4\n2 1\n2 4\n1 4 2 1\n2 2\n",
"output": "0\n3\n-1\n3\n2\n3\n-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 4\n-2\n1\n1 1 1 1\n2 1\n1 1 1 1\n1 1 1 1\n",
"output": "-2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 5\n-3 2\n3 -4\n1 1 1 2\n2 1\n2 1\n1 2 2 1\n2 1\n",
"output": "-3\n-3\n-3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 6\n4 -3 0\n1 3 -5\n2 2\n2 3\n1 2 1 2\n1 2 1 2\n2 2\n2 2\n",
"output": "3\n-5\n0\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n-1 1 1 -1\n2 -2 -3 2\n2 4\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n-1 1 -1 2 -2 2 1 2 -1 0\n-1 -2 2 0 1 -1 -1 2 -2 1\n2 1\n2 2\n2 8\n1 6 8 1\n2 5\n2 9\n1 1 7 4\n2 5\n2 2\n2 3\n",
"output": "-1\n-2\n2\n1\n-2\n1\n-2\n2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2024 | Solve the following coding problem using the programming language python:
$n$ fishermen have just returned from a fishing vacation. The $i$-th fisherman has caught a fish of weight $a_i$.
Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of showing fish is a permutation of integers from $1$ to $n$). Then they show the fish they caught according to the chosen order. When a fisherman shows his fish, he might either become happy, become sad, or stay content.
Suppose a fisherman shows a fish of weight $x$, and the maximum weight of a previously shown fish is $y$ ($y = 0$ if that fisherman is the first to show his fish). Then:
if $x \ge 2y$, the fisherman becomes happy; if $2x \le y$, the fisherman becomes sad; if none of these two conditions is met, the fisherman stays content.
Let's call an order in which the fishermen show their fish emotional if, after all fishermen show their fish according to this order, each fisherman becomes either happy or sad. Calculate the number of emotional orders modulo $998244353$.
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 5000$).
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$).
-----Output-----
Print one integer — the number of emotional orders, taken modulo $998244353$.
-----Examples-----
Input
4
1 1 4 9
Output
20
Input
4
4 3 2 1
Output
0
Input
3
4 2 1
Output
6
Input
8
42 1337 13 37 420 666 616 97
Output
19200
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
import sys
input = sys.stdin.readline
n = int(input())
a = map(int, input().split())
mod = 998244353
d = defaultdict(int)
for x in a:
d[x] += 1
d[0] = 0
b = list(d.items())
b.sort()
m = len(b)
ba = [0] * m
cn = [0] * (m + 1)
k = h = 0
for i, x in enumerate(b):
while h < m and x[0] >= b[h][0] * 2:
h += 1
ba[i] = h - 1
while k < m and x[0] * 2 > b[k][0]:
k += 1
cn[k] += x[1]
for i in range(m):
cn[i+1] += cn[i]
dp = [0] * m
dp[0] = 1
b = [x[1] for x in b]
for i in range(n):
ndp = [0] * m
for j in range(1, m):
if cn[j] >= i - 1:
ndp[j] = dp[j] * (cn[j] - i + 1) % mod
dp[j] += dp[j-1]
if dp[j] >= mod:
dp[j] -= mod
for j in range(1, m):
ndp[j] += dp[ba[j]] * b[j]
ndp[j] %= mod
dp = ndp
print(sum(dp) % mod)
``` | vfc_17850 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1437/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1 1 4 9\n",
"output": "20\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n4 3 2 1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n4 2 1\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n42 1337 13 37 420 666 616 97\n",
"output": "19200\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2025 | Solve the following coding problem using the programming language python:
You are given several queries. In the i-th query you are given a single positive integer n_{i}. You are to represent n_{i} as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.
-----Input-----
The first line contains single integer q (1 ≤ q ≤ 10^5) — the number of queries.
q lines follow. The (i + 1)-th line contains single integer n_{i} (1 ≤ n_{i} ≤ 10^9) — the i-th query.
-----Output-----
For each query print the maximum possible number of summands in a valid splitting to composite summands, or -1, if there are no such splittings.
-----Examples-----
Input
1
12
Output
3
Input
2
6
8
Output
1
2
Input
3
1
2
3
Output
-1
-1
-1
-----Note-----
12 = 4 + 4 + 4 = 4 + 8 = 6 + 6 = 12, but the first splitting has the maximum possible number of summands.
8 = 4 + 4, 6 can't be split into several composite summands.
1, 2, 3 are less than any composite number, so they do not have valid splittings.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
q = int(input())
for i in range(q):
n = int(input())
if n % 4 == 0:
print(n // 4)
elif n % 4 == 1 and n // 4 >= 2:
print(n // 4 - 1)
elif n % 4 == 2 and n // 4 >= 1:
print(n // 4)
elif n % 4 == 3 and n // 4 >= 3:
print(n // 4 - 1)
else:
print(-1)
``` | vfc_17854 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/870/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n12\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n6\n8\n",
"output": "1\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1\n2\n3\n",
"output": "-1\n-1\n-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2026 | Solve the following coding problem using the programming language python:
Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p_1, p_2, ..., p_{m} with integer coordinates, do the following: denote its initial location by p_0. First, the robot will move from p_0 to p_1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches p_1, it'll move to p_2, again, choosing one of the shortest ways, then to p_3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.
While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.
-----Input-----
The first line of input contains the only positive integer n (1 ≤ n ≤ 2·10^5) which equals the number of unit segments the robot traveled. The second line contains the movements protocol, which consists of n letters, each being equal either L, or R, or U, or D. k-th letter stands for the direction which Robot traveled the k-th unit segment in: L means that it moved to the left, R — to the right, U — to the top and D — to the bottom. Have a look at the illustrations for better explanation.
-----Output-----
The only line of input should contain the minimum possible length of the sequence.
-----Examples-----
Input
4
RURD
Output
2
Input
6
RRULDD
Output
2
Input
26
RRRULURURUULULLLDLDDRDRDLD
Output
7
Input
3
RLL
Output
2
Input
4
LRLR
Output
4
-----Note-----
The illustrations to the first three tests are given below.
[Image] [Image] [Image]
The last example illustrates that each point in the sequence should be counted as many times as it is presented in the sequence.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = input()
prot = dict()
prot["D"] = "U"
prot["L"] = "R"
prot["R"] = "L"
prot["U"] = "D"
was = set()
ans = 1
for i in range(n):
if (a[i] not in was):
if (len(was) == 0):
was.add(a[i])
elif len(was) == 1:
if (prot[a[i]] not in was):
was.add(a[i])
else:
was.clear()
was.add(a[i])
ans += 1
else:
was.clear()
was.add(a[i])
ans += 1
print(ans)
``` | vfc_17858 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/748/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\nRURD\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\nRRULDD\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "26\nRRRULURURUULULLLDLDDRDRDLD\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nRLL\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\nLRLR\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2027 | Solve the following coding problem using the programming language python:
There are n integers b_1, b_2, ..., b_{n} written in a row. For all i from 1 to n, values a_{i} are defined by the crows performing the following procedure:
The crow sets a_{i} initially 0. The crow then adds b_{i} to a_{i}, subtracts b_{i} + 1, adds the b_{i} + 2 number, and so on until the n'th number. Thus, a_{i} = b_{i} - b_{i} + 1 + b_{i} + 2 - b_{i} + 3....
Memory gives you the values a_1, a_2, ..., a_{n}, and he now wants you to find the initial numbers b_1, b_2, ..., b_{n} written in the row? Can you do it?
-----Input-----
The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of integers written in the row.
The next line contains n, the i'th of which is a_{i} ( - 10^9 ≤ a_{i} ≤ 10^9) — the value of the i'th number.
-----Output-----
Print n integers corresponding to the sequence b_1, b_2, ..., b_{n}. It's guaranteed that the answer is unique and fits in 32-bit integer type.
-----Examples-----
Input
5
6 -4 8 -2 3
Output
2 4 6 1 3
Input
5
3 -2 -1 5 6
Output
1 -3 4 11 6
-----Note-----
In the first sample test, the crows report the numbers 6, - 4, 8, - 2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6 = 2 - 4 + 6 - 1 + 3, and - 4 = 4 - 6 + 1 - 3.
In the second sample test, the sequence 1, - 3, 4, 11, 6 satisfies the reports. For example, 5 = 11 - 6 and 6 = 6.
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())
arr = list(map(int, input().split()))
arr.append(0)
ans = []
for i in range(n):
ans.append(arr[i] + arr[i + 1])
print(*ans)
main()
``` | vfc_17862 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/712/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n6 -4 8 -2 3\n",
"output": "2 4 6 1 3 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2028 | Solve the following coding problem using the programming language python:
A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.
How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007 = 10^9 + 7.
-----Input-----
Input will begin with a line containing N (1 ≤ N ≤ 100000), the number of engineers.
N lines follow, each containing exactly two integers. The i-th line contains the number of the current desk of the i-th engineer and the number of the desk the i-th engineer wants to move to. Desks are numbered from 1 to 2·N. It is guaranteed that no two engineers sit at the same desk.
-----Output-----
Print the number of possible assignments, modulo 1000000007 = 10^9 + 7.
-----Examples-----
Input
4
1 5
5 2
3 7
7 3
Output
6
Input
5
1 10
2 10
3 10
4 10
5 5
Output
5
-----Note-----
These are the possible assignments for the first example: 1 5 3 7 1 2 3 7 5 2 3 7 1 5 7 3 1 2 7 3 5 2 7 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())
m = 2 * n + 1
u = [[] for i in range(m)]
v = [0] * m
s = [0] * m
d = 10 ** 9 + 7
y = 1
for j in range(n):
a, b = map(int, input().split())
v[a] = b
if a != b:
s[b] += 1
u[b].append(a)
for b in range(m):
if not v[b]:
x = 0
p = [b]
while p:
x += 1
a = p.pop()
s[a] = -1
p += u[a]
y = (x * y) % d
for a in range(m):
if s[a] == 0:
b = v[a]
while s[b] == 1:
s[b] = -1
b = v[b]
s[b] -= 1
for a in range(m):
if s[a] == 1:
y = (2 * y) % d
while s[a]:
s[a] = 0
a = v[a]
print(y)
``` | vfc_17866 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/859/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1 5\n5 2\n3 7\n7 3\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 10\n2 10\n3 10\n4 10\n5 5\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "30\n22 37\n12 37\n37 58\n29 57\n43 57\n57 58\n58 53\n45 4\n1 4\n4 51\n35 31\n21 31\n31 51\n51 53\n53 48\n60 55\n52 55\n55 33\n36 9\n10 9\n9 33\n33 19\n5 23\n47 23\n23 32\n50 44\n26 44\n44 32\n32 19\n19 48\n",
"output": "31\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2030 | Solve the following coding problem using the programming language python:
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.
Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and different dices may have different probability distributions.
We throw both dices simultaneously and then calculate values max(a, b) and min(a, b), where a is equal to the outcome of the first dice, while b is equal to the outcome of the second dice. You don't know the probability distributions for particular values on each dice, but you know the probability distributions for max(a, b) and min(a, b). That is, for each x from 1 to n you know the probability that max(a, b) would be equal to x and the probability that min(a, b) would be equal to x. Find any valid probability distribution for values on the dices. It's guaranteed that the input data is consistent, that is, at least one solution exists.
-----Input-----
First line contains the integer n (1 ≤ n ≤ 100 000) — the number of different values for both dices.
Second line contains an array consisting of n real values with up to 8 digits after the decimal point — probability distribution for max(a, b), the i-th of these values equals to the probability that max(a, b) = i. It's guaranteed that the sum of these values for one dice is 1. The third line contains the description of the distribution min(a, b) in the same format.
-----Output-----
Output two descriptions of the probability distribution for a on the first line and for b on the second line.
The answer will be considered correct if each value of max(a, b) and min(a, b) probability distribution values does not differ by more than 10^{ - 6} from ones given in input. Also, probabilities should be non-negative and their sums should differ from 1 by no more than 10^{ - 6}.
-----Examples-----
Input
2
0.25 0.75
0.75 0.25
Output
0.5 0.5
0.5 0.5
Input
3
0.125 0.25 0.625
0.625 0.25 0.125
Output
0.25 0.25 0.5
0.5 0.25 0.25
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def tle():
k=0
while (k>=0):
k+=1
def quad(a, b, c):
disc = (b**2-4*a*c)
if disc<0:
disc=0
disc = (disc)**0.5
return ((-b+disc)/2/a, (-b-disc)/2/a)
x = int(input())
y = list(map(float, input().strip().split(' ')))
z = list(map(float, input().strip().split(' ')))
py = [0, y[0]]
for i in range(1, x):
py.append(py[-1]+y[i])
z.reverse()
pz = [0, z[0]]
for i in range(1, x):
pz.append(pz[-1]+z[i])
pz.reverse()
k = []
for i in range(0, x+1):
k.append(py[i]+1-pz[i])
l = [0]
for i in range(x):
l.append(k[i+1]-k[i])
#a[i]+b[i]
s1 = 0
s2 = 0
avals = []
bvals = []
for i in range(1, x+1):
a, b = (quad(-1, s1+l[i]-s2, (s1+l[i])*s2-py[i]))
if b<0 or l[i]-b<0:
a, b = b, a
if a<0 and b<0:
a=0
b=0
bvals.append(b)
avals.append(l[i]-b)
s1+=avals[-1]
s2+=bvals[-1]
for i in range(len(avals)):
if abs(avals[i])<=10**(-10):
avals[i] = 0
if abs(bvals[i])<=10**(-10):
bvals[i] = 0
print(' '.join([str(i) for i in avals]))
print(' '.join([str(i) for i in bvals]))
``` | vfc_17874 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/641/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n0.25 0.75\n0.75 0.25\n",
"output": "0.5 0.5 \n0.5 0.5 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2031 | Solve the following coding problem using the programming language python:
This is the easier version of the problem. In this version $1 \le n, m \le 100$. You can hack this problem only if you solve and lock both problems.
You are given a sequence of integers $a=[a_1,a_2,\dots,a_n]$ of length $n$. Its subsequence is obtained by removing zero or more elements from the sequence $a$ (they do not necessarily go consecutively). For example, for the sequence $a=[11,20,11,33,11,20,11]$:
$[11,20,11,33,11,20,11]$, $[11,20,11,33,11,20]$, $[11,11,11,11]$, $[20]$, $[33,20]$ are subsequences (these are just some of the long list); $[40]$, $[33,33]$, $[33,20,20]$, $[20,20,11,11]$ are not subsequences.
Suppose that an additional non-negative integer $k$ ($1 \le k \le n$) is given, then the subsequence is called optimal if:
it has a length of $k$ and the sum of its elements is the maximum possible among all subsequences of length $k$; and among all subsequences of length $k$ that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence $b=[b_1, b_2, \dots, b_k]$ is lexicographically smaller than the sequence $c=[c_1, c_2, \dots, c_k]$ if the first element (from the left) in which they differ less in the sequence $b$ than in $c$. Formally: there exists $t$ ($1 \le t \le k$) such that $b_1=c_1$, $b_2=c_2$, ..., $b_{t-1}=c_{t-1}$ and at the same time $b_t<c_t$. For example:
$[10, 20, 20]$ lexicographically less than $[10, 21, 1]$, $[7, 99, 99]$ is lexicographically less than $[10, 21, 1]$, $[10, 21, 0]$ is lexicographically less than $[10, 21, 1]$.
You are given a sequence of $a=[a_1,a_2,\dots,a_n]$ and $m$ requests, each consisting of two numbers $k_j$ and $pos_j$ ($1 \le k \le n$, $1 \le pos_j \le k_j$). For each query, print the value that is in the index $pos_j$ of the optimal subsequence of the given sequence $a$ for $k=k_j$.
For example, if $n=4$, $a=[10,20,30,20]$, $k_j=2$, then the optimal subsequence is $[20,30]$ — it is the minimum lexicographically among all subsequences of length $2$ with the maximum total sum of items. Thus, the answer to the request $k_j=2$, $pos_j=1$ is the number $20$, and the answer to the request $k_j=2$, $pos_j=2$ is the number $30$.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 100$) — the length of the sequence $a$.
The second line contains elements of the sequence $a$: integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).
The third line contains an integer $m$ ($1 \le m \le 100$) — the number of requests.
The following $m$ lines contain pairs of integers $k_j$ and $pos_j$ ($1 \le k \le n$, $1 \le pos_j \le k_j$) — the requests.
-----Output-----
Print $m$ integers $r_1, r_2, \dots, r_m$ ($1 \le r_j \le 10^9$) one per line: answers to the requests in the order they appear in the input. The value of $r_j$ should be equal to the value contained in the position $pos_j$ of the optimal subsequence for $k=k_j$.
-----Examples-----
Input
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
Output
20
10
20
10
20
10
Input
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
Output
2
3
2
3
2
3
1
1
3
-----Note-----
In the first example, for $a=[10,20,10]$ the optimal subsequences are: for $k=1$: $[20]$, for $k=2$: $[10,20]$, for $k=3$: $[10,20,10]$.
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())
Ans = []
A = list(map(int, input().split()))
for i in range(a):
A[i] = [A[i], -i]
A.sort()
for i in range(a):
A[i][1] = -A[i][1]
for i in range(int(input())):
n, m = map(int, input().split())
B = list(A[a - n:])
B.sort(key=lambda n: n[1])
Ans.append(B[m - 1][0])
for an in Ans:
print(an)
``` | vfc_17878 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1227/D1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3\n",
"output": "20\n10\n20\n10\n20\n10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4\n",
"output": "2\n3\n2\n3\n2\n3\n1\n1\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n3\n1 1\n1 1\n1 1\n",
"output": "1\n1\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000000\n1\n1 1\n",
"output": "1000000000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2032 | Solve the following coding problem using the programming language python:
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer $n$ castles of your opponent.
Let's describe the game process in detail. Initially you control an army of $k$ warriors. Your enemy controls $n$ castles; to conquer the $i$-th castle, you need at least $a_i$ warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army — formally, after you capture the $i$-th castle, $b_i$ warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter $c_i$, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
if you are currently in the castle $i$, you may leave one warrior to defend castle $i$; there are $m$ one-way portals connecting the castles. Each portal is characterised by two numbers of castles $u$ and $v$ (for each portal holds $u > v$). A portal can be used as follows: if you are currently in the castle $u$, you may send one warrior to defend castle $v$.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle $i$ (but only before capturing castle $i + 1$) you may recruit new warriors from castle $i$, leave a warrior to defend castle $i$, and use any number of portals leading from castle $i$ to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle $i$ won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it — your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
-----Input-----
The first line contains three integers $n$, $m$ and $k$ ($1 \le n \le 5000$, $0 \le m \le \min(\frac{n(n - 1)}{2}, 3 \cdot 10^5)$, $0 \le k \le 5000$) — the number of castles, the number of portals and initial size of your army, respectively.
Then $n$ lines follow. The $i$-th line describes the $i$-th castle with three integers $a_i$, $b_i$ and $c_i$ ($0 \le a_i, b_i, c_i \le 5000$) — the number of warriors required to capture the $i$-th castle, the number of warriors available for hire in this castle and its importance value.
Then $m$ lines follow. The $i$-th line describes the $i$-th portal with two integers $u_i$ and $v_i$ ($1 \le v_i < u_i \le n$), meaning that the portal leads from the castle $u_i$ to the castle $v_i$. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed $5000$ under any circumstances (i. e. $k + \sum\limits_{i = 1}^{n} b_i \le 5000$).
-----Output-----
If it's impossible to capture all the castles, print one integer $-1$.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
-----Examples-----
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
-----Note-----
The best course of action in the first example is as follows:
capture the first castle; hire warriors from the first castle, your army has $11$ warriors now; capture the second castle; capture the third castle; hire warriors from the third castle, your army has $13$ warriors now; capture the fourth castle; leave one warrior to protect the fourth castle, your army has $12$ warriors now.
This course of action (and several other ones) gives $5$ as your total score.
The best course of action in the second example is as follows:
capture the first castle; hire warriors from the first castle, your army has $11$ warriors now; capture the second castle; capture the third castle; hire warriors from the third castle, your army has $13$ warriors now; capture the fourth castle; leave one warrior to protect the fourth castle, your army has $12$ warriors now; send one warrior to protect the first castle through the third portal, your army has $11$ warriors now.
This course of action (and several other ones) gives $22$ as your total score.
In the third example it's impossible to capture the last castle: you need $14$ warriors to do so, but you can accumulate no more than $13$ without capturing it.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
class RAQ_RMQ():
def __init__(self, n, inf=2**31-1):
self.n0 = 1<<(n-1).bit_length()
self.INF = inf
self.data = [0]*(2*self.n0)
self.lazy = [0]*(2*self.n0)
def getIndex(self, l, r):
l += self.n0; r += self.n0
lm = (l // (l & -l)) >> 1
rm = (r // (r & -r)) >> 1
while l < r:
if r <= rm:
yield r
if l <= lm:
yield l
l >>= 1; r >>= 1
while l:
yield l
l >>= 1
def propagates(self, *ids):
for i in reversed(ids):
v = self.lazy[i-1]
if not v:
continue
self.lazy[2*i-1] += v; self.lazy[2*i] += v
self.data[2*i-1] += v; self.data[2*i] += v
self.lazy[i-1] = 0
def update(self, l, r, x):
*ids, = self.getIndex(l, r)
l += self.n0; r += self.n0
while l < r:
if r & 1:
r -= 1
self.lazy[r-1] += x; self.data[r-1] += x
if l & 1:
self.lazy[l-1] += x; self.data[l-1] += x
l += 1
l >>= 1; r >>= 1
for i in ids:
self.data[i-1] = min(self.data[2*i-1], self.data[2*i]) + self.lazy[i-1]
def query(self, l, r):
self.propagates(*self.getIndex(l, r))
l += self.n0; r += self.n0
s = self.INF
while l < r:
if r & 1:
r -= 1
s = min(s, self.data[r-1])
if l & 1:
s = min(s, self.data[l-1])
l += 1
l >>= 1; r >>= 1
return s
n,m,k = map(int, input().split())
l = [0]*(n+1)
now = k
point = [0]*n
for i in range(n):
a,b,c = map(int, input().split())
point[i] = c
now = now-a
l[i] = now
now += b+a
l[n] = now
RMQ = RAQ_RMQ(n+1)
for i in range(n+1):
RMQ.update(i,i+1,l[i])
portal = list(range(n))
for i in range(m):
u,v = map(int, input().split())
u,v = u-1, v-1
if portal[v]<u:
portal[v] = u
if RMQ.query(0, n+1) < 0:
print(-1)
return
heap = [(-point[i], -portal[i]) for i in range(n)]
from heapq import heapify, heappop
heapify(heap)
ans = 0
while heap:
p,i = heappop(heap)
p,i = -p,-i
if RMQ.query(i+1, n+1)>0:
ans += p
RMQ.update(i+1, n+1, -1)
print(ans)
``` | vfc_17882 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1271/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3 7\n7 4 17\n3 0 8\n11 2 0\n13 3 5\n3 1\n2 1\n4 3\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3 7\n7 4 17\n3 0 8\n11 2 0\n13 3 5\n3 1\n2 1\n4 1\n",
"output": "22\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3 7\n7 4 17\n3 0 8\n11 2 0\n14 3 5\n3 1\n2 1\n4 3\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2034 | Solve the following coding problem using the programming language python:
Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.
The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).
In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.
Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.
-----Input-----
The first line of the input contains two positive integers, n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000).
Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ n, x_{i} ≠ y_{i}), where x_{i} and y_{i} are the numbers of the cities connected by the i-th road.
It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.
-----Output-----
Print a single integer — the minimum number of separated cities after the reform.
-----Examples-----
Input
4 3
2 1
1 3
4 3
Output
1
Input
5 5
2 1
1 3
2 3
2 5
4 3
Output
0
Input
6 5
1 2
2 3
4 5
4 6
5 6
Output
1
-----Note-----
In the first sample the following road orientation is allowed: $1 \rightarrow 2$, $1 \rightarrow 3$, $3 \rightarrow 4$.
The second sample: $1 \rightarrow 2$, $3 \rightarrow 1$, $2 \rightarrow 3$, $2 \rightarrow 5$, $3 \rightarrow 4$.
The third sample: $1 \rightarrow 2$, $2 \rightarrow 3$, $4 \rightarrow 5$, $5 \rightarrow 6$, $6 \rightarrow 4$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a=input().split()
n=int(a[0])
m=int(a[1])
p = []
rnk = []
def init(s):
nonlocal p
nonlocal rnk
for i in range(0,s):
p.append(i)
rnk = [1]*s
def fs(v):
nonlocal p
if p[v]==v:
return v
ans = fs(p[v])
p[v]=ans
return ans
def us(a,b):
nonlocal p
nonlocal rnk
a=fs(a)
b=fs(b)
if a==b:
rnk[a]+=1
return
if rnk[a]>rnk[b]:
p[b]=a
rnk[a]+=rnk[b]
else:
p[a]=b
rnk[b]+=rnk[a]
init(n)
for i in range(0,m):
e=input().split()
us(int(e[0])-1,int(e[1])-1)
D = {}
for i in range(0,n):
if D.get(fs(i))==None:
D[fs(i)]=1
else:
D[fs(i)]+=1
ans=0
for i in D:
if rnk[i]==D[i]:
ans+=1
print(ans)
``` | vfc_17890 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/659/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n2 1\n1 3\n4 3\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n2 1\n1 3\n2 3\n2 5\n4 3\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2035 | Solve the following coding problem using the programming language python:
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.
The main school of the capital is located in $(s_x, s_y)$. There are $n$ students attending this school, the $i$-th of them lives in the house located in $(x_i, y_i)$. It is possible that some students live in the same house, but no student lives in $(s_x, s_y)$.
After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the $i$-th student goes from the school to his house is $|s_x - x_i| + |s_y - y_i|$.
The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the $i$-th student will buy a shawarma if at least one of the shortest paths from the school to the $i$-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).
You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.
-----Input-----
The first line contains three integers $n$, $s_x$, $s_y$ ($1 \le n \le 200\,000$, $0 \le s_x, s_y \le 10^{9}$) — the number of students and the coordinates of the school, respectively.
Then $n$ lines follow. The $i$-th of them contains two integers $x_i$, $y_i$ ($0 \le x_i, y_i \le 10^{9}$) — the location of the house where the $i$-th student lives. Some locations of houses may coincide, but no student lives in the same location where the school is situated.
-----Output-----
The output should consist of two lines. The first of them should contain one integer $c$ — the maximum number of students that will buy shawarmas at the tent.
The second line should contain two integers $p_x$ and $p_y$ — the coordinates where the tent should be located. If there are multiple answers, print any of them. Note that each of $p_x$ and $p_y$ should be not less than $0$ and not greater than $10^{9}$.
-----Examples-----
Input
4 3 2
1 3
4 2
5 1
4 1
Output
3
4 2
Input
3 100 100
0 0
0 0
100 200
Output
2
99 100
Input
7 10 12
5 6
20 23
15 4
16 5
4 54
12 1
4 15
Output
4
10 11
-----Note-----
In the first example, If we build the shawarma tent in $(4, 2)$, then the students living in $(4, 2)$, $(4, 1)$ and $(5, 1)$ will visit it.
In the second example, it is possible to build the shawarma tent in $(1, 1)$, then both students living in $(0, 0)$ will visit it.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,x,y = map(int,input().split())
l = 0
r = 0
u = 0
d = 0
for i in range(n):
a,b = map(int,input().split())
if a < x:
l += 1
if a > x:
r += 1
if b < y:
d += 1
if b > y:
u += 1
ans = max([l,r,u,d])
print(ans)
if ans == l:
print(x-1,y)
elif ans == r:
print(x+1,y)
elif ans == u:
print(x,y+1)
else:
print(x,y-1)
``` | vfc_17894 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1271/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3 2\n1 3\n4 2\n5 1\n4 1\n",
"output": "3\n4 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 100 100\n0 0\n0 0\n100 200\n",
"output": "2\n99 100\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 10 12\n5 6\n20 23\n15 4\n16 5\n4 54\n12 1\n4 15\n",
"output": "4\n10 11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 100 100\n50 70\n",
"output": "1\n99 100\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 100 100\n101 100\n",
"output": "1\n101 100\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2037 | Solve the following coding problem using the programming language python:
Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $n$ problems of distinct difficulty, the difficulties are numbered from $1$ to $n$.
To hold a round Arkady needs $n$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $1$ to $n$ and puts it into the problems pool.
At each moment when Arkady can choose a set of $n$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.
You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 10^5$) — the number of difficulty levels and the number of problems Arkady created.
The second line contains $m$ integers $a_1, a_2, \ldots, a_m$ ($1 \le a_i \le n$) — the problems' difficulties in the order Arkady created them.
-----Output-----
Print a line containing $m$ digits. The $i$-th digit should be $1$ if Arkady held the round after creation of the $i$-th problem, and $0$ otherwise.
-----Examples-----
Input
3 11
2 3 1 2 2 2 3 2 2 3 1
Output
00100000001
Input
4 8
4 1 3 3 2 3 3 3
Output
00001000
-----Note-----
In the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,m = map(int,input().split())
a = list(map(int,input().split()))
b = [0]*(n+5)
c = [0]*(m+5)
c[0] = n
cur = 0
for i in range(m):
c[b[a[i]]] -= 1
b[a[i]] += 1
c[b[a[i]]] += 1
if c[cur] == 0:
print(1,end='')
cur += 1
else:
print(0,end='')
``` | vfc_17902 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1100/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 11\n2 3 1 2 2 2 3 2 2 3 1\n",
"output": "00100000001\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 8\n4 1 3 3 2 3 3 3\n",
"output": "00001000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 20\n1 4 4 2 1 1 3 5 4 2 2 4 5 2 3 3 4 5 1 4\n",
"output": "00000001000000100100\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2038 | Solve the following coding problem using the programming language python:
You are given a permutation $p$ of integers from $1$ to $n$, where $n$ is an even number.
Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type: take two indices $i$ and $j$ such that $2 \cdot |i - j| \geq n$ and swap $p_i$ and $p_j$.
There is no need to minimize the number of operations, however you should use no more than $5 \cdot n$ operations. One can show that it is always possible to do that.
-----Input-----
The first line contains a single integer $n$ ($2 \leq n \leq 3 \cdot 10^5$, $n$ is even) — the length of the permutation.
The second line contains $n$ distinct integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$) — the given permutation.
-----Output-----
On the first line print $m$ ($0 \le m \le 5 \cdot n$) — the number of swaps to perform.
Each of the following $m$ lines should contain integers $a_i, b_i$ ($1 \le a_i, b_i \le n$, $|a_i - b_i| \ge \frac{n}{2}$) — the indices that should be swapped in the corresponding swap.
Note that there is no need to minimize the number of operations. We can show that an answer always exists.
-----Examples-----
Input
2
2 1
Output
1
1 2
Input
4
3 4 1 2
Output
4
1 4
1 4
1 3
2 4
Input
6
2 5 3 1 4 6
Output
3
1 5
2 5
1 4
-----Note-----
In the first example, when one swap elements on positions $1$ and $2$, the array becomes sorted.
In the second example, pay attention that there is no need to minimize number of swaps.
In the third example, after swapping elements on positions $1$ and $5$ the array becomes: $[4, 5, 3, 1, 2, 6]$. After swapping elements on positions $2$ and $5$ the array becomes $[4, 2, 3, 1, 5, 6]$ and finally after swapping elements on positions $1$ and $4$ the array becomes sorted: $[1, 2, 3, 4, 5, 6]$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# from bisect import bisect_left
# (n) = (int(x) for x in input().split())
n = int(input())
a = [int(_) - 1 for _ in input().split()]
b = [0 for _ in a]
for id, v in enumerate(a):
b[v] = id
ans = []
for i in range(n):
pos = b[i]
target = i
old_v = a[target]
if pos == target:
continue
# do swap
b[old_v] = pos
b[i] = i
a[target] = i
a[pos] = old_v
if (abs(pos - target) * 2 >= n):
ans.append((pos, target))
continue
elif max(pos, target) < n // 2:
helper = n - 1
ans.append((pos, helper))
ans.append((target, helper))
ans.append((pos, helper))
elif min(pos, target) >= n // 2:
helper = 0
ans.append((pos, helper))
ans.append((target, helper))
ans.append((pos, helper))
else:
L = 0
R = n - 1
if pos > target:
(pos, target) = (target, pos)
ans.append((pos, R))
ans.append((L, R))
ans.append((L, target))
ans.append((L, R))
ans.append((pos, R))
print(len(ans))
for i in ans:
print(i[0] + 1, i[1] + 1)
``` | vfc_17906 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1148/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n2 1\n",
"output": "1\n1 2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n3 4 1 2\n",
"output": "2\n1 3\n2 4",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n2 5 3 1 4 6\n",
"output": "9\n1 4\n2 6\n4 1\n1 6\n4 1\n2 6\n4 1\n5 1\n4 1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n7 2 9 6 5 8 1 3 10 4\n",
"output": "12\n1 7\n3 8\n4 10\n6 1\n10 1\n6 1\n8 1\n10 1\n8 1\n9 1\n10 1\n9 1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 2\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n6 1 2 9 3 5 4 10 7 8\n",
"output": "25\n1 10\n2 10\n1 10\n2 10\n3 10\n2 10\n3 10\n5 10\n3 10\n4 10\n7 1\n1 10\n7 1\n4 10\n5 10\n6 1\n1 10\n6 1\n5 10\n7 1\n9 1\n7 1\n8 1\n10 1\n8 1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2040 | Solve the following coding problem using the programming language python:
Vasya had a strictly increasing sequence of positive integers a_1, ..., a_{n}. Vasya used it to build a new sequence b_1, ..., b_{n}, where b_{i} is the sum of digits of a_{i}'s decimal representation. Then sequence a_{i} got lost and all that remained is sequence b_{i}.
Vasya wonders what the numbers a_{i} could be like. Of all the possible options he likes the one sequence with the minimum possible last number a_{n}. Help Vasya restore the initial sequence.
It is guaranteed that such a sequence always exists.
-----Input-----
The first line contains a single integer number n (1 ≤ n ≤ 300).
Next n lines contain integer numbers b_1, ..., b_{n} — the required sums of digits. All b_{i} belong to the range 1 ≤ b_{i} ≤ 300.
-----Output-----
Print n integer numbers, one per line — the correct option for numbers a_{i}, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to b_{i}.
If there are multiple sequences with least possible number a_{n}, print any of them. Print the numbers without leading zeroes.
-----Examples-----
Input
3
1
2
3
Output
1
2
3
Input
3
3
2
1
Output
3
11
100
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Codeforces Contest 289 Div 2 Problem C
Author : chaotic_iak
Language: Python 3.4.2
"""
################################################### SOLUTION
def printing(num):
arr = num[:]
while len(arr) > 1 and arr[-1] == 0: arr.pop()
print("".join(map(str, reversed(arr))))
def main():
n, = read()
last = [0]*500
for i in range(n):
b, = read()
last[0] += 1
p = 0
while last[p] == 10:
last[p] = 0
p += 1
last[p] += 1
p = 0
while sum(last) > b:
last[p] = 0
p += 1
k = p
last[k] += 1
while last[k] == 10:
last[k] = 0
k += 1
last[k] += 1
p = 0
while sum(last) < b:
while last[p] == 9: p += 1
last[p] += 1
printing(last)
#################################################### HELPERS
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0: return inputs
if mode == 1: return inputs.split()
if mode == 2: return list(map(int, inputs.split()))
def write(s="\n"):
if s is None: s = ""
if isinstance(s, list): s = " ".join(map(str, s))
s = str(s)
print(s, end="")
write(main())
``` | vfc_17914 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/509/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1\n2\n3\n",
"output": "1\n2\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3\n2\n1\n",
"output": "3\n11\n100\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2041 | Solve the following coding problem using the programming language python:
This is the harder version of the problem. In this version, $1 \le n, m \le 2\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
You are given a sequence of integers $a=[a_1,a_2,\dots,a_n]$ of length $n$. Its subsequence is obtained by removing zero or more elements from the sequence $a$ (they do not necessarily go consecutively). For example, for the sequence $a=[11,20,11,33,11,20,11]$: $[11,20,11,33,11,20,11]$, $[11,20,11,33,11,20]$, $[11,11,11,11]$, $[20]$, $[33,20]$ are subsequences (these are just some of the long list); $[40]$, $[33,33]$, $[33,20,20]$, $[20,20,11,11]$ are not subsequences.
Suppose that an additional non-negative integer $k$ ($1 \le k \le n$) is given, then the subsequence is called optimal if: it has a length of $k$ and the sum of its elements is the maximum possible among all subsequences of length $k$; and among all subsequences of length $k$ that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence $b=[b_1, b_2, \dots, b_k]$ is lexicographically smaller than the sequence $c=[c_1, c_2, \dots, c_k]$ if the first element (from the left) in which they differ less in the sequence $b$ than in $c$. Formally: there exists $t$ ($1 \le t \le k$) such that $b_1=c_1$, $b_2=c_2$, ..., $b_{t-1}=c_{t-1}$ and at the same time $b_t<c_t$. For example: $[10, 20, 20]$ lexicographically less than $[10, 21, 1]$, $[7, 99, 99]$ is lexicographically less than $[10, 21, 1]$, $[10, 21, 0]$ is lexicographically less than $[10, 21, 1]$.
You are given a sequence of $a=[a_1,a_2,\dots,a_n]$ and $m$ requests, each consisting of two numbers $k_j$ and $pos_j$ ($1 \le k \le n$, $1 \le pos_j \le k_j$). For each query, print the value that is in the index $pos_j$ of the optimal subsequence of the given sequence $a$ for $k=k_j$.
For example, if $n=4$, $a=[10,20,30,20]$, $k_j=2$, then the optimal subsequence is $[20,30]$ — it is the minimum lexicographically among all subsequences of length $2$ with the maximum total sum of items. Thus, the answer to the request $k_j=2$, $pos_j=1$ is the number $20$, and the answer to the request $k_j=2$, $pos_j=2$ is the number $30$.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 2\cdot10^5$) — the length of the sequence $a$.
The second line contains elements of the sequence $a$: integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).
The third line contains an integer $m$ ($1 \le m \le 2\cdot10^5$) — the number of requests.
The following $m$ lines contain pairs of integers $k_j$ and $pos_j$ ($1 \le k \le n$, $1 \le pos_j \le k_j$) — the requests.
-----Output-----
Print $m$ integers $r_1, r_2, \dots, r_m$ ($1 \le r_j \le 10^9$) one per line: answers to the requests in the order they appear in the input. The value of $r_j$ should be equal to the value contained in the position $pos_j$ of the optimal subsequence for $k=k_j$.
-----Examples-----
Input
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
Output
20
10
20
10
20
10
Input
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
Output
2
3
2
3
2
3
1
1
3
-----Note-----
In the first example, for $a=[10,20,10]$ the optimal subsequences are: for $k=1$: $[20]$, for $k=2$: $[10,20]$, for $k=3$: $[10,20,10]$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
def __starting_point():
lines = sys.stdin.readlines()
n = int(lines[0])
aa = [(a, i) for i, a in enumerate(map(int, lines[1].split()))]
m = int(lines[2])
qs = [None]*m
ans = [None]*m
for i in range(m):
k, pos = list(map(int, lines[i+3].split()))
qs[i] = (pos, k, i)
qs.sort(key=lambda x: x[1])
aa.sort(key=lambda x: x[1])
aa.sort(key=lambda x: x[0], reverse=True)
avl = AvlTree()
s = 0
for pos, k, i in qs:
for a, j in aa[s: k]:
avl.add(j, a)
ans[i] = str(avl.get_at(pos - 1)[1])
s = k
print("\n".join(ans))
__starting_point()
``` | vfc_17918 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1227/D2",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3\n",
"output": "20\n10\n20\n10\n20\n10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2042 | Solve the following coding problem using the programming language python:
Igor is in the museum and he wants to see as many pictures as possible.
Museum can be represented as a rectangular field of n × m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.
At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.
For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.
-----Input-----
First line of the input contains three integers n, m and k (3 ≤ n, m ≤ 1000, 1 ≤ k ≤ min(n·m, 100 000)) — the museum dimensions and the number of starting positions to process.
Each of the next n lines contains m symbols '.', '*' — the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.
Each of the last k lines contains two integers x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) — the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns — from left to right. It is guaranteed that all starting positions are empty cells.
-----Output-----
Print k integers — the maximum number of pictures, that Igor can see if he starts in corresponding position.
-----Examples-----
Input
5 6 3
******
*..*.*
******
*....*
******
2 2
2 5
4 3
Output
6
4
10
Input
4 4 1
****
*..*
*.**
****
3 2
Output
8
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
# 598D_Igor.py - Codeforces.com/problemset/problem/598/D by Sergey 2015
import unittest
import sys
from collections import deque
###############################################################################
# Igor Class (Main Program)
###############################################################################
def empty_around(i, rc, n, m, nw, mw):
w = 32
r = (i // m) // w
c = (i % m) // w
j = r * mw + c
if j < len(rc):
if rc[j] == 0:
rc[j] = 1
return True, r, c
return False, 0, 0
def fill_around(a, r0, c0, to_visit, visited, n, m):
w = 32
for r in range(w):
for c in range(w):
i = (r0 * w + r) * m + (c0 * w + c)
if (r == 0 or r == w - 1 or c == 0 or c == w - 1):
if a[i] == 0:
to_visit.append(i)
a[i] = 1
else:
a[i] = 2
visited.append(i)
class Igor:
""" Igor representation """
def __init__(self, test_inputs=None):
""" Default constructor """
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
self.result = []
w = 32
n, m, k = [int(x) for x in uinput().split()]
d0, d1, d2, d3 = -m, 2*m, -m-1, 2
a = []
rc = []
rr = []
mw = m // w
nw = n // w
for _ in range(n):
row = [(0 if v == '.' else 3) for v in uinput()]
a += row
rc += [sum(row[i*w:i*w+w]) for i in range(mw)]
for i in range(nw):
j = i*mw*w
rr += [sum([rc[j+u*mw+v] for u in range(w)]) for v in range(mw)]
to_visit = deque()
for _ in range(k):
x0, y0 = [int(x)-1 for x in uinput().split()]
i0 = x0*m+y0
step = 0
if a[i0] > 3:
self.result.append(a[i0])
else:
ans = 0
to_visit.append(i0)
visited = deque()
step += 1
while to_visit:
i = to_visit.pop()
if a[i] == 2:
continue
visited.append(i)
if step % w == 1:
e, r0, c0 = empty_around(i, rr, n, m, nw, mw)
else:
e = False
a[i] = 2
if e:
fill_around(a, r0, c0, to_visit, visited, n, m)
for d in (d0, d1, d2, d3):
i += d
if a[i] == 0:
to_visit.append(i)
a[i] = 1
elif a[i] == 3:
ans += 1
self.result.append(ans)
for i in visited:
a[i] = ans
def calculate(self):
""" Main calcualtion function of the class """
return str("\n".join(map(str, self.result)))
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_single_test(self):
""" Igor class testing """
# Constructor test
test = "5 6 3\n******\n*..*.*\n******\n*....*\n******\n2 2\n2 5\n4 3"
d = Igor(test)
# Sample test
self.assertEqual(Igor(test).calculate(), "6\n4\n10")
# Sample test
test = ""
# self.assertEqual(Igor(test).calculate(), "0")
# Sample test
test = ""
# self.assertEqual(Igor(test).calculate(), "0")
# My tests
test = ""
# self.assertEqual(Igor(test).calculate(), "0")
# Time limit test
# self.time_limit_test(5000)
def time_limit_test(self, nmax):
""" Timelimit testing """
import random
import timeit
# Random inputs
test = str(nmax) + " " + str(nmax) + "\n"
numnums = [str(i) + " " + str(i+1) for i in range(nmax)]
test += "\n".join(numnums) + "\n"
nums = [random.randint(1, 10000) for i in range(nmax)]
test += " ".join(map(str, nums)) + "\n"
# Run the test
start = timeit.default_timer()
d = Igor(test)
calc = timeit.default_timer()
d.calculate()
stop = timeit.default_timer()
print(("\nTimelimit Test: " +
"{0:.3f}s (init {1:.3f}s calc {2:.3f}s)".
format(stop-start, calc-start, stop-calc)))
def __starting_point():
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(Igor().calculate())
__starting_point()
``` | vfc_17922 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/598/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 6 3\n******\n*..*.*\n******\n*....*\n******\n2 2\n2 5\n4 3\n",
"output": "6\n4\n10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4 1\n****\n*..*\n*.**\n****\n3 2\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 1\n***\n*.*\n***\n2 2\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5 10\n*****\n*...*\n*..**\n*.***\n*****\n2 4\n4 2\n2 2\n2 3\n2 2\n2 2\n2 4\n3 2\n2 2\n2 2\n",
"output": "12\n12\n12\n12\n12\n12\n12\n12\n12\n12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 3 10\n***\n*.*\n*.*\n***\n***\n*.*\n*.*\n*.*\n*.*\n***\n2 2\n2 2\n2 2\n2 2\n8 2\n2 2\n2 2\n7 2\n8 2\n6 2\n",
"output": "6\n6\n6\n6\n10\n6\n6\n10\n10\n10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2043 | Solve the following coding problem using the programming language python:
A Martian boy is named s — he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if s=«aba», then strings «baobab», «aabbaa», «helloabahello» make him very happy and strings «aab», «baaa» and «helloabhello» do not.
However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.
Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.
-----Input-----
The first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters.
The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 10^6 letters.
-----Output-----
Print the sought number of ways to cut string t in two so that each part made s happy.
-----Examples-----
Input
aba
baobababbah
Output
2
Input
mars
sunvenusearthmarsjupitersaturnuranusneptune
Output
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()
pole = input()
t = 0
count = 0
for i in range(len(pole)):
if pole[i] == s[t]:
t += 1
if t == len(s):
break
count += 1
t -= 1
for i in range(len(pole) - 1, -1, -1):
if pole[i] == s[t]:
t -= 1
if t == -1:
count1 = i
break
if count1 - count > 0:
print(count1 - count)
else:
print(0)
``` | vfc_17926 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/523/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "aba\nbaobababbah\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "mars\nsunvenusearthmarsjupitersaturnuranusneptune\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "rry\nsorrymercuryismissedabove\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "a\naaaaaaaaaaaaaa\n",
"output": "13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "abcaba\nabcabaabcabaabcabaabcaba\n",
"output": "13\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2044 | Solve the following coding problem using the programming language python:
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $n$ consecutive days. During the $i$-th day you have to write exactly $a_i$ names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).
Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $m$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.
Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $1$ to $n$.
-----Input-----
The first line of the input contains two integers $n$, $m$ ($1 \le n \le 2 \cdot 10^5$, $1 \le m \le 10^9$) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ means the number of names you will write in the notebook during the $i$-th day.
-----Output-----
Print exactly $n$ integers $t_1, t_2, \dots, t_n$, where $t_i$ is the number of times you will turn the page during the $i$-th day.
-----Examples-----
Input
3 5
3 7 9
Output
0 2 1
Input
4 20
10 9 19 2
Output
0 0 1 1
Input
1 100
99
Output
0
-----Note-----
In the first example pages of the Death Note will look like this $[1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]$. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
import io
stream_enable = 0
inpstream = """
3 5
3 7 9
"""
if stream_enable:
sys.stdin = io.StringIO(inpstream)
input()
def inpmap():
return list(map(int, input().split()))
n, m = inpmap()
arr = inpmap()
s = 0
for x in arr:
s += x
print(s // m, end=' ')
s %= m
print()
``` | vfc_17930 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1016/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5\n3 7 9\n",
"output": "0 2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 20\n10 9 19 2\n",
"output": "0 0 1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 100\n99\n",
"output": "0 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n2\n",
"output": "2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "16 2\n999999999 999999999 999999999 999999999 999999999 999999999 999999999 999999999 999999999 999999999 999999999 999999999 999999999 999999999 999999999 999999999\n",
"output": "499999999 500000000 499999999 500000000 499999999 500000000 499999999 500000000 499999999 500000000 499999999 500000000 499999999 500000000 499999999 500000000 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2045 | Solve the following coding problem using the programming language python:
Amugae has a sentence consisting of $n$ words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease".
Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 10^5$), the number of the words in Amugae's sentence.
The second line contains $n$ words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits ('A', 'B', ..., 'Z', 'a', 'b', ..., 'z', '0', '1', ..., '9'). The total length of the words does not exceed $10^6$.
-----Output-----
In the only line output the compressed word after the merging process ends as described in the problem.
-----Examples-----
Input
5
I want to order pizza
Output
Iwantorderpizza
Input
5
sample please ease in out
Output
sampleaseinout
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())
words = input().split()[:n]
p_base = 1543
p_mod = 1300199
current = [c for c in words[0]]
for word in words[1:]:
cur_hash = 0
word_hash = 0
cur_base = 1
i_matches = []
same_i = 0
biggest_match = None
while same_i < len(current) and same_i < len(word):
cur_hash *= p_base
cur_hash %= p_mod
cur_hash += ord(current[len(current) - 1 - same_i])
cur_hash %= p_mod
word_hash += ord(word[same_i]) * cur_base
word_hash %= p_mod
cur_base *= p_base
cur_base %= p_mod
if cur_hash == word_hash:
i_matches.append(same_i)
#biggest_match = same_i
same_i += 1
for match in reversed(i_matches):
if ''.join(word[:match + 1]) == ''.join(current[-1 - match:]):
biggest_match = match
break
if biggest_match is None:
current.extend(list(word))
else:
current.extend(list(word[biggest_match + 1:]))
print(*current, sep='')
``` | vfc_17934 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1200/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\nI want to order pizza\n",
"output": "Iwantorderpizza",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\nsample please ease in out\n",
"output": "sampleaseinout",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1101 1001 001001 101 010\n",
"output": "1101001001010",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\nX XtS XtS XtSo4P0Mhj\n",
"output": "XtSo4P0Mhj",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2046 | Solve the following coding problem using the programming language python:
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.
Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. [Image]
However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.
Write a program that models the behavior of Ankh-Morpork residents.
-----Input-----
The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks.
The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.
-----Output-----
Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.
-----Examples-----
Input
3
3 1 2
Output
3
2 1
Input
5
4 5 1 2 3
Output
5 4
3 2 1
-----Note-----
In the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(map(int, input().split()))
s = set()
j = 0
i = n
while i != 0:
if a[j] == i:
print(i)
j += 1
i -= 1
else:
while j < n and a[j] != i:
s.add(a[j])
j += 1
print()
s.add(i)
while i > 0 and i in s:
print(i, end = ' ')
i -= 1
``` | vfc_17938 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/767/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 1 2\n",
"output": "3 \n\n2 1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2049 | Solve the following coding problem using the programming language python:
You've got an array, consisting of n integers a_1, a_2, ..., a_{n}. Also, you've got m queries, the i-th query is described by two integers l_{i}, r_{i}. Numbers l_{i}, r_{i} define a subsegment of the original array, that is, the sequence of numbers a_{l}_{i}, a_{l}_{i} + 1, a_{l}_{i} + 2, ..., a_{r}_{i}. For each query you should check whether the corresponding segment is a ladder.
A ladder is a sequence of integers b_1, b_2, ..., b_{k}, such that it first doesn't decrease, then doesn't increase. In other words, there is such integer x (1 ≤ x ≤ k), that the following inequation fulfills: b_1 ≤ b_2 ≤ ... ≤ b_{x} ≥ b_{x} + 1 ≥ b_{x} + 2... ≥ b_{k}. Note that the non-decreasing and the non-increasing sequences are also considered ladders.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of array elements and the number of queries. The second line contains the sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where number a_{i} stands for the i-th array element.
The following m lines contain the description of the queries. The i-th line contains the description of the i-th query, consisting of two integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) — the boundaries of the subsegment of the initial array.
The numbers in the lines are separated by single spaces.
-----Output-----
Print m lines, in the i-th line print word "Yes" (without the quotes), if the subsegment that corresponds to the i-th query is the ladder, or word "No" (without the quotes) otherwise.
-----Examples-----
Input
8 6
1 2 1 3 3 5 2 1
1 3
2 3
2 4
8 8
1 4
5 8
Output
Yes
Yes
No
Yes
No
Yes
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=list(map(int,sys.stdin.readline().split()))
M=[m]
A=list(map(int,sys.stdin.readline().split()))
L=[0]*n
inc=False
dec=False
def ALLYes():
Ans=""
for i in range(M[0]):
Ans+="Yes\n"
sys.stdout.write(Ans)
return
for i in range(1,n):
if(A[i]>A[i-1]):
L[i]=1
inc=True
elif(A[i]==A[i-1]):
L[i]=0
else:
L[i]=-1
dec=True
if(inc==False or dec==False):
ALLYes()
else:
neg=L.index(-1)
pos=L.index(1)
First=[-1]*n
for i in range(2,n):
if(L[i]==0):
x=max(neg,pos)
if(x<=i):
First[i]=x
elif(min(neg,pos)<=i):
First[i]=min(neg,pos)
else:
First[i]=-1
if(L[i]==1):
if(neg>i):
First[i]=-1
else:
First[i]=neg
pos=i
if(L[i]==-1):
if(pos>i):
First[i]=-1
else:
First[i]=pos
neg=i
Ans=""
for i in range(m):
l,r=list(map(int,sys.stdin.readline().split()))
r-=1
if(r-l<1):
Ans+="Yes\n"
continue
if(L[r]==0):
r=First[r]
if(r<1):
Ans+="Yes\n"
continue
if(L[r]==1):
r=First[r]
if(r<l):
Ans+="Yes\n"
continue
else:
Ans+="No\n"
continue
elif(L[r]==-1):
r=First[r]
if(r<l):
Ans+="Yes\n"
continue
r=First[r]
if(r<l):
Ans+="Yes\n"
continue
else:
Ans+="No\n"
continue
sys.stdout.write(Ans)
``` | vfc_17950 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/279/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "8 6\n1 2 1 3 3 5 2 1\n1 3\n2 3\n2 4\n8 8\n1 4\n5 8\n",
"output": "Yes\nYes\nNo\nYes\nNo\nYes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n6\n1 1\n",
"output": "Yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 5\n1 1\n1 2\n2 2\n2 2\n1 2\n1 2\n",
"output": "Yes\nYes\nYes\nYes\nYes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n4 7 2 6 4 8 1 2 1 9\n6 10\n1 9\n9 9\n2 8\n9 9\n1 1\n8 8\n4 8\n8 8\n7 7\n",
"output": "No\nNo\nYes\nNo\nYes\nYes\nYes\nNo\nYes\nYes\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2050 | Solve the following coding problem using the programming language python:
Dreamoon likes to play with sets, integers and $gcd$. $\operatorname{gcd}(a, b)$ is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements s_{i}, s_{j} from S, $\operatorname{gcd}(s_{i}, s_{j}) = k$.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
-----Input-----
The single line of the input contains two space separated integers n, k (1 ≤ n ≤ 10 000, 1 ≤ k ≤ 100).
-----Output-----
On the first line print a single integer — the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
-----Examples-----
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
-----Note-----
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since $\operatorname{gcd}(2,4) = 2 \neq 1$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
'''
Created on Oct 12, 2014
@author: Ismael
'''
#import time
from fractions import gcd
def checkSet(setK,newVal):
for v in setK:
if(gcd(v,newVal) != 1):
return False
return True
def solve(n,k):
j = 1
sets = []
for _ in range(n):
setK = set()
while(len(setK) < 4):
if(checkSet(setK,j) and not(len(setK) == 0 and j%3==0)):
setK.add(j)
j += 1
sets.append(setK)
maxV = 0
for setK in sets:
maxV = max(maxV,max(setK))
print(maxV*k)
for setK in sets:
print(' '.join([str(x*k) for x in setK]))
#t = time.clock()
n,k = list(map(int,input().split()))
solve(n,k)
#print(time.clock()-t)
``` | vfc_17954 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/476/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 1\n",
"output": "5\n1 3 4 5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n",
"output": "22\n2 6 8 10\n14 18 20 22\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 7\n",
"output": "287\n7 21 28 35\n49 63 70 77\n91 105 112 119\n133 147 154 161\n175 189 196 203\n217 231 238 245\n259 273 280 287\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "13 7\n",
"output": "539\n7 21 28 35\n49 63 70 77\n91 105 112 119\n133 147 154 161\n175 189 196 203\n217 231 238 245\n259 273 280 287\n301 315 322 329\n343 357 364 371\n385 399 406 413\n427 441 448 455\n469 483 490 497\n511 525 532 539\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15 27\n",
"output": "2403\n27 81 108 135\n189 243 270 297\n351 405 432 459\n513 567 594 621\n675 729 756 783\n837 891 918 945\n999 1053 1080 1107\n1161 1215 1242 1269\n1323 1377 1404 1431\n1485 1539 1566 1593\n1647 1701 1728 1755\n1809 1863 1890 1917\n1971 2025 2052 2079\n2133 2187 2214 2241\n2295 2349 2376 2403\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2052 | Solve the following coding problem using the programming language python:
A lot of frogs want to cross a river. A river is $w$ units width, but frogs can only jump $l$ units long, where $l < w$. Frogs can also jump on lengths shorter than $l$. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are $a_i$ stones at the distance of $i$ units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
-----Input-----
The first line contains two integers $w$ and $l$ ($1 \le l < w \le 10^5$) — the width of the river and the maximum length of a frog's jump.
The second line contains $w - 1$ integers $a_1, a_2, \ldots, a_{w-1}$ ($0 \le a_i \le 10^4$), where $a_i$ is the number of stones at the distance $i$ from the bank the frogs are currently at.
-----Output-----
Print a single integer — the maximum number of frogs that can cross the river.
-----Examples-----
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
-----Note-----
In the first sample two frogs can use the different stones at the distance $5$, and one frog can use the stones at the distances $3$ and then $8$.
In the second sample although there are two stones at the distance $5$, that does not help. The three paths are: $0 \to 3 \to 6 \to 9 \to 10$, $0 \to 2 \to 5 \to 8 \to 10$, $0 \to 1 \to 4 \to 7 \to 10$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
w, l = [int(i) for i in input().split(' ')]
arr = [int(i) for i in input().split(' ')]
cummulative = [0 for i in range(len(arr) + 1)]
for i in range(len(arr)):
cummulative[i+1] = cummulative[i] + arr[i]
min_cut = 1000000009
for i in range(w - l):
cut = cummulative[i + l] - cummulative[i]
if cut < min_cut:
min_cut = cut
print(min_cut)
``` | vfc_17962 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/965/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 5\n0 0 1 0 2 0 0 1 0\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2053 | Solve the following coding problem using the programming language python:
Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a s_{a} as close as possible to the sum of the elements in the array b s_{b}. So he wants to minimize the value v = |s_{a} - s_{b}|.
In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5, 1, 3, 2, 4] and the array b is [3, 3, 2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2, 1, 3, 2, 4] and the new array b [3, 3, 5].
Professor doesn't want to make more than two swaps. Find the minimal value v and some sequence of no more than two swaps that will lead to the such value v. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 2000) — the number of elements in the array a.
The second line contains n integers a_{i} ( - 10^9 ≤ a_{i} ≤ 10^9) — the elements of the array a.
The third line contains integer m (1 ≤ m ≤ 2000) — the number of elements in the array b.
The fourth line contains m integers b_{j} ( - 10^9 ≤ b_{j} ≤ 10^9) — the elements of the array b.
-----Output-----
In the first line print the minimal value v = |s_{a} - s_{b}| that can be got with no more than two swaps.
The second line should contain the number of swaps k (0 ≤ k ≤ 2).
Each of the next k lines should contain two integers x_{p}, y_{p} (1 ≤ x_{p} ≤ n, 1 ≤ y_{p} ≤ m) — the index of the element in the array a and the index of the element in the array b in the p-th swap.
If there are several optimal solutions print any of them. Print the swaps in order the professor did them.
-----Examples-----
Input
5
5 4 3 2 1
4
1 1 1 1
Output
1
2
1 1
4 2
Input
5
1 2 3 4 5
1
15
Output
0
0
Input
5
1 2 3 4 5
4
1 2 3 4
Output
1
1
3 1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
sum_a, sum_b = sum(a), sum(b)
delta = sum_b - sum_a
ans = abs(delta)
ans_swap = []
for i in range(n):
for j in range(m):
if abs((sum_a - a[i] + b[j]) - (sum_b + a[i] - b[j])) < ans:
ans = abs((sum_a - a[i] + b[j]) - (sum_b + a[i] - b[j]))
ans_swap = [(i+1, j+1)]
d = dict()
for i in range(m):
for j in range(i+1, m):
d[b[i]+b[j]] = (i+1, j+1)
minf, inf = -10**13, 10**13
val = [minf, minf] + sorted(d.keys()) + [inf, inf]
for i in range(n):
for j in range(i+1, n):
ap = a[i] + a[j]
req = (delta + ap*2) >> 1
k = bisect_left(val, req)
for k in range(k-1, k+2):
if abs(delta + ap*2 - val[k]*2) < ans:
ans = abs(delta + ap*2 - val[k]*2)
ans_swap = [(i+1, d[val[k]][0]), (j+1, d[val[k]][1])]
print(ans)
print(len(ans_swap))
for x, y in ans_swap:
print(x, y)
``` | vfc_17966 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/620/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n5 4 3 2 1\n4\n1 1 1 1\n",
"output": "1\n2\n1 1\n4 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 2 3 4 5\n1\n15\n",
"output": "0\n0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2054 | Solve the following coding problem using the programming language python:
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.
Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $a$ sticks and $b$ diamonds?
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The only line of each test case contains two integers $a$ and $b$ ($0 \le a, b \le 10^9$) — the number of sticks and the number of diamonds, respectively.
-----Output-----
For each test case print one integer — the maximum number of emeralds Polycarp can earn.
-----Example-----
Input
4
4 4
1000000000 0
7 15
8 7
Output
2
0
7
5
-----Note-----
In the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel.
In the second test case Polycarp does not have any diamonds, so he cannot craft anything.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t = int(input())
for _ in range(t):
a, b = list(map(int, input().split()))
print(min((a+b)//3,a,b))
``` | vfc_17970 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1366/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n4 4\n1000000000 0\n7 15\n8 7\n",
"output": "2\n0\n7\n5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n7 4\n1 5\n",
"output": "3\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n33993 5\n",
"output": "5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2055 | Solve the following coding problem using the programming language python:
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and $n$ cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the $i$-th city contains $a_i$ households that require a connection.
The government designed a plan to build $n$ network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the $i$-th network station will provide service only for the $i$-th and the $(i + 1)$-th city (the $n$-th station is connected to the $n$-th and the $1$-st city).
All network stations have capacities: the $i$-th station can provide the connection to at most $b_i$ households.
Now the government asks you to check can the designed stations meet the needs of all cities or not — that is, is it possible to assign each household a network station so that each network station $i$ provides the connection to at most $b_i$ households.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.
The first line of each test case contains the single integer $n$ ($2 \le n \le 10^6$) — the number of cities and stations.
The second line of each test case contains $n$ integers ($1 \le a_i \le 10^9$) — the number of households in the $i$-th city.
The third line of each test case contains $n$ integers ($1 \le b_i \le 10^9$) — the capacities of the designed stations.
It's guaranteed that the sum of $n$ over test cases doesn't exceed $10^6$.
-----Output-----
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
-----Example-----
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
-----Note-----
In the first test case: the first network station can provide $2$ connections to the first city and $1$ connection to the second city; the second station can provide $2$ connections to the second city and $1$ connection to the third city; the third station can provide $3$ connections to the third city.
In the second test case: the $1$-st station can provide $2$ connections to the $1$-st city; the $2$-nd station can provide $3$ connections to the $2$-nd city; the $3$-rd station can provide $3$ connections to the $3$-rd city and $1$ connection to the $1$-st station.
In the third test case, the fourth city needs $5$ connections, but the third and the fourth station has $4$ connections in total.
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
############ ---- Input Functions ---- ############
def inp():
return (int(input()))
def instr():
return (str(input()))
def inlt():
return (list(map(int, input().split())))
def insr():
s = input()
return(list(map(int, list(s[:len(s) - 1]))))
# def insr():
# s = input()
# return list(s[:len(s) - 1])
def invr():
return (list(map(int, input().split())))
from collections import Counter
def check(cities, stations, k, allow):
# cities = cities.copy()
n = len(cities)
k = min(cities[0], k)
last_st = stations[-1] - k
c_i = cities[0] - k
for i in range(n - 1):
d = stations[i] - (c_i + cities[i + 1])
if d > 0:
# cities[i + 1] = 0
c_i = 0
allow -= d
if allow < 0:
return 1
elif stations[i] < c_i:
return -1
else:
c_i = cities[i + 1] - (stations[i] - c_i)
if c_i > last_st:
return -1
return 0
def bin_search(cities, stations, allow, l, r):
while l <= r:
mid = l + (r - l) // 2
res = check(cities, stations, mid, allow)
if res == 0:
return mid
elif res == -1:
l = mid + 1
else:
r = mid - 1
return -1
def main():
t = inp()
for _ in range(t):
n = inp()
cities = inlt()
stations = inlt()
allow = sum(stations) - sum(cities)
if allow < 0:
print('NO')
else:
res = bin_search(cities, stations, allow, 0, stations[-1] + 1)
if res == -1:
print('NO')
else:
print('YES')
def __starting_point():
main()
__starting_point()
``` | vfc_17974 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1373/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n3\n2 3 4\n3 3 3\n3\n3 3 3\n2 3 4\n4\n2 3 4 5\n3 7 2 2\n4\n4 5 2 3\n2 3 2 7\n2\n1 1\n10 10\n",
"output": "YES\nYES\nNO\nYES\nYES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2\n1 1000000000\n1000000000 1\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n10\n3 3 2 3 2 5 1 2 6 3\n6 5 2 5 6 2 4 2 1 2\n20\n9 1 10 1 17 7 5 5 8 1 1 2 7 1 4 2 3 7 6 3\n2 6 3 2 37 1 5 5 2 5 1 3 21 15 1 7 7 5 1 1\n20\n9 1 9 5 5 1 3 2 6 3 6 1 2 5 11 7 3 5 14 2\n11 14 6 4 6 8 8 2 9 9 6 5 3 2 5 7 1 9 14 1\n",
"output": "NO\nNO\nNO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2056 | Solve the following coding problem using the programming language python:
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of $n$ non-negative integers $a_1, \ldots, a_n$. You are allowed to perform the following operation: choose two distinct indices $1 \leq i, j \leq n$. If before the operation $a_i = x$, $a_j = y$, then after the operation $a_i = x~\mathsf{AND}~y$, $a_j = x~\mathsf{OR}~y$, where $\mathsf{AND}$ and $\mathsf{OR}$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute $\sum_{i=1}^n a_i^2$ — the sum of squares of all $a_i$. What is the largest sum of squares you can achieve?
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 2 \cdot 10^5$).
The second line contains $n$ integers $a_1, \ldots, a_n$ ($0 \leq a_i < 2^{20}$).
-----Output-----
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.
-----Examples-----
Input
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
-----Note-----
In the first sample no operation can be made, thus the answer is $123^2$.
In the second sample we can obtain the collection $1, 1, 7$, and $1^2 + 1^2 + 7^2 = 51$.
If $x$ and $y$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $x~\mathsf{AND}~y$ is set to $1$ if and only if both corresponding bits of $x$ and $y$ are set to $1$. Similarly, each bit of $x~\mathsf{OR}~y$ is set to $1$ if and only if at least one of the corresponding bits of $x$ and $y$ are set to $1$. For example, $x = 3$ and $y = 5$ are represented as $011_2$ and $101_2$ (highest bit first). Then, $x~\mathsf{AND}~y = 001_2 = 1$, and $x~\mathsf{OR}~y = 111_2 = 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
from copy import copy
input = sys.stdin.readline
n = int(input())
l = [int(a) for a in input().split()]
x = []
for i in range(0, 20):
res = 0
for a in l:
if a & (1 << i):
res += 1
x.append(res)
res = 0
for i in range(n):
a = 0
for j in range(20):
if i < x[j]:
a += (1 << j)
res += a ** 2
print(res)
``` | vfc_17978 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1368/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n123\n",
"output": "15129\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 3 5\n",
"output": "51\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n349525 699050\n",
"output": "1099509530625\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n991 143 445 903 399\n",
"output": "2241949\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2057 | Solve the following coding problem using the programming language python:
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number t_{i}: If Petya has visited this room before, he writes down the minute he was in this room last time; Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i.
Initially, Petya was in one of the rooms at minute 0, he didn't write down number t_0.
At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — then number of notes in Petya's logbook.
The second line contains n non-negative integers t_1, t_2, ..., t_{n} (0 ≤ t_{i} < i) — notes in the logbook.
-----Output-----
In the only line print a single integer — the minimum possible number of rooms in Paris catacombs.
-----Examples-----
Input
2
0 0
Output
2
Input
5
0 1 0 1 3
Output
3
-----Note-----
In the first sample, sequence of rooms Petya visited could be, for example 1 → 1 → 2, 1 → 2 → 1 or 1 → 2 → 3. The minimum possible number of rooms is 2.
In the second sample, the sequence could be 1 → 2 → 3 → 1 → 2 → 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())
mas = list(map(int, input().split()))
dist = set([0])
res = 1
for i, e in enumerate(mas):
time = i + 1
if e in dist:
dist.remove(e)
else:
res += 1
dist.add(time)
print(res)
``` | vfc_17982 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/886/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n0 0\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n0 1 0 1 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n0 1 0 0 0 0 0\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n0 0 0 0 0 0 1 4 4 0 2 2 4 1 7 1 11 0 8 4 12 12 3 0 3 2 2 4 3 9 1 5 4 6 9 14 6 2 4 18 7 7 19 11 20 13 17 16 0 34 2 6 12 27 9 4 29 22 4 20 20 17 17 20 37 53 17 3 3 15 1 46 11 24 31 6 12 6 11 18 13 1 5 0 19 10 24 41 16 41 18 52 46 39 16 30 18 23 53 13\n",
"output": "66\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n0 0 0 0 1 2 0 0 3 3 2 2 6 4 1 6 2 9 8 0 2 0 2 2 0 0 10 0 4 20 4 11 3 9 0 3 8 2 6 3 13 2 1 23 20 20 16 7 1 37 6 1 25 25 14 30 6 23 18 3 2 16 0 4 37 9 4 6 2 14 15 11 16 35 36 7 32 26 8 1 0 37 35 38 27 3 16 8 3 7 7 25 13 13 30 11 5 28 0 12\n",
"output": "71\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2058 | Solve the following coding problem using the programming language python:
Genos needs your help. He was asked to solve the following programming problem by Saitama:
The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as $\sum_{i = 1}^{|s|}|s_{i} - t_{i}|$, where s_{i} is the i-th character of s and t_{i} is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.
Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.
-----Input-----
The first line of the input contains binary string a (1 ≤ |a| ≤ 200 000).
The second line of the input contains binary string b (|a| ≤ |b| ≤ 200 000).
Both strings are guaranteed to consist of characters '0' and '1' only.
-----Output-----
Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
-----Examples-----
Input
01
00111
Output
3
Input
0011
0110
Output
2
-----Note-----
For the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.
The second sample case is described in the statement.
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
a = input()
b = input()
sumi = 0
for i in range(len(b) - len(a) + 1):
if b[i] == '1':
sumi += 1
lowest = 0
highest = len(b) - len(a) + 1
total = 0
for i in range(len(a)):
if a[i] == '0':
total += sumi
else:
total += highest - lowest - sumi
if b[lowest] == '1':
sumi -= 1
if highest < len(b) and b[highest] == '1':
sumi += 1
lowest += 1
highest += 1
print(total)
``` | vfc_17986 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/608/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "01\n00111\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0011\n0110\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0\n0\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n0\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2059 | Solve the following coding problem using the programming language python:
Let's call an array of non-negative integers $a_1, a_2, \ldots, a_n$ a $k$-extension for some non-negative integer $k$ if for all possible pairs of indices $1 \leq i, j \leq n$ the inequality $k \cdot |i - j| \leq min(a_i, a_j)$ is satisfied. The expansion coefficient of the array $a$ is the maximal integer $k$ such that the array $a$ is a $k$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.
You are given an array of non-negative integers $a_1, a_2, \ldots, a_n$. Find its expansion coefficient.
-----Input-----
The first line contains one positive integer $n$ — the number of elements in the array $a$ ($2 \leq n \leq 300\,000$). The next line contains $n$ non-negative integers $a_1, a_2, \ldots, a_n$, separated by spaces ($0 \leq a_i \leq 10^9$).
-----Output-----
Print one non-negative integer — expansion coefficient of the array $a_1, a_2, \ldots, a_n$.
-----Examples-----
Input
4
6 4 5 5
Output
1
Input
3
0 1 2
Output
0
Input
4
821 500 479 717
Output
239
-----Note-----
In the first test, the expansion coefficient of the array $[6, 4, 5, 5]$ is equal to $1$ because $|i-j| \leq min(a_i, a_j)$, because all elements of the array satisfy $a_i \geq 3$. On the other hand, this array isn't a $2$-extension, because $6 = 2 \cdot |1 - 4| \leq min(a_1, a_4) = 5$ is false.
In the second test, the expansion coefficient of the array $[0, 1, 2]$ is equal to $0$ because this array is not a $1$-extension, but it is $0$-extension.
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())
nums = [int(x) for x in input().split()]
ans = 10 ** 12
for idx, num in enumerate(nums):
dist = max(idx, n - idx - 1)
curr = num // dist
ans = min(ans, curr)
print(ans)
``` | vfc_17990 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1159/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n6 4 5 5\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n0 1 2\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n821 500 479 717\n",
"output": "239",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1000000000 1000000000\n",
"output": "1000000000",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2060 | Solve the following coding problem using the programming language python:
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly this amount of chicken.
Formally, Ivan wants to know if he can choose two non-negative integers a and b in such a way that a small portions and b large ones contain exactly x chunks.
Help Ivan to answer this question for several values of x!
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 100) — the number of testcases.
The i-th of the following n lines contains one integer x_{i} (1 ≤ x_{i} ≤ 100) — the number of chicken chunks Ivan wants to eat.
-----Output-----
Print n lines, in i-th line output YES if Ivan can buy exactly x_{i} chunks. Otherwise, print NO.
-----Example-----
Input
2
6
5
Output
YES
NO
-----Note-----
In the first example Ivan can buy two small portions.
In the second example Ivan cannot buy exactly 5 chunks, since one small portion is not enough, but two small portions or one large is too much.
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())
for i in range(n):
x=int(input())
f=0
for a in range(100):
for b in range(100):
if 3*a+7*b==x:
f=1
if f==1:
print("YES")
else:
print("NO")
``` | vfc_17994 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/903/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n6\n5\n",
"output": "YES\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n",
"output": "NO\nNO\nYES\nNO\nNO\nYES\nYES\nNO\nYES\nYES\nNO\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nYES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2061 | Solve the following coding problem using the programming language python:
The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean.
Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.
You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k.
-----Input-----
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 0 ≤ k ≤ 50) — the sizes of the map and the number of lakes which should be left on the map.
The next n lines contain m characters each — the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land).
It is guaranteed that the map contain at least k lakes.
-----Output-----
In the first line print the minimum number of cells which should be transformed from water to land.
In the next n lines print m symbols — the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them.
It is guaranteed that the answer exists on the given data.
-----Examples-----
Input
5 4 1
****
*..*
****
**.*
..**
Output
1
****
*..*
****
****
..**
Input
3 3 0
***
*.*
***
Output
1
***
***
***
-----Note-----
In the first example there are only two lakes — the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time
sys.setrecursionlimit(10**7)
inf = 10**10
mod = 10**9 + 7
def f():
n,m,k = list(map(int, input().split()))
a = [[inf]*(m+2)]
g = []
for _ in range(n):
a.append([inf] + [_ for _ in input()] + [inf])
g.append([False]*m)
a.append([[inf]*(m+2)])
c = 0
for i in range(1,n+1):
if a[i][1] == '.':
a[i][1] = -1
if a[i][-2] == '.':
a[i][-2] = -1
for j in range(1,m+1):
if a[1][j] == '.':
a[1][j] = -1
if a[-2][j] == '.':
a[-2][j] = -1
def ff(n1,n2):
for i in range(1,n+1):
for j in range(1,m+1):
if a[i][j] == n1:
a[i][j] = n2
ff('*', inf)
for i in range(1,n+1):
for j in range(1,m+1):
if a[i][j] == '.':
mc = [inf]
if a[i-1][j] != '.': mc.append(a[i-1][j])
if a[i+1][j] != '.': mc.append(a[i+1][j])
if a[i][j+1] != '.': mc.append(a[i][j+1])
if a[i][j-1] != '.': mc.append(a[i][j-1])
mm = min(mc)
if mm < inf:
a[i][j] = mm
for t in [_ for _ in mc if _ < inf and _ != mm]:
ff(t,mm)
else:
a[i][j] = c
c += 1
cnt = [0] * c
for i in range(1,n+1):
for j in range(1,m+1):
if -1 < a[i][j] < c:
cnt[a[i][j]] += 1
cnt2 = [_ for _ in cnt if _ > 0]
r = 0
for _i in range(len(cnt2) - k):
cnt2 = [_ for _ in cnt if _ > 0]
mm = min(cnt2)
ind = cnt.index(mm)
cnt[ind] = 0
r += mm
for i in range(1,n+1):
for j in range(1,m+1):
if a[i][j] == ind:
a[i][j] = '*'
print(r)
for i in range(1,n+1):
s = ''
for j in range(1,m+1):
c = a[i][j]
if c == '*':
s += c
elif c == inf:
s += '*'
else:
s += '.'
print(s)
f()
``` | vfc_17998 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/723/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 4 1\n****\n*..*\n****\n**.*\n..**\n",
"output": "1\n****\n*..*\n****\n****\n..**\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 0\n***\n*.*\n***\n",
"output": "1\n***\n***\n***\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 5 1\n.**.*\n*.*.*\n***..\n",
"output": "0\n.**.*\n*.*.*\n***..\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2062 | Solve the following coding problem using the programming language python:
Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.
There are n video cards in the shop, the power of the i-th video card is equal to integer value a_{i}. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it can't be reduced.
Vlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of video cards in the shop.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 200 000) — powers of video cards.
-----Output-----
The only line of the output should contain one integer value — the maximum possible total power of video cards working together.
-----Examples-----
Input
4
3 2 15 9
Output
27
Input
4
8 2 2 7
Output
18
-----Note-----
In the first sample, it would be optimal to buy video cards with powers 3, 15 and 9. The video card with power 3 should be chosen as the leading one and all other video cards will be compatible with it. Thus, the total power would be 3 + 15 + 9 = 27. If he buys all the video cards and pick the one with the power 2 as the leading, the powers of all other video cards should be reduced by 1, thus the total power would be 2 + 2 + 14 + 8 = 26, that is less than 27. Please note, that it's not allowed to reduce the power of the leading video card, i.e. one can't get the total power 3 + 1 + 15 + 9 = 28.
In the second sample, the optimal answer is to buy all video cards and pick the one with the power 2 as the leading. The video card with the power 7 needs it power to be reduced down to 6. The total power would be 8 + 2 + 2 + 6 = 18.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
input()
l = list(map(int, input().split()))
n = max(l)
aa = [0] * (n + 1)
for x in l:
aa[x] += 1
f, x = [0] * n, 0
for a in reversed(aa):
x += a
f.append(x)
f.reverse()
res = []
for i, a in enumerate(aa):
if a:
tot, a = 0, f[i]
for j in range(i, n + 1, i):
b = f[j + i]
tot += (a - b) * j
a = b
res.append(tot)
print(max(res))
def __starting_point():
main()
__starting_point()
``` | vfc_18002 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/731/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n3 2 15 9\n",
"output": "27\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n8 2 2 7\n",
"output": "18\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2063 | Solve the following coding problem using the programming language python:
Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions.
There are m days left to the birthday. The height of the i-th flower (assume that the flowers in the row are numbered from 1 to n from left to right) is equal to a_{i} at the moment. At each of the remaining m days the beaver can take a special watering and water w contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get?
-----Input-----
The first line contains space-separated integers n, m and w (1 ≤ w ≤ n ≤ 10^5; 1 ≤ m ≤ 10^5). The second line contains space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print a single integer — the maximum final height of the smallest flower.
-----Examples-----
Input
6 2 3
2 2 2 2 1 1
Output
2
Input
2 5 1
5 8
Output
9
-----Note-----
In the first sample beaver can water the last 3 flowers at the first day. On the next day he may not to water flowers at all. In the end he will get the following heights: [2, 2, 2, 3, 2, 2]. The smallest flower has height equal to 2. It's impossible to get height 3 in this test.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
from collections import defaultdict
def f(x):
inc = [0 for i in range(n + w)]
cur_inc = 0
days = m
for i, v in enumerate(arr):
cur_inc -= inc[i]
v += cur_inc
if x - v > days:
return False
if x > v:
cur_inc += x - v
days -= x - v
inc[i + w] += x - v
return True
n, m, w = [int(i) for i in input().split()]
arr = [int(i) for i in input().split()]
left, right = min(arr), max(arr) + m + 1
while right - left > 1:
middle = (left + right) // 2
if f(middle):
left = middle
else:
right = middle
print(left)
main()
``` | vfc_18006 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/460/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 2 3\n2 2 2 2 1 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 5 1\n5 8\n",
"output": "9\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2064 | Solve the following coding problem using the programming language python:
Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below. [Image]
So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted.
The battery of the newest device allows to highlight at most n sections on the display.
Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.
-----Input-----
The first line contains the integer n (2 ≤ n ≤ 100 000) — the maximum number of sections which can be highlighted on the display.
-----Output-----
Print the maximum integer which can be shown on the display of Stepan's newest device.
-----Examples-----
Input
2
Output
1
Input
3
Output
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());
if (n % 2 != 0):
s = '7';
n -= 3;
else:
s = '1';
n-=2;
for i in range(n // 2): s = s + '1';
print(s);
``` | vfc_18010 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/774/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "71\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2065 | Solve the following coding problem using the programming language python:
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied: A = B; the man number A is the father of the man number B; there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B.
Of course, if the man number A is an ancestor of the man number B and A ≠ B, then the man number B is not an ancestor of the man number A.
The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens. A list of candidates is prepared, containing some (possibly all) of the n men in some order. Each of the n men decides to give a gift. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.
This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?
-----Input-----
In the first line of the input two integers n and m (0 ≤ m < n ≤ 100 000) are given — the number of the men in the Sasha's family and the number of family relations in it respectively.
The next m lines describe family relations: the (i + 1)^{th} line consists of pair of integers p_{i} and q_{i} (1 ≤ p_{i}, q_{i} ≤ n, p_{i} ≠ q_{i}) meaning that the man numbered p_{i} is the father of the man numbered q_{i}. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father.
The next line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n), i^{th} of which means that the man numbered i wants to give a gift to the man numbered a_{i}. It is guaranteed that for every 1 ≤ i ≤ n the man numbered a_{i} is an ancestor of the man numbered i.
-----Output-----
Print an integer k (1 ≤ k ≤ n) — the number of the men in the list of candidates, in the first line.
Print then k pairwise different positive integers not exceeding n — the numbers of the men in the list in an order satisfying every of the men's wishes, one per line.
If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line.
-----Examples-----
Input
3 2
1 2
2 3
1 2 1
Output
-1
Input
4 2
1 2
3 4
1 2 3 3
Output
3
2
1
3
-----Note-----
The first sample explanation: if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a_1 = a_3 = 1); if there would be no 2 in the list then the second man wish would not be satisfied (a_2 = 2); if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a_2 = 2). if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a_3 = 1).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
cp = [-1] * n
for i in range(m):
p, c = map(int, input().split())
adj[p - 1].append(c - 1)
cp[c - 1] = p - 1
pres = [i - 1 for i in map(int, input().split())]
level = [0] * n
from collections import deque
def bfs(v):
q = deque([v])
while q:
v = q.pop()
if cp[v] >= 0:
level[v] = level[cp[v]] + 1
for nv in adj[v]:
q.append(nv)
for i in range(n):
if cp[i] == -1:
bfs(i)
for i in range(n):
if level[i] > 0:
par = cp[i]
if pres[i] != pres[par] and level[pres[i]] <= level[par]:
print(-1)
return
pres = list(set(pres))
pres = sorted(pres, key = lambda i : level[i], reverse = True)
print(len(pres))
pres = [i + 1 for i in pres]
print("\n".join(map(str, pres)))
``` | vfc_18014 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/681/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n1 2\n2 3\n1 2 1\n",
"output": "-1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2\n1 2\n3 4\n1 2 3 3\n",
"output": "3\n2\n1\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 0\n1\n",
"output": "1\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2066 | Solve the following coding problem using the programming language python:
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions $(1, 2)$ — "ab" and $(2, 3)$ — "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer $T$ separate queries.
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 100$) — the number of queries.
Each of the next $T$ lines contains string $s$ $(1 \le |s| \le 100)$ — the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set $T = 1$.
-----Output-----
Print $T$ lines. The $i$-th line should contain the answer to the $i$-th query.
If the answer for the $i$-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
-----Example-----
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
-----Note-----
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from collections import Counter
import string
def valid(o):
for x, y in zip(o, o[1:]):
if abs(ord(x) - ord(y)) == 1:
return False
return True
def create(c, o):
res = []
for x in o:
for j in range(c[x]):
res.append(x)
return res
T = int(input())
for _ in range(T):
c = Counter(input())
o = []
o1 = string.ascii_lowercase[1::2] + string.ascii_lowercase[::2]
o2 = string.ascii_lowercase[::2] + string.ascii_lowercase[1::2]
s1 = create(c, o1)
s2 = create(c, o2)
if valid(s1):
print(''.join(s1))
elif valid(s2):
print(''.join(s2))
else:
print('No answer')
``` | vfc_18018 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1156/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\nabcd\ngg\ncodeforces\nabaca\n",
"output": "bdac\ngg\ndfrcceeoos\nNo answer\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nddb\n",
"output": "bdd\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2067 | Solve the following coding problem using the programming language python:
On a chessboard with a width of $10^9$ and a height of $10^9$, the rows are numbered from bottom to top from $1$ to $10^9$, and the columns are numbered from left to right from $1$ to $10^9$. Therefore, for each cell of the chessboard you can assign the coordinates $(x,y)$, where $x$ is the column number and $y$ is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates $(1,1)$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the upper side of the field (that is, in any cell that is in the row with number $10^9$).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells: Vertical. Each of these is defined by one number $x$. Such spells create an infinite blocking line between the columns $x$ and $x+1$. Horizontal. Each of these is defined by three numbers $x_1$, $x_2$, $y$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $y$ and in columns from $x_1$ to $x_2$ inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
[Image]
An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $(r_0,c_0)$ into the cell $(r_1,c_1)$ only under the condition that $r_1 = r_0$ or $c_1 = c_0$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
-----Input-----
The first line contains two integers $n$ and $m$ ($0 \le n,m \le 10^5$) — the number of vertical and horizontal spells.
Each of the following $n$ lines contains one integer $x$ ($1 \le x < 10^9$) — the description of the vertical spell. It will create a blocking line between the columns of $x$ and $x+1$.
Each of the following $m$ lines contains three integers $x_1$, $x_2$ and $y$ ($1 \le x_{1} \le x_{2} \le 10^9$, $1 \le y < 10^9$) — the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number $y$, in columns from $x_1$ to $x_2$ inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
-----Output-----
In a single line print one integer — the minimum number of spells the rook needs to remove so it can get from the cell $(1,1)$ to at least one cell in the row with the number $10^9$
-----Examples-----
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
-----Note-----
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
[Image] Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
$m$ Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
[Image] Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
[Image] Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 11/20/18
"""
import collections
import bisect
N, M = map(int, input().split())
vlines = []
for i in range(N):
x = int(input())
vlines.append(x)
vlines.sort()
vlines.append(10**9)
yxs = collections.defaultdict(list)
ys = set()
for i in range(M):
l, r, y = map(int, input().split())
yxs[y].append((l, r))
if l <= 1:
ys.add(y)
def merge(segs):
segs.sort()
ans = [segs[0]]
for s in segs[1:]:
pre = ans[-1]
if s[0] > pre[1]:
# ans.append(s)
return ans[0]
else:
ans[-1] = (pre[0], s[1])
return ans[0]
xs = [merge(yxs[y])[1] for y in ys]
xs.sort()
ans = float('inf')
for i, x in enumerate(vlines):
if i >= ans:
break
# count = i + sum([1 if u >= x else 0 for u in xs])
count = i + len(xs) - bisect.bisect_left(xs, x)
ans = min(ans, count)
print(ans)
``` | vfc_18022 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1044/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3\n6\n8\n1 5 6\n1 9 4\n2 4 2\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 3\n4\n1 5 3\n1 9 4\n4 6 6\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0 2\n1 1000000000 4\n1 1000000000 2\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0 0\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n4\n6\n1 4 3\n1 5 2\n1 6 5\n",
"output": "2",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2068 | Solve the following coding problem using the programming language python:
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.
We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.
-----Output-----
Print a single integer — the maximum length of a repost chain.
-----Examples-----
Input
5
tourist reposted Polycarp
Petr reposted Tourist
WJMZBMR reposted Petr
sdya reposted wjmzbmr
vepifanov reposted sdya
Output
6
Input
6
Mike reposted Polycarp
Max reposted Polycarp
EveryOne reposted Polycarp
111 reposted Polycarp
VkCup reposted Polycarp
Codeforces reposted Polycarp
Output
2
Input
1
SoMeStRaNgEgUe reposted PoLyCaRp
Output
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 main():
mx = 1
n = int(input())
D = {}
D["polycarp"] = 1
for i in range(n):
s, r, t = input().split()
s = s.lower()
t = t.lower()
D[s] = D[t] + 1
mx = max(mx, D[s])
print(mx)
main()
``` | vfc_18026 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/522/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nSoMeStRaNgEgUe reposted PoLyCaRp\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2069 | Solve the following coding problem using the programming language python:
You are given a permutation p of length n. Also you are given m foe pairs (a_{i}, b_{i}) (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}).
Your task is to count the number of different intervals (x, y) (1 ≤ x ≤ y ≤ n) that do not contain any foe pairs. So you shouldn't count intervals (x, y) that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important).
Consider some example: p = [1, 3, 2, 4] and foe pairs are {(3, 2), (4, 2)}. The interval (1, 3) is incorrect because it contains a foe pair (3, 2). The interval (1, 4) is also incorrect because it contains two foe pairs (3, 2) and (4, 2). But the interval (1, 2) is correct because it doesn't contain any foe pair.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 3·10^5) — the length of the permutation p and the number of foe pairs.
The second line contains n distinct integers p_{i} (1 ≤ p_{i} ≤ n) — the elements of the permutation p.
Each of the next m lines contains two integers (a_{i}, b_{i}) (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}) — the i-th foe pair. Note a foe pair can appear multiple times in the given list.
-----Output-----
Print the only integer c — the number of different intervals (x, y) that does not contain any foe pairs.
Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
-----Examples-----
Input
4 2
1 3 2 4
3 2
2 4
Output
5
Input
9 5
9 7 2 3 1 4 6 5 8
1 6
4 5
2 7
7 2
2 7
Output
20
-----Note-----
In the first example the intervals from the answer are (1, 1), (1, 2), (2, 2), (3, 3) and (4, 4).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
from sys import stdin
n, m = list(map(int, input().split()))
n += 1
aa, pos, duo = [0] * n, [0] * n, [0] * n
for i, a in enumerate(map(int, input().split()), 1):
aa[i] = a
pos[a] = i
for s in stdin.read().splitlines():
x, y = list(map(int, s.split()))
px, py = pos[x], pos[y]
if px > py:
if duo[x] < py:
duo[x] = py
else:
if duo[y] < px:
duo[y] = px
res = mx = 0
for i, a in enumerate(aa):
if mx < duo[a]:
mx = duo[a]
res += i - mx
print(res)
def __starting_point():
main()
__starting_point()
``` | vfc_18030 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/652/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2\n1 3 2 4\n3 2\n2 4\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 5\n9 7 2 3 1 4 6 5 8\n1 6\n4 5\n2 7\n7 2\n2 7\n",
"output": "20\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n1 2\n1 2\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2071 | Solve the following coding problem using the programming language python:
Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.
Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.
Help Vasya! Calculate the maximum total weight of mushrooms he can collect.
-----Input-----
The first line contains the number n (1 ≤ n ≤ 3·10^5) — the length of the glade.
The second line contains n numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the growth rate of mushrooms in the first row of the glade.
The third line contains n numbers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^6) is the growth rate of mushrooms in the second row of the glade.
-----Output-----
Output one number — the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.
-----Examples-----
Input
3
1 2 3
6 5 4
Output
70
Input
3
1 1000 10000
10 100 100000
Output
543210
-----Note-----
In the first test case, the optimal route is as follows: [Image] Thus, the collected weight of mushrooms will be 0·1 + 1·2 + 2·3 + 3·4 + 4·5 + 5·6 = 70.
In the second test case, the optimal route is as follows: [Image] Thus, the collected weight of mushrooms will be 0·1 + 1·10 + 2·100 + 3·1000 + 4·10000 + 5·100000 = 543210.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
def f(l):
s = sum(l)
sume = [s for i in range(n)]
s3 = [0 for i in range(n)]
ts = 0
for i in range(1, n):
sume[i] = sume[i - 1] - l[i - 1]
ts += i * l[i]
s3[n - i - 1] = s3[n - i] + i * l[n - i - 1]
s2 = [ts for i in range(n)]
for i in range(1, n):
s2[i] = s2[i - 1] - (i - 1) * l[i - 1]
return sume, s2, s3
a1, a2, a3 = f(a)
b1, b2, b3 = f(b)
best = 0
curr, t = 0, 0
for i in range(n):
if i % 2 == 0:
pot = curr + t * a1[i] + a2[i] - i * a1[i] +\
(t + n - i) * b1[i] + b3[i]
else:
pot = curr + t * b1[i] + b2[i] - i * b1[i] +\
(t + n - i) * a1[i] + a3[i]
best = max(best, pot)
if i % 2 == 0:
curr += t * a[i] + (t + 1) * b[i]
else:
curr += t * b[i] + (t + 1) * a[i]
t += 2
print(max(best, curr))
``` | vfc_18038 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1016/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 3\n6 5 4\n",
"output": "70\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 1000 10000\n10 100 100000\n",
"output": "543210\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2072 | Solve the following coding problem using the programming language python:
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.
At some points on the road there are n friends, and i-th of them is standing at the point x_{i} meters and can move with any speed no greater than v_{i} meters per second in any of the two directions along the road: south or north.
You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.
-----Input-----
The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends.
The second line contains n integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9) — the current coordinates of the friends, in meters.
The third line contains n integers v_1, v_2, ..., v_{n} (1 ≤ v_{i} ≤ 10^9) — the maximum speeds of the friends, in meters per second.
-----Output-----
Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road.
Your answer will be considered correct, if its absolute or relative error isn't greater than 10^{ - 6}. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$ holds.
-----Examples-----
Input
3
7 1 3
1 2 1
Output
2.000000000000
Input
4
5 10 3 2
2 3 2 4
Output
1.400000000000
-----Note-----
In the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds.
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())
xs = list(map(int, input().split()))
vs = list(map(int, input().split()))
l = 0
r = max(xs) - min(xs) + 1
for i in range(50):
m = (r + l) / 2
lev = 0
prav = 1000000000
for j in range(n):
prav = min(prav, xs[j] + vs[j] * m)
lev = max(lev, xs[j] - vs[j] * m)
if prav < lev:
break
if prav < lev:
l = m
else:
r = m
print((l + r) / 2)
``` | vfc_18042 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/780/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n7 1 3\n1 2 1\n",
"output": "2.000000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n5 10 3 2\n2 3 2 4\n",
"output": "1.400000000000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2073 | Solve the following coding problem using the programming language python:
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n.
There are n directed roads in the Udayland. i-th of them goes from town i to some other town a_{i} (a_{i} ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after.
ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A_1, A_2, ..., A_{k} (k > 1) such that for every 1 ≤ i < k there is a road from town A_{i} to town A_{i} + 1 and another road from town A_{k} to town A_1. In other words, the roads are confusing if some of them form a directed cycle of some towns.
Now ZS the Coder wonders how many sets of roads (there are 2^{n} variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing.
Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
-----Input-----
The first line of the input contains single integer n (2 ≤ n ≤ 2·10^5) — the number of towns in Udayland.
The next line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n, a_{i} ≠ i), a_{i} denotes a road going from town i to town a_{i}.
-----Output-----
Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 10^9 + 7.
-----Examples-----
Input
3
2 3 1
Output
6
Input
4
2 1 1 1
Output
8
Input
5
2 4 2 5 3
Output
28
-----Note-----
Consider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are $1 \rightarrow 2$, $2 \rightarrow 3$, $3 \rightarrow 1$ initially. Number the roads 1 to 3 in this order.
The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip.
The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.
[Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# You lost the game.
n = int(input())
A = list(map(int, input().split()))
V = [0 for _ in range(n)]
G = V[:]
def visiter(i,d):
nonlocal V
nonlocal G
G[i] = d+1
V[i] = d+1
c = d+2
while 1:
if V[A[i]-1] and G[A[i]-1] > d:
return 1,c-G[A[i]-1],G[A[i]-1]-1-d,c
elif V[A[i]-1]:
return 0,0,c-1-d,c
else:
G[A[i]-1] = c
c += 1
V[A[i]-1] = 1
i = A[i]-1
T = [1 for _ in range(n+1)]
for i in range(1,n+1):
T[i] = (T[i-1]*2) % (10**9 + 7)
R = []
d = 0
i = 0
c = 0
for i in range(n):
if V[i] == 0:
v,l,s,c = visiter(i,c)
if v:
R += [l]
d += s
r = T[d]
for x in R:
r = (r*(T[x]-2)) % (10**9 + 7)
print(r)
``` | vfc_18046 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/711/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 3 1\n",
"output": "6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2074 | Solve the following coding problem using the programming language python:
Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.
Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is c_{ij}.
Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.
-----Input-----
The first line contains two integers n, m (1 ≤ n, m ≤ 100) — the number of streets and avenues in Munhattan.
Each of the next n lines contains m integers c_{ij} (1 ≤ c_{ij} ≤ 10^9) — the cost of the dinner in the restaurant on the intersection of the i-th street and the j-th avenue.
-----Output-----
Print the only integer a — the cost of the dinner for Jack and Emma.
-----Examples-----
Input
3 4
4 1 3 5
2 2 2 2
5 4 5 1
Output
2
Input
3 3
1 2 3
2 3 1
3 1 2
Output
1
-----Note-----
In the first example if Emma chooses the first or the third streets Jack can choose an avenue with the cost of the dinner 1. So she chooses the second street and Jack chooses any avenue. The cost of the dinner is 2.
In the second example regardless of Emma's choice Jack can choose a restaurant with the cost of the dinner 1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
q=list(map(int,input().split()))
a=[]
s=[]
for i in range(0,q[0]):
s+=[min(list(map(int,input().split())))]
print(max(s))
``` | vfc_18050 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/616/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4\n4 1 3 5\n2 2 2 2\n5 4 5 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n1 2 3\n2 3 1\n3 1 2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 10\n74 35 82 39 1 84 29 41 70 12\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2075 | Solve the following coding problem using the programming language python:
As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings!
The sequence of round brackets is called valid if and only if: the total number of opening brackets is equal to the total number of closing brackets; for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets.
Gabi bought a string s of length m (m ≤ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s.
Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 10^9 + 7.
-----Input-----
First line contains n and m (1 ≤ m ≤ n ≤ 100 000, n - m ≤ 2000) — the desired length of the string and the length of the string bought by Gabi, respectively.
The second line contains string s of length m consisting of characters '(' and ')' only.
-----Output-----
Print the number of pairs of string p and q such that p + s + q is a valid sequence of round brackets modulo 10^9 + 7.
-----Examples-----
Input
4 1
(
Output
4
Input
4 4
(())
Output
1
Input
4 3
(((
Output
0
-----Note-----
In the first sample there are four different valid pairs: p = "(", q = "))" p = "()", q = ")" p = "", q = "())" p = "", q = ")()"
In the second sample the only way to obtain a desired string is choose empty p and q.
In the third sample there is no way to get a valid sequence of brackets.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = list(map(int, input().split()))
s = input()
mod = 10 ** 9 + 7
c = b = 0
for x in s:
c += (x == '(') * 2 - 1
b = min(c, b)
d = [[1]]
for i in range(n - m):
nd = d[-1][1:] + [0] * 2
for j in range(1, i + 2):
nd[j] = (nd[j] + d[-1][j-1]) % mod
d.append(nd)
ans = 0
for i in range(n - m + 1):
l = n - m - i
for j in range(-b, min(l - c, i) + 1):
ans = (ans + d[i][j] * d[l][j + c]) % mod
print(ans)
``` | vfc_18054 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/629/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 1\n(\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4\n(())\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3\n(((\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2076 | Solve the following coding problem using the programming language python:
Alice is playing with some stones.
Now there are three numbered heaps of stones. The first of them contains $a$ stones, the second of them contains $b$ stones and the third of them contains $c$ stones.
Each time she can do one of two operations: take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones); take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones).
She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $0$ stones. Can you help her?
-----Input-----
The first line contains one integer $t$ ($1 \leq t \leq 100$) — the number of test cases. Next $t$ lines describe test cases in the following format:
Line contains three non-negative integers $a$, $b$ and $c$, separated by spaces ($0 \leq a,b,c \leq 100$) — the number of stones in the first, the second and the third heap, respectively.
In hacks it is allowed to use only one test case in the input, so $t = 1$ should be satisfied.
-----Output-----
Print $t$ lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer — the maximum possible number of stones that Alice can take after making some operations.
-----Example-----
Input
3
3 4 5
1 0 5
5 3 2
Output
9
0
6
-----Note-----
For the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is $9$. It is impossible to make some operations to take more than $9$ stones, so the answer is $9$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# Contest: Codeforces Round #593 (Div. 2) (https://codeforces.com/contest/1236)
# Problem: A: Stones (https://codeforces.com/contest/1236/problem/A)
def rint():
return int(input())
def rints():
return list(map(int, input().split()))
t = rint()
for _ in range(t):
a, b, c, = rints()
mx = 0
for ta in range(0, min(a, b // 2) + 1):
mx = max(mx, 3 * ta + 3 * min(b - 2 * ta, c // 2))
print(mx)
``` | vfc_18058 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1236/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 4 5\n1 0 5\n5 3 2\n",
"output": "9\n0\n6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "64\n0 0 0\n0 0 1\n0 0 2\n0 0 3\n0 1 0\n0 1 1\n0 1 2\n0 1 3\n0 2 0\n0 2 1\n0 2 2\n0 2 3\n0 3 0\n0 3 1\n0 3 2\n0 3 3\n1 0 0\n1 0 1\n1 0 2\n1 0 3\n1 1 0\n1 1 1\n1 1 2\n1 1 3\n1 2 0\n1 2 1\n1 2 2\n1 2 3\n1 3 0\n1 3 1\n1 3 2\n1 3 3\n2 0 0\n2 0 1\n2 0 2\n2 0 3\n2 1 0\n2 1 1\n2 1 2\n2 1 3\n2 2 0\n2 2 1\n2 2 2\n2 2 3\n2 3 0\n2 3 1\n2 3 2\n2 3 3\n3 0 0\n3 0 1\n3 0 2\n3 0 3\n3 1 0\n3 1 1\n3 1 2\n3 1 3\n3 2 0\n3 2 1\n3 2 2\n3 2 3\n3 3 0\n3 3 1\n3 3 2\n3 3 3\n",
"output": "0\n0\n0\n0\n0\n0\n3\n3\n0\n0\n3\n3\n0\n0\n3\n3\n0\n0\n0\n0\n0\n0\n3\n3\n3\n3\n3\n3\n3\n3\n6\n6\n0\n0\n0\n0\n0\n0\n3\n3\n3\n3\n3\n3\n3\n3\n6\n6\n0\n0\n0\n0\n0\n0\n3\n3\n3\n3\n3\n3\n3\n3\n6\n6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2078 | Solve the following coding problem using the programming language python:
There is a square of size $10^6 \times 10^6$ on the coordinate plane with four points $(0, 0)$, $(0, 10^6)$, $(10^6, 0)$, and $(10^6, 10^6)$ as its vertices.
You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.
Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.
-----Input-----
The first line contains two integers $n$ and $m$ ($0 \le n, m \le 10^5$) — the number of horizontal segments and the number of vertical segments.
The next $n$ lines contain descriptions of the horizontal segments. The $i$-th line contains three integers $y_i$, $lx_i$ and $rx_i$ ($0 < y_i < 10^6$; $0 \le lx_i < rx_i \le 10^6$), which means the segment connects $(lx_i, y_i)$ and $(rx_i, y_i)$.
The next $m$ lines contain descriptions of the vertical segments. The $i$-th line contains three integers $x_i$, $ly_i$ and $ry_i$ ($0 < x_i < 10^6$; $0 \le ly_i < ry_i \le 10^6$), which means the segment connects $(x_i, ly_i)$ and $(x_i, ry_i)$.
It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.
-----Output-----
Print the number of pieces the square is divided into after drawing all the segments.
-----Example-----
Input
3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000
Output
7
-----Note-----
The sample is like this: [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
import sys
input=sys.stdin.readline
class BIT:
def __init__(self,n):
self.n=n+1
self.BIT=[0]*self.n
def add(self,i,x):
idx=i
while idx<self.n:
self.BIT[idx]+=x
idx+=(idx&-idx)
def _sum(self,i):
if i==-1:
return -1
ret=0
idx=i
while idx>0:
ret+=self.BIT[idx]
idx-=(idx&-idx)
return ret
def sum(self,l,r):
return self._sum(r)-self._sum(l-1)
def value(self,i):
return self._sum(i)-self._sum(i-1)
bound=10**6
n,m=map(int,input().split())
yoko_edges=[list(map(int,input().split())) for _ in range(n)]
yoko_edges=sorted(yoko_edges,reverse=True,key=lambda x:x[0])
ue_tate_edges=[[] for _ in range(bound+1)]
sita_tate_edges=[[] for _ in range(bound+1)]
tate_edges=BIT(bound)
tate_edges.add(bound,1)
ans=1
for _ in range(m):
x,l,r=map(int,input().split())
if l==0 and r==bound:
tate_edges.add(x,1)
ans+=1
elif l==0:
sita_tate_edges[r].append(x)
elif r==bound:
ue_tate_edges[l].append(x)
tate_edges.add(x,1)
prev=bound-1
for y,l,r in yoko_edges:
while prev>=y:
for x in sita_tate_edges[prev]:
tate_edges.add(x,1)
for x in ue_tate_edges[prev+1]:
tate_edges.add(x,-1)
prev-=1
ans+=tate_edges.sum(l,r)-1
print(ans)
``` | vfc_18066 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1401/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3\n2 3 1000000\n4 0 4\n3 0 1000000\n4 0 1\n2 0 5\n3 1 1000000\n",
"output": "7",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2079 | Solve the following coding problem using the programming language python:
In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct.
Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers: an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it.
You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 200\,000$) — the number of rows in the bus.
The second line contains the sequence of integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le 10^{9}$), where $w_i$ is the width of each of the seats in the $i$-th row. It is guaranteed that all $w_i$ are distinct.
The third line contains a string of length $2n$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $j$-th character is '0', then the passenger that enters the bus on the $j$-th stop is an introvert. If the $j$-th character is '1', the the passenger that enters the bus on the $j$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $n$), and for each extrovert there always is a suitable row.
-----Output-----
Print $2n$ integers — the rows the passengers will take. The order of passengers should be the same as in input.
-----Examples-----
Input
2
3 1
0011
Output
2 1 1 2
Input
6
10 8 9 11 13 5
010010011101
Output
6 6 2 3 3 1 4 4 1 2 5 5
-----Note-----
In the first example the first passenger (introvert) chooses the row $2$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $1$, because it is the only empty row now. The third passenger (extrovert) chooses the row $1$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $2$, because it is the only row with an empty place.
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():
n = int(input())
a = list(map(int, input().split()))
s = input()
b = []
for i in range(n):
b.append([a[i], i + 1])
b.sort()
ans = []
count1, count2 = 0, 0
c = deque([])
for i in range(2 * n):
if (s[i] == '0'):
ans.append(b[count1][1])
c.append(b[count1][1])
count1 += 1
else:
ans.append(c[-1])
c.pop()
count2 += 1
for i in range(2 * n):
print(ans[i], end=' ')
main()
``` | vfc_18070 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/982/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n3 1\n0011\n",
"output": "2 1 1 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n10 8 9 11 13 5\n010010011101\n",
"output": "6 6 2 3 3 1 4 4 1 2 5 5 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n01\n",
"output": "1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000\n01\n",
"output": "1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1000000\n0011\n",
"output": "1 2 2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1000000000 1\n0101\n",
"output": "2 2 1 1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2080 | Solve the following coding problem using the programming language python:
Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.
Ivan decided that there should be exactly n_{i} vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.
So the task Ivan gave you is: given q numbers n_1, n_2, ..., n_{q}, for each i tell the maximum number of edges in a graph with n_{i} vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.
-----Input-----
The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct.
Then q lines follow, i-th line contains one positive integer n_{i} (1 ≤ n_{i} ≤ 2·10^9) — the number of vertices in i-th graph.
Note that in hacks you have to use q = 1.
-----Output-----
Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph.
-----Example-----
Input
3
3
4
6
Output
2
3
6
-----Note-----
In the first example it is possible to construct these graphs: 1 - 2, 1 - 3; 1 - 2, 1 - 3, 2 - 4; 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.
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 python
# http://codeforces.com/problemset/problem/818/F
# Problem name ::: F. Level Generation
# submission number
#212055293
#508427854
def newest_approach(n):
from math import floor, ceil, sqrt
quad_solv = sqrt(2*n+1/4)-1/2
x = floor(quad_solv)
y = ceil(quad_solv)
xed = int(x*(x-1)/2 + n - x)
xbr = n - x
ybr = n - y
yed = 2*ybr
if xed > yed:
print(xed)
# print("nodes = %s :: edges = %s :: bridges = %s" % (n, xed, xbr))
else:
print(yed)
# print("nodes = %s :: edges = %s :: bridges = %s" % (n, yed, ybr))
return
def main():
import sys
data = [line.rstrip() for line in sys.stdin.readlines()]
num_graphs = data[0]
graph_sizes = [int(x) for x in data[1:]]
for val in graph_sizes:
# binary_search(val)
# new_approach(val)
newest_approach(val)
def __starting_point():
main()
__starting_point()
``` | vfc_18074 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/818/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3\n4\n6\n",
"output": "2\n3\n6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n",
"output": "0\n1\n2\n3\n4\n6\n7\n8\n10\n12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n212055293\n",
"output": "424069398\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n508427854\n",
"output": "1016791932\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n398561321\n",
"output": "797066176\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n322647200\n",
"output": "645243594\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2081 | Solve the following coding problem using the programming language python:
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.
For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0;
You have to determine the imbalance value of the array a.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 10^6) — size of the array a.
The second line contains n integers a_1, a_2... a_{n} (1 ≤ a_{i} ≤ 10^6) — elements of the array.
-----Output-----
Print one integer — the imbalance value of a.
-----Example-----
Input
3
1 4 1
Output
9
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#taken from https://stackoverflow.com/questions/30698441/optimal-way-to-find-sums-of-all-contiguous-sub-arrays-max-difference
def max_sums(d):
stack = [(-1, float('inf'))]
sum_ = 0
for i, x in enumerate(d):
while x > stack[-1][1]:
prev_i, prev_x = stack.pop()
prev_prev_i, prev_prev_x = stack[-1]
sum_ += prev_x * (i - prev_i) * (prev_i - prev_prev_i)
stack.append((i, x))
while len(stack) > 1:
prev_i, prev_x = stack.pop()
prev_prev_i, prev_prev_x = stack[-1]
sum_ += prev_x * (len(d) - prev_i) * (prev_i - prev_prev_i)
return sum_
def max_differences_sum(d):
return max_sums(d) + max_sums([-x for x in d])
n=int(input())
l=list(map(int,input().split()))
print(max_differences_sum(l))
``` | vfc_18078 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/817/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 4 1\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1 1 1 1 1 1 1 1 1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 4 4 3 5 2 4 2 4 5\n",
"output": "123\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n9 6 8 5 5 2 8 9 2 2\n",
"output": "245\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "30\n4 5 2 2 5 2 3 4 3 3 2 1 3 4 4 5 3 3 1 5 2 3 5 4 5 4 4 3 5 2\n",
"output": "1480\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2085 | Solve the following coding problem using the programming language python:
Ridhiman challenged Ashish to find the maximum valued subsequence of an array $a$ of size $n$ consisting of positive integers.
The value of a non-empty subsequence of $k$ elements of $a$ is defined as $\sum 2^i$ over all integers $i \ge 0$ such that at least $\max(1, k - 2)$ elements of the subsequence have the $i$-th bit set in their binary representation (value $x$ has the $i$-th bit set in its binary representation if $\lfloor \frac{x}{2^i} \rfloor \mod 2$ is equal to $1$).
Recall that $b$ is a subsequence of $a$, if $b$ can be obtained by deleting some(possibly zero) elements from $a$.
Help Ashish find the maximum value he can get by choosing some subsequence of $a$.
-----Input-----
The first line of the input consists of a single integer $n$ $(1 \le n \le 500)$ — the size of $a$.
The next line consists of $n$ space-separated integers — the elements of the array $(1 \le a_i \le 10^{18})$.
-----Output-----
Print a single integer — the maximum value Ashish can get by choosing some subsequence of $a$.
-----Examples-----
Input
3
2 1 3
Output
3
Input
3
3 1 4
Output
7
Input
1
1
Output
1
Input
4
7 7 1 1
Output
7
-----Note-----
For the first test case, Ashish can pick the subsequence $\{{2, 3}\}$ of size $2$. The binary representation of $2$ is 10 and that of $3$ is 11. Since $\max(k - 2, 1)$ is equal to $1$, the value of the subsequence is $2^0 + 2^1$ (both $2$ and $3$ have $1$-st bit set in their binary representation and $3$ has $0$-th bit set in its binary representation). Note that he could also pick the subsequence $\{{3\}}$ or $\{{2, 1, 3\}}$.
For the second test case, Ashish can pick the subsequence $\{{3, 4\}}$ with value $7$.
For the third test case, Ashish can pick the subsequence $\{{1\}}$ with value $1$.
For the fourth test case, Ashish can pick the subsequence $\{{7, 7\}}$ with value $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())
l = list(map(int, input().split()))
best = 0
for i in range(n):
for j in range(i, n):
for k in range(j, n):
best = max(best, l[i] | l[j] | l[k])
print(best)
``` | vfc_18094 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1365/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 1 3\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3 1 4\n",
"output": "7",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n7 7 1 1\n",
"output": "7",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2086 | Solve the following coding problem using the programming language python:
In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.
Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are a_{i} people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.
Help platform select such an hour, that the number of people who will participate in the contest is maximum.
-----Input-----
The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of hours in day.
The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10 000), where a_{i} is the number of people in the i-th timezone who want to participate in the contest.
The third line contains two space-separated integers s and f (1 ≤ s < f ≤ n).
-----Output-----
Output a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.
-----Examples-----
Input
3
1 2 3
1 3
Output
3
Input
5
1 2 3 4 1
1 3
Output
4
-----Note-----
In the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate.
In second example only people from the third and the fourth timezones will participate.
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(i) for i in input().split()]
s, f = [int(i) for i in input().split()]
a = a + a
ln = f - s
ans = sum(a[:ln])
mx = ans
h = s
for i in range(n - 1):
ans = ans - a[i] + a[i + ln]
if ans > mx:
ans = mx
k = s + (n - (i + 2) + 1)
if k > n:
k -= n
h = k
elif ans == mx:
k = s + (n - (i + 2) + 1)
if k > n:
k -= n
h = min(h, k)
print(h)
``` | vfc_18098 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/939/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 3\n1 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 2 3 4 1\n1 3\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2088 | Solve the following coding problem using the programming language python:
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $1$ to $n$, the junction $1$ is called the root.
A subtree of a junction $v$ is a set of junctions $u$ such that the path from $u$ to the root must pass through $v$. Note that $v$ itself is included in a subtree of $v$.
A leaf is such a junction that its subtree contains exactly one junction.
The New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction $t$ that all light bulbs in the subtree of $t$ have different colors.
Arkady is interested in the following question: for each $k$ from $1$ to $n$, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to $k$?
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of junctions in the tree.
The second line contains $n - 1$ integers $p_2$, $p_3$, ..., $p_n$ ($1 \le p_i < i$), where $p_i$ means there is a branch between junctions $i$ and $p_i$. It is guaranteed that this set of branches forms a tree.
-----Output-----
Output $n$ integers. The $i$-th of them should be the minimum number of colors needed to make the number of happy junctions be at least $i$.
-----Examples-----
Input
3
1 1
Output
1 1 2
Input
5
1 1 3 3
Output
1 1 1 2 3
-----Note-----
In the first example for $k = 1$ and $k = 2$ we can use only one color: the junctions $2$ and $3$ will be happy. For $k = 3$ you have to put the bulbs of different colors to make all the junctions happy.
In the second example for $k = 4$ you can, for example, put the bulbs of color $1$ in junctions $2$ and $4$, and a bulb of color $2$ into junction $5$. The happy junctions are the ones with indices $2$, $3$, $4$ and $5$ then.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# encoding:UTF-8
# Filename:Base.py
import sys
import random
import copy
from itertools import permutations, combinations
from math import sqrt, fabs, ceil
from collections import namedtuple
# ------Util Const--------
in_file_path = "input.txt"
output_file_path = "output.txt"
SUBMIT = True
def get_array(x, initial=None):
dimension = len(x)
if dimension == 1:
return [copy.deepcopy(initial) for _ in range(x[0])]
else:
return [get_array(x[1:], initial) for _ in range(x[0])]
def read_num(fin, num_type=int):
tmp_list = [num_type(x) for x in fin.readline().strip().split()]
if len(tmp_list) == 1:
return tmp_list[0]
else:
return tuple(tmp_list)
def read_num_list(fin, num_type=int):
return [num_type(x) for x in fin.readline().strip().split()]
# def solve(fin):
# n = read_num(fin)
# ans_set = None
# for i in range(n):
# tmp_list = read_num_list(fin)
# if ans_set == None:
# ans_set = set(tmp_list[1:])
# else:
# ans_set &= set(tmp_list[1:])
#
# print(' '.join([str(x) for x in ans_set]))
# def solve(fin):
# n, m = read_num(fin)
# a = [0] * m
# b = [0] * int(sqrt(n))
# for i in range(1, n + 1):
# a[i * i % m] += 1
#
# ans = 0
# for x in range(m):
# y = (m - x) % m
# ans += a[x] * a[y]
# print(ans)
# def BFS_count(x, chs, count):
# q = []
# q.append(x)
# while (q)
# return count[x]
def solve(fin):
n = read_num(fin)
f = read_num_list(fin)
new_f = [0] + f
for i in range(0, n):
new_f[i] -= 1
f = new_f
# print(f)
chs = get_array([n], [])
for i, p in enumerate(f):
if p >= 0:
chs[p].append(i)
# print(chs)
q = [x for x in range(0, n) if not chs[x]]
vis = [0] * n
count = [0] * n
while q:
x = q.pop(0)
if not chs[x]:
count[x] = 1
if f[x] >= 0:
vis[f[x]] += 1
# print(vis[f[x]], len(chs[f[x]]))
if vis[f[x]] == len(chs[f[x]]):
q.append(f[x])
count[f[x]] += count[x]
# print(chs)
count = sorted(count)
print(' '.join([str(x) for x in count]))
def __starting_point():
if SUBMIT:
solve(sys.stdin)
else:
solve(open(in_file_path, 'r'))
__starting_point()
``` | vfc_18106 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1056/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 1\n",
"output": "1 1 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 1 3 3\n",
"output": "1 1 1 2 3 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2090 | Solve the following coding problem using the programming language python:
You have a playlist consisting of $n$ songs. The $i$-th song is characterized by two numbers $t_i$ and $b_i$ — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of $3$ songs having lengths $[5, 7, 4]$ and beauty values $[11, 14, 6]$ is equal to $(5 + 7 + 4) \cdot 6 = 96$.
You need to choose at most $k$ songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 3 \cdot 10^5$) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next $n$ lines contains two integers $t_i$ and $b_i$ ($1 \le t_i, b_i \le 10^6$) — the length and beauty of $i$-th song.
-----Output-----
Print one integer — the maximum pleasure you can get.
-----Examples-----
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
-----Note-----
In the first test case we can choose songs ${1, 3, 4}$, so the total pleasure is $(4 + 3 + 6) \cdot 6 = 78$.
In the second test case we can choose song $3$. The total pleasure will be equal to $100 \cdot 100 = 10000$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import heapq
n,k=list(map(int,input().split()))
S=[list(map(int,input().split())) for i in range(n)]
S.sort(key=lambda x:x[1],reverse=True)
ANS=0
LENGTH=0
H=[]
for x,y in S:
heapq.heappush(H,x)
LENGTH+=x
if len(H)>k:
z=heapq.heappop(H)
LENGTH-=z
if ANS<LENGTH*y:
ANS=LENGTH*y
print(ANS)
``` | vfc_18114 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1140/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n4 7\n15 1\n3 6\n6 8\n",
"output": "78\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2091 | Solve the following coding problem using the programming language python:
This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string $s$, consisting of lowercase English letters. Find the longest string, $t$, which satisfies the following conditions: The length of $t$ does not exceed the length of $s$. $t$ is a palindrome. There exists two strings $a$ and $b$ (possibly empty), such that $t = a + b$ ( "$+$" represents concatenation), and $a$ is prefix of $s$ while $b$ is suffix of $s$.
-----Input-----
The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 10^5$), the number of test cases. The next $t$ lines each describe a test case.
Each test case is a non-empty string $s$, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed $10^6$.
-----Output-----
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
-----Example-----
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
-----Note-----
In the first test, the string $s = $"a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because: Its length is $9$, which does not exceed the length of the string $s$, which equals $11$. It is a palindrome. "abcdfdcba" $=$ "abcdfdc" $+$ "ba", and "abcdfdc" is a prefix of $s$ while "ba" is a suffix of $s$.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" $=$ "c" $+$ "" and $a$ or $b$ can be empty. The other possible solution for this test is "s".
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
# 偶数長含めた回文の長さを求める
# R[2*i] = L: S[i]を中心とする奇数長の最大回文
# R[2*i+1] = L: S[i:i+2]を中心とする偶数長の最大回文
# ダミー文字を挟むが、各 R[i] は実際の回文の文字列長と一致する
def manacher(S):
C = []
for a in S:
C.append(a)
C.append(0)
C.pop()
L = len(C)
R = [0] * L
i = j = 0
while i < L:
while j <= i < L - j and C[i - j] == C[i + j]:
j += 1
R[i] = j
k = 1
while j - R[i - k] > k <= i < L - k:
R[i + k] = R[i - k]
k += 1
i += k
j -= k
return R
for _ in range(int(input())):
S = input().rstrip('\n')
N = len(S)
if N == 1:
print(S)
continue
ii = -1
for i in range(N//2):
if S[i] != S[N-1-i]:
break
ii = i
if ii >= 0:
ss = S[:ii+1]
S = S[ii+1:N-ii-1]
else:
ss = ''
N = len(S)
if N == 0:
print(''.join([ss, ss[::-1]]))
continue
R = manacher(S)
M = 0
iii = 0
for i in range(N):
if R[i*2] > M:
if R[i*2]%2 == 0:
continue
k = R[i*2] // 2
if i-k == 0 or i+k == N-1:
M = R[i*2]
iii = i
for i in range(N-1):
if R[i*2+1] > M:
if R[i*2+1]%2 == 1:
continue
k = R[i*2+1] // 2
if i-k+1 == 0 or i+k == N-1:
M = R[i*2+1]
iii = i
if M & 1:
ans = S[iii - M//2: iii + M // 2 + 1]
else:
ans = S[iii - M // 2 + 1: iii + M // 2 + 1]
print(''.join([ss, ans, ss[::-1]]))
#print(S, R, iii, M)
def __starting_point():
main()
__starting_point()
``` | vfc_18118 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1326/D2",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\na\nabcdfdcecba\nabbaxyzyx\ncodeforces\nacbba\n",
"output": "a\nabcdfdcba\nxyzyx\nc\nabba\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2092 | Solve the following coding problem using the programming language python:
You are playing a computer game, where you lead a party of $m$ soldiers. Each soldier is characterised by his agility $a_i$.
The level you are trying to get through can be represented as a straight line segment from point $0$ (where you and your squad is initially located) to point $n + 1$ (where the boss is located).
The level is filled with $k$ traps. Each trap is represented by three numbers $l_i$, $r_i$ and $d_i$. $l_i$ is the location of the trap, and $d_i$ is the danger level of the trap: whenever a soldier with agility lower than $d_i$ steps on a trap (that is, moves to the point $l_i$), he gets instantly killed. Fortunately, you can disarm traps: if you move to the point $r_i$, you disarm this trap, and it no longer poses any danger to your soldiers. Traps don't affect you, only your soldiers.
You have $t$ seconds to complete the level — that is, to bring some soldiers from your squad to the boss. Before the level starts, you choose which soldiers will be coming with you, and which soldiers won't be. After that, you have to bring all of the chosen soldiers to the boss. To do so, you may perform the following actions:
if your location is $x$, you may move to $x + 1$ or $x - 1$. This action consumes one second; if your location is $x$ and the location of your squad is $x$, you may move to $x + 1$ or to $x - 1$ with your squad in one second. You may not perform this action if it puts some soldier in danger (i. e. the point your squad is moving into contains a non-disarmed trap with $d_i$ greater than agility of some soldier from the squad). This action consumes one second; if your location is $x$ and there is a trap $i$ with $r_i = x$, you may disarm this trap. This action is done instantly (it consumes no time).
Note that after each action both your coordinate and the coordinate of your squad should be integers.
You have to choose the maximum number of soldiers such that they all can be brought from the point $0$ to the point $n + 1$ (where the boss waits) in no more than $t$ seconds.
-----Input-----
The first line contains four integers $m$, $n$, $k$ and $t$ ($1 \le m, n, k, t \le 2 \cdot 10^5$, $n < t$) — the number of soldiers, the number of integer points between the squad and the boss, the number of traps and the maximum number of seconds you may spend to bring the squad to the boss, respectively.
The second line contains $m$ integers $a_1$, $a_2$, ..., $a_m$ ($1 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the agility of the $i$-th soldier.
Then $k$ lines follow, containing the descriptions of traps. Each line contains three numbers $l_i$, $r_i$ and $d_i$ ($1 \le l_i \le r_i \le n$, $1 \le d_i \le 2 \cdot 10^5$) — the location of the trap, the location where the trap can be disarmed, and its danger level, respectively.
-----Output-----
Print one integer — the maximum number of soldiers you may choose so that you may bring them all to the boss in no more than $t$ seconds.
-----Example-----
Input
5 6 4 14
1 2 3 4 5
1 5 2
1 2 5
2 3 5
3 5 3
Output
3
-----Note-----
In the first example you may take soldiers with agility $3$, $4$ and $5$ with you. The course of action is as follows:
go to $2$ without your squad; disarm the trap $2$; go to $3$ without your squad; disartm the trap $3$; go to $0$ without your squad; go to $7$ with your squad.
The whole plan can be executed in $13$ seconds.
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,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
M,N,K,T = inpl()
AA = inpl()
DD_di = []
LR = []
for i in range(K):
L,R,D = inpl()
LR.append((L,R))
DD_di.append((D,i))
DD_di.sort()
DD_d = [D for D,i in DD_di]
def solve(x):
idx = bisect.bisect_right(DD_d, x)
path = [0]*(N+2)
for D,i in DD_di[idx:]:
L,R = LR[i]
path[L] += 1
path[R+1] -= 1
t = N+1
bp = path[0]
for i in range(1,N+2):
p = bp + path[i]
if p > 0:
t += 2
bp = p
return t <= T
OK = (10**5) * 2 + 10
NG = -1
while OK-NG > 1:
mid = (OK+NG)//2
if solve(mid):
OK = mid
else:
NG = mid
ans = 0
for A in AA:
if A >= OK:
ans += 1
print(ans)
``` | vfc_18122 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1260/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 6 4 14\n1 2 3 4 5\n1 5 2\n1 2 5\n2 3 5\n3 5 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 5 3\n5 2 10\n1 2 3\n1 1 9\n1 1 2\n2 2 4\n1 2 9\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1 4\n2\n1 1 5\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2093 | Solve the following coding problem using the programming language python:
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.
TV series have n seasons (numbered 1 through n), the i-th season has a_{i} episodes (numbered 1 through a_{i}). Polycarp thinks that if for some pair of integers x and y (x < y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 2·10^5) — the number of seasons.
The second line contains n integers separated by space a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — number of episodes in each season.
-----Output-----
Print one integer — the number of pairs x and y (x < y) such that there exist both season x episode y and season y episode x.
-----Examples-----
Input
5
1 2 3 4 5
Output
0
Input
3
8 12 7
Output
3
Input
3
3 2 1
Output
2
-----Note-----
Possible pairs in the second example: x = 1, y = 2 (season 1 episode 2 [Image] season 2 episode 1); x = 2, y = 3 (season 2 episode 3 [Image] season 3 episode 2); x = 1, y = 3 (season 1 episode 3 [Image] season 3 episode 1).
In the third example: x = 1, y = 2 (season 1 episode 2 [Image] season 2 episode 1); x = 1, y = 3 (season 1 episode 3 [Image] season 3 episode 1).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
class RangeBit:
def __init__(self, n):
sz = 1
while n >= sz:
sz *= 2
self.size = sz
self.dataAdd = [0 for _ in range(sz)]
self.dataMul = [0 for _ in range(sz)]
def sum(self, i):
assert i > 0
add, mul, start = 0, 0, i
while i > 0:
add += self.dataAdd[i]
mul += self.dataMul[i]
i -= i & -i
return mul * start + add
def add(self, left, right, by):
assert 0 < left <= right
self._add(left, by, -by * (left - 1))
self._add(right, -by, by * right)
def _add(self, i, mul, add):
assert i > 0
while i < self.size:
self.dataAdd[i] += add
self.dataMul[i] += mul
i += i & -i
n = int(input())
l = list(map(int, sys.stdin.readline().split()))
queries = []
for i in range(n):
if min(l[i], n) >= i+2:
queries.append((i+2, min(l[i], n), i+1))
result = 0
a = sorted(list(zip(list(range(1, n+1)), l)) + queries, key=lambda x:(-x[-1], len(x)))
ft = RangeBit(n+1)
for el in a:
#print(el)
if len(el) == 2: #update
ind, val = el
ft.add(ind, ind, 1)
else: #query
fr, to, val = el
# print(fr, to, val)
# print(ft.sum(to) - (ft.sum(fr - 1) if fr > 1 else 0))
result += ft.sum(to) - (ft.sum(fr - 1) if fr > 1 else 0)
print(result)
``` | vfc_18126 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/961/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 3 4 5\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n8 12 7\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3 2 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n2 3 4 5 6\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n7 2 6 6 5 1 4 9\n",
"output": "9\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2094 | Solve the following coding problem using the programming language python:
Your program fails again. This time it gets "Wrong answer on test 233".
This is the harder version of the problem. In this version, $1 \le n \le 2\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
The problem is to finish $n$ one-choice-questions. Each of the questions contains $k$ options, and only one of them is correct. The answer to the $i$-th question is $h_{i}$, and if your answer of the question $i$ is $h_{i}$, you earn $1$ point, otherwise, you earn $0$ points for this question. The values $h_1, h_2, \dots, h_n$ are known to you in this problem.
However, you have a mistake in your program. It moves the answer clockwise! Consider all the $n$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.
Formally, the mistake moves the answer for the question $i$ to the question $i \bmod n + 1$. So it moves the answer for the question $1$ to question $2$, the answer for the question $2$ to the question $3$, ..., the answer for the question $n$ to the question $1$.
We call all the $n$ answers together an answer suit. There are $k^n$ possible answer suits in total.
You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $1$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $998\,244\,353$.
For example, if $n = 5$, and your answer suit is $a=[1,2,3,4,5]$, it will submitted as $a'=[5,1,2,3,4]$ because of a mistake. If the correct answer suit is $h=[5,2,2,3,4]$, the answer suit $a$ earns $1$ point and the answer suite $a'$ earns $4$ points. Since $4 > 1$, the answer suit $a=[1,2,3,4,5]$ should be counted.
-----Input-----
The first line contains two integers $n$, $k$ ($1 \le n \le 2\cdot10^5$, $1 \le k \le 10^9$) — the number of questions and the number of possible answers to each question.
The following line contains $n$ integers $h_1, h_2, \dots, h_n$, ($1 \le h_{i} \le k)$ — answers to the questions.
-----Output-----
Output one integer: the number of answers suits satisfying the given condition, modulo $998\,244\,353$.
-----Examples-----
Input
3 3
1 3 1
Output
9
Input
5 5
1 1 4 2 2
Output
1000
Input
6 2
1 1 2 2 1 1
Output
16
-----Note-----
For the first example, valid answer suits are $[2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3]$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
M=998244353
class Factorial:
def __init__(self,n):
self.f=f=[0]*(n+1)
f[0]=b=1
for i in range(1,n+1):f[i]=b=b*i%M
self.inv=inv=[0]*(n+1)
inv[n]=b=pow(self.f[n],M-2,M)
for i in range(n,0,-1):inv[i-1]=b=b*i%M
def factorial(self,i):
return self.f[i]
def ifactorial(self,i):
return self.inv[i]
def comb(self,n,k):
if n>=k:return self.f[n]*self.inv[n-k]*self.inv[k]%M
else:return 0
def main():
n,k,*h=map(int,open(0).read().split())
m=sum(i!=j for i,j in zip(h,h[1:]+h[:1]))
comb=Factorial(m).comb
print((pow(k,m,M)-sum(comb(m,i)*comb(m-i,i)*pow(k-2,m-i-i,M)for i in range(m//2+1)))*pow(k,n-m,M)*pow(2,M-2,M)%M)
main()
``` | vfc_18130 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1227/F2",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3\n1 3 1\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n1 1 4 2 2\n",
"output": "1000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 2\n1 1 2 2 1 1\n",
"output": "16\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15 10\n1 5 5 6 2 4 9 7 2 4 8 7 8 8 9\n",
"output": "809573316\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 100\n82 51 81 14 37 17 78 92 64 15 8 86 89 8 87 77 66 10 15 12 100 25 92 47 21 78 20 63 13 49 41 36 41 79 16 87 87 69 3 76 80 60 100 49 70 59 72 8 38 71 45 97 71 14 76 54 81 4 59 46 39 29 92 3 49 22 53 99 59 52 74 31 92 43 42 23 44 9 82 47 7 40 12 9 3 55 37 85 46 22 84 52 98 41 21 77 63 17 62 91\n",
"output": "490987641\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 100000\n48997 48997 22146 22146 22146 22146 22146 22146 22146 48997\n",
"output": "921332324\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2095 | Solve the following coding problem using the programming language python:
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.
There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n × n matrix А: there is a number on the intersection of the і-th row and j-th column that describes the result of the collision of the і-th and the j-th car: - 1: if this pair of cars never collided. - 1 occurs only on the main diagonal of the matrix. 0: if no car turned over during the collision. 1: if only the i-th car turned over during the collision. 2: if only the j-th car turned over during the collision. 3: if both cars turned over during the collision.
Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100) — the number of cars.
Each of the next n lines contains n space-separated integers that determine matrix A.
It is guaranteed that on the main diagonal there are - 1, and - 1 doesn't appear anywhere else in the matrix.
It is guaranteed that the input is correct, that is, if A_{ij} = 1, then A_{ji} = 2, if A_{ij} = 3, then A_{ji} = 3, and if A_{ij} = 0, then A_{ji} = 0.
-----Output-----
Print the number of good cars and in the next line print their space-separated indices in the increasing order.
-----Examples-----
Input
3
-1 0 0
0 -1 1
0 2 -1
Output
2
1 3
Input
4
-1 3 3 3
3 -1 3 3
3 3 -1 3
3 3 3 -1
Output
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = [list(map(int, input().split())) for i in range(n)]
res = []
for i in range(n):
j = 0
while j < n and 3 != a[i][j] != 1:
j += 1
if j == n: res.append(i + 1)
print(len(res))
print(' '.join(map(str, res)))
``` | vfc_18134 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/545/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n-1 0 0\n0 -1 1\n0 2 -1\n",
"output": "2\n1 3 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2096 | Solve the following coding problem using the programming language python:
Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap.
Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer — the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.
Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100). The second line contains 2·n space-separated integers a_{i} (10 ≤ a_{i} ≤ 99), denoting the numbers on the cubes.
-----Output-----
In the first line print a single number — the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2·n numbers b_{i} (1 ≤ b_{i} ≤ 2). The numbers mean: the i-th cube belongs to the b_{i}-th heap in your division.
If there are multiple optimal ways to split the cubes into the heaps, print any of them.
-----Examples-----
Input
1
10 99
Output
1
2 1
Input
2
13 24 13 45
Output
4
1 2 2 1
-----Note-----
In the first test case Valera can put the first cube in the first heap, and second cube — in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.
In the second test case Valera can obtain numbers 1313, 1345, 2413, 2445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(map(int, input().split()))
g = [[] for i in range(100)]
for i in range(2 * n):
g[a[i]].append(i)
x = [0, 0]
cur = 1
mus = []
ans = [0] * 2 * n
for i in range(10, 100):
if len(g[i]) == 1:
ans[g[i][0]] = cur
x[cur - 1] += 1
cur = 3 - cur
if len(g[i]) >= 2:
ans[g[i][0]] = 1
ans[g[i][1]] = 2
x[0] += 1
x[1] += 1
for j in range(2, len(g[i])):
mus.append(g[i][j])
for i in range(len(mus)):
ans[mus[i]] = 2 - (i % 2)
print(x[0] * x[1])
print(*ans)
``` | vfc_18138 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/353/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n10 99\n",
"output": "1\n2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n13 24 13 45\n",
"output": "4\n1 2 2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n21 60 18 21 17 39 58 74 62 34\n",
"output": "25\n1 1 1 2 2 1 2 1 2 2 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2097 | Solve the following coding problem using the programming language python:
Guy-Manuel and Thomas have an array $a$ of $n$ integers [$a_1, a_2, \dots, a_n$]. In one step they can add $1$ to any element of the array. Formally, in one step they can choose any integer index $i$ ($1 \le i \le n$) and do $a_i := a_i + 1$.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.
What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $a_1 + a_2 +$ $\dots$ $+ a_n \ne 0$ and $a_1 \cdot a_2 \cdot$ $\dots$ $\cdot a_n \ne 0$.
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10^3$). The description of the test cases follows.
The first line of each test case contains an integer $n$ ($1 \le n \le 100$) — the size of the array.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-100 \le a_i \le 100$) — elements of the array .
-----Output-----
For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.
-----Example-----
Input
4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
Output
1
2
0
2
-----Note-----
In the first test case, the sum is $0$. If we add $1$ to the first element, the array will be $[3,-1,-1]$, the sum will be equal to $1$ and the product will be equal to $3$.
In the second test case, both product and sum are $0$. If we add $1$ to the second and the third element, the array will be $[-1,1,1,1]$, the sum will be equal to $2$ and the product will be equal to $-1$. It can be shown that fewer steps can't be enough.
In the third test case, both sum and product are non-zero, we don't need to do anything.
In the fourth test case, after adding $1$ twice to the first element the array will be $[2,-2,1]$, the sum will be $1$ and the product will be $-4$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
import math
import heapq
import bisect
import re
from collections import deque
from decimal import *
from fractions import gcd
def YES_NO(flag):
if flag:
print("AWW")
else:
print("WAW")
def main():
# q = [int(i) for i in sys.stdin.readline().split()]
n = int(sys.stdin.readline())
q = [int(i) for i in sys.stdin.readline().split()]
w = q.count(0)
if w + sum(q) == 0:
print(w + 1)
else:
print(w)
for i in range(int(sys.stdin.readline())):
main()
``` | vfc_18142 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1300/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1\n",
"output": "1\n2\n0\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n100\n64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2098 | Solve the following coding problem using the programming language python:
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $1$ to $n$. For every edge $e$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $e$ (and only this edge) is erased from the tree.
Monocarp has given you a list of $n - 1$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 1\,000$) — the number of vertices in the tree.
Each of the next $n-1$ lines contains two integers $a_i$ and $b_i$ each ($1 \le a_i < b_i \le n$) — the maximal indices of vertices in the components formed if the $i$-th edge is removed.
-----Output-----
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $n - 1$ lines. Each of the last $n - 1$ lines should contain two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$) — vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
-----Examples-----
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
-----Note-----
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs. [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from copy import deepcopy
import itertools
from bisect import bisect_left
from bisect import bisect_right
import math
from collections import deque
from collections import Counter
def read():
return int(input())
def readmap():
return map(int, input().split())
def readlist():
return list(map(int, input().split()))
n = read()
V = []
for _ in range(n-1):
a, b = readmap()
V.append(a)
if b < n:
print("NO")
quit()
V.sort()
for i in range(n-1):
if V[i] <= i:
print("NO")
quit()
used = [False] * (n+1)
tree = []
for i in range(n-1):
v = V[i]
if not used[v]:
tree.append(v)
used[v] = True
else:
for j in range(1, n+1):
if not used[j]:
tree.append(j)
used[j] = True
break
tree.append(n)
print("YES")
for i in range(n-1):
print(tree[i], tree[i+1])
``` | vfc_18146 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1041/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n3 4\n1 4\n3 4\n",
"output": "YES\n1 3\n3 2\n2 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 3\n1 3\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2099 | Solve the following coding problem using the programming language python:
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that: the number of different users online did not exceed M at any moment, at some second the number of distinct users online reached value M, the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
-----Input-----
The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
-----Output-----
In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
-----Examples-----
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
-----Note-----
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(1,1+n):
g = gets()
a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
[p,count,sim] = [1,0,0]
is_solution_there=False
for i in range(1,n+1):
while p<i and a[i] - t + 1>a[p]:
p+=1
if b[p]!=b[p-1]:
sim = max(sim-1,0)
if a[i]<a[p]+t and sim<m:
count+=1
sim+=1
if sim==m:
is_solution_there=True
b[i] = count
if is_solution_there==False:
print("No solution")
return
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
def __starting_point():
main()
__starting_point()
``` | vfc_18150 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/524/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2 10\n17:05:53\n17:05:58\n17:06:01\n22:39:47\n",
"output": "3\n1\n2\n2\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2 86400\n00:00:00\n",
"output": "No solution\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2100 | Solve the following coding problem using the programming language python:
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds t.
-----Input-----
The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 10^4). Then follow n lines, each containing two integers l_{i} and r_{i} (0 ≤ l_{i}, r_{i} ≤ 1). Number l_{i} equals one, if the left door of the i-th cupboard is opened, otherwise number l_{i} equals zero. Similarly, number r_{i} equals one, if the right door of the i-th cupboard is opened, otherwise number r_{i} equals zero.
The numbers in the lines are separated by single spaces.
-----Output-----
In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
-----Examples-----
Input
5
0 1
1 0
0 1
1 1
0 1
Output
3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n=int(input())
R=[]
L=[]
for i in range(n):
x,y=input().split()
R.append(x)
L.append(y)
a=R.count("0")
b=L.count("0")
answer=min(a,n-a)+min(b,n-b)
print(answer)
``` | vfc_18154 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/248/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n0 1\n1 0\n0 1\n1 1\n0 1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n0 0\n0 0\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n0 1\n1 1\n1 1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2101 | Solve the following coding problem using the programming language python:
You are given three multisets of pairs of colored sticks: $R$ pairs of red sticks, the first pair has length $r_1$, the second pair has length $r_2$, $\dots$, the $R$-th pair has length $r_R$; $G$ pairs of green sticks, the first pair has length $g_1$, the second pair has length $g_2$, $\dots$, the $G$-th pair has length $g_G$; $B$ pairs of blue sticks, the first pair has length $b_1$, the second pair has length $b_2$, $\dots$, the $B$-th pair has length $b_B$;
You are constructing rectangles from these pairs of sticks with the following process: take a pair of sticks of one color; take a pair of sticks of another color different from the first one; add the area of the resulting rectangle to the total area.
Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.
Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.
What is the maximum area you can achieve?
-----Input-----
The first line contains three integers $R$, $G$, $B$ ($1 \le R, G, B \le 200$) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks.
The second line contains $R$ integers $r_1, r_2, \dots, r_R$ ($1 \le r_i \le 2000$) — the lengths of sticks in each pair of red sticks.
The third line contains $G$ integers $g_1, g_2, \dots, g_G$ ($1 \le g_i \le 2000$) — the lengths of sticks in each pair of green sticks.
The fourth line contains $B$ integers $b_1, b_2, \dots, b_B$ ($1 \le b_i \le 2000$) — the lengths of sticks in each pair of blue sticks.
-----Output-----
Print the maximum possible total area of the constructed rectangles.
-----Examples-----
Input
1 1 1
3
5
4
Output
20
Input
2 1 3
9 5
1
2 8 5
Output
99
Input
10 1 1
11 7 20 15 19 14 2 4 13 14
8
11
Output
372
-----Note-----
In the first example you can construct one of these rectangles: red and green with sides $3$ and $5$, red and blue with sides $3$ and $4$ and green and blue with sides $5$ and $4$. The best area of them is $4 \times 5 = 20$.
In the second example the best rectangles are: red/blue $9 \times 8$, red/blue $5 \times 5$, green/blue $2 \times 1$. So the total area is $72 + 25 + 2 = 99$.
In the third example the best rectangles are: red/green $19 \times 8$ and red/blue $20 \times 11$. The total area is $152 + 220 = 372$. Note that you can't construct more rectangles because you are not allowed to have both pairs taken to be the same color.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m, q = map(int, input().split())
a = sorted(map(int, input().split()), reverse=True)
b = sorted(map(int, input().split()), reverse=True)
c = sorted(map(int, input().split()), reverse=True)
dp = [[[0] * 201 for _ in range(201)] for _ in range(201)]
for ijk in range(n + m + q + 1):
for i in range(min(n + 1, ijk + 1)):
for j in range(min(m + 1, ijk - i + 1)):
k = ijk - i - j
if k < 0 or k > q:
continue
if i + 1 <= n:
dp[i + 1][j][k] = max(dp[i + 1][j][k], dp[i][j][k])
if j + 1 <= m:
dp[i][j + 1][k] = max(dp[i][j + 1][k], dp[i][j][k])
if k + 1 <= q:
dp[i][j][k + 1] = max(dp[i][j][k + 1], dp[i][j][k])
if i + 1 <= n and j + 1 <= m:
dp[i + 1][j + 1][k] = max(dp[i + 1][j + 1][k], dp[i][j][k] + a[i] * b[j])
if i + 1 <= n and k + 1 <= q:
dp[i + 1][j][k + 1] = max(dp[i + 1][j][k + 1], dp[i][j][k] + a[i] * c[k])
if j + 1 <= m and k + 1 <= q:
dp[i][j + 1][k + 1] = max(dp[i][j + 1][k + 1], dp[i][j][k] + b[j] * c[k])
print(dp[n][m][q])
``` | vfc_18158 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1398/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 1 1\n3\n5\n4\n",
"output": "20\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1 3\n9 5\n1\n2 8 5\n",
"output": "99\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 1 1\n11 7 20 15 19 14 2 4 13 14\n8\n11\n",
"output": "372\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2 2\n3 10\n6 9\n10 9\n",
"output": "199\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 3 6\n2\n8 6 7\n5 2 4 1 10 4\n",
"output": "147\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2102 | Solve the following coding problem using the programming language python:
After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has $6$ strings and an infinite number of frets numbered from $1$. Fretting the fret number $j$ on the $i$-th string produces the note $a_{i} + j$.
Tayuya wants to play a melody of $n$ notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference.
For example, if $a = [1, 1, 2, 2, 3, 3]$, and the sequence of notes is $4, 11, 11, 12, 12, 13, 13$ (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be $10$, the minimal one will be $3$, and the answer is $10 - 3 = 7$, as shown on the picture. [Image]
-----Input-----
The first line contains $6$ space-separated numbers $a_{1}$, $a_{2}$, ..., $a_{6}$ ($1 \leq a_{i} \leq 10^{9}$) which describe the Tayuya's strings.
The second line contains the only integer $n$ ($1 \leq n \leq 100\,000$) standing for the number of notes in the melody.
The third line consists of $n$ integers $b_{1}$, $b_{2}$, ..., $b_{n}$ ($1 \leq b_{i} \leq 10^{9}$), separated by space. They describe the notes to be played. It's guaranteed that $b_i > a_j$ for all $1\leq i\leq n$ and $1\leq j\leq 6$, in other words, you can play each note on any string.
-----Output-----
Print the minimal possible difference of the maximal and the minimal indices of used frets.
-----Examples-----
Input
1 4 100 10 30 5
6
101 104 105 110 130 200
Output
0
Input
1 1 2 2 3 3
7
13 4 11 12 11 13 12
Output
7
-----Note-----
In the first sample test it is optimal to play the first note on the first string, the second note on the second string, the third note on the sixth string, the fourth note on the fourth string, the fifth note on the fifth string, and the sixth note on the third string. In this case the $100$-th fret is used each time, so the difference is $100 - 100 = 0$. [Image]
In the second test it's optimal, for example, to play the second note on the first string, and all the other notes on the sixth string. Then the maximal fret will be $10$, the minimal one will be $3$, and the answer is $10 - 3 = 7$. [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from sys import stdin
input = stdin.readline
a = sorted([int(i) for i in input().split()])
n = int(input())
b = sorted([int(i) for i in input().split()])
c = []
for i in range(n):
c += [[b[i] - a[j], i] for j in range(6)]
c.sort()
d = [0] * n
e = 0
ans = 10 ** 10
u = 0
for i in range(len(c)):
while u < len(c) and e < n:
x = c[u][1]
if d[x] == 0:
e += 1
d[x] += 1
u += 1
if e == n:
ans = min(ans, c[u - 1][0] - c[i][0])
x = c[i][1]
d[x] -= 1
if d[x] == 0:
e -= 1
print(ans)
``` | vfc_18162 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1413/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 4 100 10 30 5\n6\n101 104 105 110 130 200\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 2 2 3 3\n7\n13 4 11 12 11 13 12\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "58260522 77914575 2436426 24979445 61648772 23690081\n10\n582107247 906728404 411434947 673536177 411497300 488012525 561127307 800305059 992325267 112738006\n",
"output": "804109112\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11 16 12 20 12 13\n10\n21 21 21 21 21 21 21 21 21 21\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2103 | Solve the following coding problem using the programming language python:
Given an array $a$ of length $n$, find another array, $b$, of length $n$ such that:
for each $i$ $(1 \le i \le n)$ $MEX(\{b_1$, $b_2$, $\ldots$, $b_i\})=a_i$.
The $MEX$ of a set of integers is the smallest non-negative integer that doesn't belong to this set.
If such array doesn't exist, determine this.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 10^5$) — the length of the array $a$.
The second line contains $n$ integers $a_1$, $a_2$, $\ldots$, $a_n$ ($0 \le a_i \le i$) — the elements of the array $a$. It's guaranteed that $a_i \le a_{i+1}$ for $1\le i < n$.
-----Output-----
If there's no such array, print a single line containing $-1$.
Otherwise, print a single line containing $n$ integers $b_1$, $b_2$, $\ldots$, $b_n$ ($0 \le b_i \le 10^6$)
If there are multiple answers, print any.
-----Examples-----
Input
3
1 2 3
Output
0 1 2
Input
4
0 0 0 2
Output
1 3 4 0
Input
3
1 1 3
Output
0 2 1
-----Note-----
In the second test case, other answers like $[1,1,1,0]$, for example, are valid.
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()))
sa = set(a)
san = set()
min_not_in = 0
prev = 0
ans = [0] * n
for i in range(n):
cur = a[i]
if cur == prev:
while min_not_in in sa:
min_not_in += 1
ans[i] = min_not_in
sa.add(min_not_in)
san.add(min_not_in)
else:
ans[i] = prev
sa.add(prev)
san.add(prev)
while prev in san:
prev += 1
if cur != prev:
print(-1)
break
else:
print(*ans)
``` | vfc_18166 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1364/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "0 1 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n0 0 0 2\n",
"output": "1 3 4 0 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 1 3\n",
"output": "0 2 1 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2104 | Solve the following coding problem using the programming language python:
You are given a set of all integers from $l$ to $r$ inclusive, $l < r$, $(r - l + 1) \le 3 \cdot 10^5$ and $(r - l)$ is always odd.
You want to split these numbers into exactly $\frac{r - l + 1}{2}$ pairs in such a way that for each pair $(i, j)$ the greatest common divisor of $i$ and $j$ is equal to $1$. Each number should appear in exactly one of the pairs.
Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.
-----Input-----
The only line contains two integers $l$ and $r$ ($1 \le l < r \le 10^{18}$, $r - l + 1 \le 3 \cdot 10^5$, $(r - l)$ is odd).
-----Output-----
If any solution exists, print "YES" in the first line. Each of the next $\frac{r - l + 1}{2}$ lines should contain some pair of integers. GCD of numbers in each pair should be equal to $1$. All $(r - l + 1)$ numbers should be pairwise distinct and should have values from $l$ to $r$ inclusive.
If there are multiple solutions, print any of them.
If there exists no solution, print "NO".
-----Example-----
Input
1 8
Output
YES
2 7
4 1
3 8
6 5
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
l, r = list(map(int, input().split()))
print("YES")
for i in range(l, r + 1, 2):
print(i, i + 1)
``` | vfc_18170 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1051/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 8\n",
"output": "YES\n1 2\n3 4\n5 6\n7 8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\n",
"output": "YES\n1 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n",
"output": "YES\n2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 9\n",
"output": "YES\n4 5\n6 7\n8 9\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2105 | Solve the following coding problem using the programming language python:
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of $n$ strings $s_1, s_2, s_3, \ldots, s_{n}$ and $m$ strings $t_1, t_2, t_3, \ldots, t_{m}$. These strings contain only lowercase letters. There might be duplicates among these strings.
Let's call a concatenation of strings $x$ and $y$ as the string that is obtained by writing down strings $x$ and $y$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".
The year 1 has a name which is the concatenation of the two strings $s_1$ and $t_1$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.
For example, if $n = 3, m = 4, s = ${"a", "b", "c"}, $t =$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. [Image]
You are given two sequences of strings of size $n$ and $m$ and also $q$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?
-----Input-----
The first line contains two integers $n, m$ ($1 \le n, m \le 20$).
The next line contains $n$ strings $s_1, s_2, \ldots, s_{n}$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $1$ and at most $10$.
The next line contains $m$ strings $t_1, t_2, \ldots, t_{m}$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $1$ and at most $10$.
Among the given $n + m$ strings may be duplicates (that is, they are not necessarily all different).
The next line contains a single integer $q$ ($1 \le q \le 2\,020$).
In the next $q$ lines, an integer $y$ ($1 \le y \le 10^9$) is given, denoting the year we want to know the name for.
-----Output-----
Print $q$ lines. For each line, print the name of the year as per the rule described above.
-----Example-----
Input
10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
Output
sinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
-----Note-----
The first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
input = __import__('sys').stdin.readline
MIS = lambda: map(int,input().split())
n, m = MIS()
A = input().split()
B = input().split()
for TEST in range(int(input())):
y = int(input())-1
print(A[y%len(A)] + B[y%len(B)])
``` | vfc_18174 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1284/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020\n",
"output": "sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\na\na\n1\n1\n",
"output": "aa\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n1\n2016\n",
"output": "byeongsin\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\na b c d e\nhola mundo\n1\n5\n",
"output": "ehola\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4\na b c b\na b c b\n1\n3\n",
"output": "cc\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2106 | Solve the following coding problem using the programming language python:
There are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c_1, c_2, ..., c_{n}. The Old Peykan wants to travel from city c_1 to c_{n} using roads. There are (n - 1) one way roads, the i-th road goes from city c_{i} to city c_{i} + 1 and is d_{i} kilometers long.
The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.
Each city c_{i} (except for the last city c_{n}) has a supply of s_{i} liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly k hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times.
Initially (at time zero) the Old Peykan is at city c_1 and s_1 liters of fuel is transferred to it's empty tank from c_1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.
Find the minimum time the Old Peykan needs to reach city c_{n}.
-----Input-----
The first line of the input contains two space-separated integers m and k (1 ≤ m, k ≤ 1000). The value m specifies the number of roads between cities which is equal to n - 1.
The next line contains m space-separated integers d_1, d_2, ..., d_{m} (1 ≤ d_{i} ≤ 1000) and the following line contains m space-separated integers s_1, s_2, ..., s_{m} (1 ≤ s_{i} ≤ 1000).
-----Output-----
In the only line of the output print a single integer — the minimum time required for The Old Peykan to reach city c_{n} from city c_1.
-----Examples-----
Input
4 6
1 2 5 2
2 3 3 4
Output
10
Input
2 3
5 6
5 5
Output
14
-----Note-----
In the second sample above, the Old Peykan stays in c_1 for 3 hours.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = map(int, input().split())
l, a = list(map(int, input().split())), list(map(int, input().split()))
v, t, s = 0, 0, sum(l)
for i in range(n):
l[i] -= a[i]
L, A = [l[0]], [a[0]]
for i in range(1, n):
if a[i] <= A[-1]: L[-1] += l[i]
else:
A.append(a[i])
L.append(l[i])
for i in range(len(A)):
d = L[i] - v
if d > 0:
u = (d - 1) // A[i] + 1
v += u * A[i]
t += u * k
v -= L[i]
print(t + s)
``` | vfc_18178 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/241/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 6\n1 2 5 2\n2 3 3 4\n",
"output": "10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2107 | Solve the following coding problem using the programming language python:
Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret the guitar produces a note, let's denote it as a_{ij}. We know that Dima's guitar can produce k distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that a_{ij} = a_{pq} at (i, j) ≠ (p, q).
Dima has already written a song — a sequence of s notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein).
We'll represent a way to play a song as a sequence of pairs (x_{i}, y_{i}) (1 ≤ i ≤ s), such that the x_{i}-th string on the y_{i}-th fret produces the i-th note from the song. The complexity of moving between pairs (x_1, y_1) and (x_2, y_2) equals $|x_{1} - x_{2}|$ + $|y_{1} - y_{2}|$. The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs.
Help Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!
-----Input-----
The first line of the input contains four integers n, m, k and s (1 ≤ n, m ≤ 2000, 1 ≤ k ≤ 9, 2 ≤ s ≤ 10^5).
Then follow n lines, each containing m integers a_{ij} (1 ≤ a_{ij} ≤ k). The number in the i-th row and the j-th column (a_{ij}) means a note that the guitar produces on the i-th string and the j-th fret.
The last line of the input contains s integers q_{i} (1 ≤ q_{i} ≤ k) — the sequence of notes of the song.
-----Output-----
In a single line print a single number — the maximum possible complexity of the song.
-----Examples-----
Input
4 6 5 7
3 1 2 2 3 1
3 2 2 2 5 5
4 2 2 2 5 3
3 2 2 1 4 3
2 3 1 4 1 5 1
Output
8
Input
4 4 9 5
4 7 9 5
1 2 1 7
8 3 4 9
5 7 7 2
7 1 9 2 5
Output
4
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def solution() : # 最大的距离来自于角落附近的点
n,m,k,s = map(int, input().split())
dis = lambda a,b : abs(a[0] - b[0]) + abs(a[1] - b[1])
corner = [(0,0), (0,m-1), (n-1,0), (n-1,m-1)]
vertex = [[(n,m), (n,-1), (-1,m), (-1,-1)] for _ in range(k+1)]
for i in range(n) :
for j,note in enumerate(map(int, input().split())) :
vertex[note] = [
(i,j) if dis((i,j), c) < dis(v, c) else v
for v,c in zip(vertex[note], corner)]
maxdis = [[-1] * (k+1) for _ in range(k+1)]
pairs = [(0,3),(3,0),(1,2),(2,1)]
for i in range(1, k+1) :
for j in range(i, k+1) :
vi,vj = vertex[i],vertex[j]
maxdis[i][j] = max(dis(vi[a], vj[b]) for a,b in pairs)
maxdis[j][i] = maxdis[i][j]
s = list(map(int, input().split()))
print(max(maxdis[s[i]][s[i+1]] for i in range(len(s) - 1)))
solution()
``` | vfc_18182 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/366/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 6 5 7\n3 1 2 2 3 1\n3 2 2 2 5 5\n4 2 2 2 5 3\n3 2 2 1 4 3\n2 3 1 4 1 5 1\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4 9 5\n4 7 9 5\n1 2 1 7\n8 3 4 9\n5 7 7 2\n7 1 9 2 5\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5 2 2\n2 2 2 1 2\n2 1 2 2 2\n2 2 2 2 2\n1 2 2 2 2\n2 2 2 2 1\n1 1\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5 2 2\n2 1 2 2 2\n2 2 2 2 2\n2 2 2 2 1\n2 2 2 2 2\n1 2 2 2 2\n1 1\n",
"output": "6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2108 | Solve the following coding problem using the programming language python:
You are given an undirected graph without self-loops or multiple edges which consists of $n$ vertices and $m$ edges. Also you are given three integers $n_1$, $n_2$ and $n_3$.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $n_1$; The total number of vertices with label 2 should be equal to $n_2$; The total number of vertices with label 3 should be equal to $n_3$; $|col_u - col_v| = 1$ for each edge $(u, v)$, where $col_x$ is the label of vertex $x$.
If there are multiple valid labelings, print any of them.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n \le 5000$; $0 \le m \le 10^5$) — the number of vertices and edges in the graph.
The second line contains three integers $n_1$, $n_2$ and $n_3$ ($0 \le n_1, n_2, n_3 \le n$) — the number of labels 1, 2 and 3, respectively. It's guaranteed that $n_1 + n_2 + n_3 = n$.
Next $m$ lines contan description of edges: the $i$-th line contains two integers $u_i$, $v_i$ ($1 \le u_i, v_i \le n$; $u_i \neq v_i$) — the vertices the $i$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
-----Output-----
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $n$ consisting of 1, 2 and 3. The $i$-th letter should be equal to the label of the $i$-th vertex.
If there is no valid labeling, print "NO" (without quotes).
-----Examples-----
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output
NO
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,m=map(int,input().split())
x,y,z=map(int,input().split())
edge=[[]for _ in range(n)]
for _ in range(m):
a,b=map(int,input().split())
a-=1
b-=1
edge[a].append(b)
edge[b].append(a)
color=[0]*n
def bfs(v,c):
color[v]=c
h=w=0
if c==1:h=1
else:w=1
for i in edge[v]:
if color[i]==c:return [False,h,w]
elif color[i]==0:
f,hh,ww=bfs(i,-c)
h+=hh
w+=ww
if not f:return [False,h,w]
return [True,h,w]
q=[]
for i in range(n):
if color[i]==0:
f,h,w=bfs(i,1)
if not f:print("NO");return
q.append([i,min(h,w),max(h,w)-min(h,w),1-2*(h<w)])
yy=y
for _,i,__,___ in q:yy-=i
if yy<0:print("NO");return
dp=[(yy+1)*[0]for _ in range(len(q)+1)]
dp[0][0]=1
for i in range(len(q)):
_,__,ii,___=q[i]
for j in range(yy+1):dp[i+1][j]=dp[i][j]
for j in range(yy+1):
if ii+j>yy:break
dp[i+1][ii+j]|=dp[i][j]
if dp[-1][-1]==0:print("NO");return
k=yy
qq=[]
for i in range(len(q),0,-1):
if dp[i][k]==dp[i-1][k]:qq.append((q[i-1][0],-q[i-1][3]))
else:
qq.append((q[i-1][0],q[i-1][3]))
k-=q[i-1][2]
color=[0]*n
visited=set()
for i,c in qq:
stack=[i]
visited.add(i)
color[i]=c
for j in stack:
for k in edge[j]:
if k in visited:continue
visited.add(k)
color[k]=-color[j]
stack.append(k)
for i in range(n):
if color[i]==1:color[i]="2"
elif x:color[i]="1";x-=1
else:color[i]="3"
print("YES")
print("".join(color))
``` | vfc_18186 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1354/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 3\n2 2 2\n3 1\n5 4\n2 5\n",
"output": "YES\n112323\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2109 | Solve the following coding problem using the programming language python:
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
The product of all numbers in the first set is less than zero ( < 0). The product of all numbers in the second set is greater than zero ( > 0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set.
Help Vitaly. Divide the given array.
-----Input-----
The first line of the input contains integer n (3 ≤ n ≤ 100). The second line contains n space-separated distinct integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 10^3) — the array elements.
-----Output-----
In the first line print integer n_1 (n_1 > 0) — the number of elements in the first set. Then print n_1 numbers — the elements that got to the first set.
In the next line print integer n_2 (n_2 > 0) — the number of elements in the second set. Then print n_2 numbers — the elements that got to the second set.
In the next line print integer n_3 (n_3 > 0) — the number of elements in the third set. Then print n_3 numbers — the elements that got to the third set.
The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.
-----Examples-----
Input
3
-1 2 0
Output
1 -1
1 2
1 0
Input
4
-1 -2 -3 0
Output
1 -1
2 -3 -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
# coding: utf-8
n = int(input())
a = []
b = []
c = []
for i in input().split():
i = int(i)
if i < 0:
a.append(i)
elif i == 0:
b.append(i)
else:
c.append(i)
if len(c) == 0:
c.append(a.pop())
c.append(a.pop())
if len(a)%2==0:
b.append(a.pop())
print(len(a),' '.join([str(i) for i in a]))
print(len(c),' '.join([str(i) for i in c]))
print(len(b),' '.join([str(i) for i in b]))
``` | vfc_18190 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/300/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n-1 2 0\n",
"output": "1 -1\n1 2\n1 0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2110 | Solve the following coding problem using the programming language python:
There are many freight trains departing from Kirnes planet every day. One day on that planet consists of $h$ hours, and each hour consists of $m$ minutes, where $m$ is an even number. Currently, there are $n$ freight trains, and they depart every day at the same time: $i$-th train departs at $h_i$ hours and $m_i$ minutes.
The government decided to add passenger trams as well: they plan to add a regular tram service with half-hour intervals. It means that the first tram of the day must depart at $0$ hours and $t$ minutes, where $0 \le t < {m \over 2}$, the second tram departs $m \over 2$ minutes after the first one and so on. This schedule allows exactly two passenger trams per hour, which is a great improvement.
To allow passengers to board the tram safely, the tram must arrive $k$ minutes before. During the time when passengers are boarding the tram, no freight train can depart from the planet. However, freight trains are allowed to depart at the very moment when the boarding starts, as well as at the moment when the passenger tram departs. Note that, if the first passenger tram departs at $0$ hours and $t$ minutes, where $t < k$, then the freight trains can not depart during the last $k - t$ minutes of the day.
$O$ A schematic picture of the correct way to run passenger trams. Here $h=2$ (therefore, the number of passenger trams is $2h=4$), the number of freight trains is $n=6$. The passenger trams are marked in red (note that the spaces between them are the same). The freight trains are marked in blue. Time segments of length $k$ before each passenger tram are highlighted in red. Note that there are no freight trains inside these segments.
Unfortunately, it might not be possible to satisfy the requirements of the government without canceling some of the freight trains. Please help the government find the optimal value of $t$ to minimize the number of canceled freight trains in case all passenger trams depart according to schedule.
-----Input-----
The first line of input contains four integers $n$, $h$, $m$, $k$ ($1 \le n \le 100\,000$, $1 \le h \le 10^9$, $2 \le m \le 10^9$, $m$ is even, $1 \le k \le {m \over 2}$) — the number of freight trains per day, the number of hours and minutes on the planet, and the boarding time for each passenger tram.
$n$ lines follow, each contains two integers $h_i$ and $m_i$ ($0 \le h_i < h$, $0 \le m_i < m$) — the time when $i$-th freight train departs. It is guaranteed that no freight trains depart at the same time.
-----Output-----
The first line of output should contain two integers: the minimum number of trains that need to be canceled, and the optimal starting time $t$. Second line of output should contain freight trains that need to be canceled.
-----Examples-----
Input
2 24 60 15
16 0
17 15
Output
0 0
Input
2 24 60 16
16 0
17 15
Output
1 0
2
-----Note-----
In the first test case of the example the first tram can depart at 0 hours and 0 minutes. Then the freight train at 16 hours and 0 minutes can depart at the same time as the passenger tram, and the freight train at 17 hours and 15 minutes can depart at the same time as the boarding starts for the upcoming passenger tram.
In the second test case of the example it is not possible to design the passenger tram schedule without cancelling any of the freight trains: if $t \in [1, 15]$, then the freight train at 16 hours and 0 minutes is not able to depart (since boarding time is 16 minutes). If $t = 0$ or $t \in [16, 29]$, then the freight train departing at 17 hours 15 minutes is not able to depart. However, if the second freight train is canceled, one can choose $t = 0$. Another possible option is to cancel the first train and choose $t = 13$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
import re
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n, h, m, k = mints()
m //= 2
a = [0]*n
e = [None]*(2*n+2)
c = 0
for i in range(n):
hh, mm = mints()
x = mm % m
a[i] = mm
e[2*i] = ((x+k)%m, -1, i)
e[2*i+1] = ((x+1)%m, 1, i)
if (x+1)%m > (x+k)%m:
c += 1
e[2*n] = (0,0,0)
e[2*n+1] = (m-1,0,0)
#print(e)
e.sort()
p = -1
r = (int(1e9),0)
#print(e)
for x, t, id in e:
#print(x,t,id,c)
if p != x and p != -1:
r = min(r, (c, p))
p = x
c += t
r = min(r, (c, p))
print(*r)
p = r[1]
for i in range(n):
mm = a[i]
x = (mm-p) % m
if (x+1)%m > (x+k)%m and (x+k)%m != 0 \
or (x+1)%m < (x+k)%m and (x+1)%m == 0:
print(i+1,end=' ')
#for i in range(mint()):
solve()
``` | vfc_18194 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1379/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 24 60 15\n16 0\n17 15\n",
"output": "0 0\n\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 24 60 16\n16 0\n17 15\n",
"output": "1 0\n2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 24 60 8\n10 59\n21 56\n0 42\n21 27\n5 24\n5 53\n16 5\n5 22\n10 11\n10 46\n",
"output": "1 5\n1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 3 24 9\n1 15\n0 6\n0 22\n2 22\n2 7\n1 7\n1 23\n2 14\n0 14\n",
"output": "5 7\n1 2 7 8 9 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 24 60 21\n1 36\n2 35\n2 16\n2 55\n1 16\n0 35\n0 55\n1 56\n0 15\n",
"output": "5 16\n1 2 6 8 9 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 11 12 6\n9 5\n8 5\n9 11\n7 5\n10 5\n1 5\n2 11\n3 5\n2 5\n3 11\n",
"output": "0 5\n\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2112 | Solve the following coding problem using the programming language python:
There are $n$ warriors in a row. The power of the $i$-th warrior is $a_i$. All powers are pairwise distinct.
You have two types of spells which you may cast: Fireball: you spend $x$ mana and destroy exactly $k$ consecutive warriors; Berserk: you spend $y$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power.
For example, let the powers of warriors be $[2, 3, 7, 8, 11, 5, 4]$, and $k = 3$. If you cast Berserk on warriors with powers $8$ and $11$, the resulting sequence of powers becomes $[2, 3, 7, 11, 5, 4]$. Then, for example, if you cast Fireball on consecutive warriors with powers $[7, 11, 5]$, the resulting sequence of powers becomes $[2, 3, 4]$.
You want to turn the current sequence of warriors powers $a_1, a_2, \dots, a_n$ into $b_1, b_2, \dots, b_m$. Calculate the minimum amount of mana you need to spend on it.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the length of sequence $a$ and the length of sequence $b$ respectively.
The second line contains three integers $x, k, y$ ($1 \le x, y, \le 10^9; 1 \le k \le n$) — the cost of fireball, the range of fireball and the cost of berserk respectively.
The third line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$). It is guaranteed that all integers $a_i$ are pairwise distinct.
The fourth line contains $m$ integers $b_1, b_2, \dots, b_m$ ($1 \le b_i \le n$). It is guaranteed that all integers $b_i$ are pairwise distinct.
-----Output-----
Print the minimum amount of mana for turning the sequnce $a_1, a_2, \dots, a_n$ into $b_1, b_2, \dots, b_m$, or $-1$ if it is impossible.
-----Examples-----
Input
5 2
5 2 3
3 1 4 5 2
3 5
Output
8
Input
4 4
5 1 4
4 3 1 2
2 4 3 1
Output
-1
Input
4 4
2 1 11
1 3 2 4
1 3 2 4
Output
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def get_val(x, k, y, left_val, right_val, arr):
x, y = y, x
if not arr:
return 0
if len(arr) < k:
if max(arr) > max(left_val, right_val):
return -1
return len(arr) * x
if y < x * k:
n = len(arr)
res = 0
while n >= k:
n -= k
res += y
res += n * x
return res
else:
if max(arr) < max(left_val, right_val):
return len(arr) * x
else:
return ((len(arr) - k) * x) + y
def solve(x, k, y, a, b):
def check(a, b):
j = 0
i = 0
while i < len(a) and j < len(b):
if a[i] != b[j]:
i += 1
else:
i += 1
j += 1
return j == len(b)
if not check(a, b):
return -1
j = 0
left_val = -1
arr = []
res = 0
for num in a:
if j == len(b) or num != b[j]:
arr.append(num)
else:
val = get_val(x, k, y, left_val, num, arr)
if val == -1:
return -1
res += val
arr = []
left_val = num
j += 1
if arr:
val = get_val(x, k, y, left_val, -1, arr)
if val == -1:
return -1
res += val
return res
n, m = list(map(int, input().split()))
x, k, y = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(solve(x, k, y, a, b))
``` | vfc_18202 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1380/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 2\n5 2 3\n3 1 4 5 2\n3 5\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4\n5 1 4\n4 3 1 2\n2 4 3 1\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2114 | Solve the following coding problem using the programming language python:
Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!
Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The queen walks in all directions vertically and diagonally at any distance. You can see the examples below. [Image]
To reach the goal, Egor should research the next topic:
There is an $N \times N$ board. Each cell of the board has a number from $1$ to $N ^ 2$ in it and numbers in all cells are distinct.
In the beginning, some chess figure stands in the cell with the number $1$. Note that this cell is already considered as visited. After that every move is determined by the following rules: Among all not visited yet cells to which the figure can get in one move, it goes to the cell that has minimal number. If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of $1$ vun. If all cells are already visited, the process is stopped.
Egor should find an $N \times N$ board on which the rook pays strictly less vuns than the queen during the round with this numbering. Help him to find such $N \times N$ numbered board, or tell that it doesn't exist.
-----Input-----
The only line contains one integer $N$ — the size of the board, $1\le N \le 500$.
-----Output-----
The output should contain $N$ lines.
In $i$-th line output $N$ numbers — numbers on the $i$-th row of the board. All numbers from $1$ to $N \times N$ must be used exactly once.
On your board rook must pay strictly less vuns than the queen.
If there are no solutions, print $-1$.
If there are several solutions, you can output any of them.
-----Examples-----
Input
1
Output
-1
Input
4
Output
4 3 6 12
7 5 9 15
14 1 11 10
13 8 16 2
-----Note-----
In case we have $1 \times 1$ board, both rook and queen do not have a chance to pay fees.
In second sample rook goes through cells $1 \to 3 \to 4 \to 6 \to 9 \to 5 \to 7 \to 13 \to 2 \to 8 \to 16 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14$.
Queen goes through $1 \to 3 \to 4 \to 2 \to 5 \to 6 \to 9 \to 7 \to 13 \to 8 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14 \to \textbf{(1 vun)} \to 16$.
As a result rook pays 1 vun and queen pays 2 vuns.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = input()
n = int(n)
if n <=2:
print(-1)
elif n%2 ==0:
for row in range(n):
if row ==0:
for i in range(n):
if i ==0:
print(i+1,end = " ")
elif i==n-1:
print(i+1)
else:
print(i+1,end = " ")
elif row ==n-1:
for i in range(n):
if i==n-1:
print(n*n-1)
else:
print(n+(n-1)*(n-2)+(n-3)-i+2,end = " ")
elif row ==n-2:
for i in range(n):
if i ==0:
print(n*n-n+2+row,end = " ")
elif i <n-1:
print(n+(n-1)*(row-1)+i,end = " ")
else:
print(n+(n-1)*(row-1)+n-1)
elif row%2 ==1:
for i in range(n):
if i ==0:
print(n*n-n+2+row-1,end = " ")
elif i <n-1:
print(n+(n-1)*(row-1)+n-i,end = " ")
else:
print(n+(n-1)*(row-1)+1)
elif row%2 ==0:
for i in range(n):
if i ==0:
print(n*n-n+2+row-1,end = " ")
elif i <n-1:
print(n+(n-1)*(row-1)+i,end = " ")
else:
print(n+(n-1)*(row-1)+n-1)
elif n%2 ==1:
for row in range(n):
if row ==0:
for i in range(n):
if i ==0:
print(i+1,end = " ")
elif i==n-1:
print(n*n-n+row+1)
else:
print(i+1,end = " ")
elif row ==n-1:
for i in range(n):
if i==0:
print(n*n-1,end = " ")
elif i ==n-1:
print((n-1)*(n-1)+i)
else:
print((n-1)*(n-1)+i,end = " ")
elif row ==n-2:
for i in range(n):
if i ==0:
print((n-1)*row+n-i-1,end = " ")
elif i <n-1:
print((n-1)*row+n-i-1,end = " ")
else:
print(n*n)
elif row%2 ==1:
for i in range(n):
if i ==0:
print((n-1)*row+n-i-1,end = " ")
elif i <n-1:
print((n-1)*row+n-i-1,end = " ")
else:
print(n*n-n+row+1)
elif row%2 ==0:
for i in range(n):
if i ==0:
print((n-1)*row+i+1,end = " ")
elif i <n-1:
print((n-1)*row+i+1,end = " ")
else:
print(n*n-n+row+1)
``` | vfc_18210 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1333/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n",
"output": "-1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "1 2 3 4 \n13 15 11 5 \n12 9 10 6 \n16 14 8 7 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "-1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2115 | Solve the following coding problem using the programming language python:
You are given a sequence of positive integers a_1, a_2, ..., a_{n}.
While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer x + 1 on their place. This way the number of elements in the sequence is decreased by 1 on each step.
You stop performing the operation when there is no pair of equal consecutive elements.
For example, if the initial sequence is [5, 2, 1, 1, 2, 2], then after the first operation you get [5, 2, 2, 2, 2], after the second — [5, 3, 2, 2], after the third — [5, 3, 3], and finally after the fourth you get [5, 4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.
Determine the final sequence after you stop performing the operation.
-----Input-----
The first line contains a single integer n (2 ≤ n ≤ 2·10^5) — the number of elements in the sequence.
The second line contains the sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
In the first line print a single integer k — the number of elements in the sequence after you stop performing the operation.
In the second line print k integers — the sequence after you stop performing the operation.
-----Examples-----
Input
6
5 2 1 1 2 2
Output
2
5 4
Input
4
1000000000 1000000000 1000000000 1000000000
Output
1
1000000002
Input
7
4 10 22 11 12 5 6
Output
7
4 10 22 11 12 5 6
-----Note-----
The first example is described in the statements.
In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].
In the third example there are no two equal consecutive elements initially, so the sequence does not change.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n=int(input())
a=list(map(int,input().split()))
i=0
b=[]
while i+1<n:
if a[i]==a[i+1]:
a[i+1]=a[i]+1
if len(b)>0:
a[i]=b.pop()
else:
i=i+1
else:
b.append(a[i])
i=i+1
b.append(a[-1])
print(len(b))
print(*b)
``` | vfc_18214 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/926/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n5 2 1 1 2 2\n",
"output": "2\n5 4 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1000000000 1000000000 1000000000 1000000000\n",
"output": "1\n1000000002 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n4 10 22 11 12 5 6\n",
"output": "7\n4 10 22 11 12 5 6 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1\n",
"output": "1\n2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 1 1\n",
"output": "1\n3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n3 2 1 1\n",
"output": "1\n4 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2116 | Solve the following coding problem using the programming language python:
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online.
The store contains k items. n customers have already used the above service. Each user paid for m items. Let a_{ij} denote the j-th item in the i-th person's order.
Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items a_{ij} (1 ≤ j ≤ m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(a_{i}1) + pos(a_{i}2) + ... + pos(a_{im}) for the i-th customer.
When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating.
Your task is to calculate the total time it takes for Ayush to process all the orders.
You can assume that the market has endless stock.
-----Input-----
The first line contains three integers n, m and k (1 ≤ n, k ≤ 100, 1 ≤ m ≤ k) — the number of users, the number of items each user wants to buy and the total number of items at the market.
The next line contains k distinct integers p_{l} (1 ≤ p_{l} ≤ k) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to k.
Each of the next n lines contains m distinct integers a_{ij} (1 ≤ a_{ij} ≤ k) — the order of the i-th person.
-----Output-----
Print the only integer t — the total time needed for Ayush to process all the orders.
-----Example-----
Input
2 2 5
3 4 1 2 5
1 5
3 1
Output
14
-----Note-----
Customer 1 wants the items 1 and 5.
pos(1) = 3, so the new positions are: [1, 3, 4, 2, 5].
pos(5) = 5, so the new positions are: [5, 1, 3, 4, 2].
Time taken for the first customer is 3 + 5 = 8.
Customer 2 wants the items 3 and 1.
pos(3) = 3, so the new positions are: [3, 5, 1, 4, 2].
pos(1) = 3, so the new positions are: [1, 3, 5, 4, 2].
Time taken for the second customer is 3 + 3 = 6.
Total time is 8 + 6 = 14.
Formally pos(x) is the index of x in the current row.
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())
a = list(map(int, input().split()))
ans = 0
for i in range(n):
orders = map(int, input().split())
for order in orders:
ans += a.index(order) + 1
a.remove(order)
a.insert(0, order)
print(ans)
``` | vfc_18218 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/665/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2 5\n3 4 1 2 5\n1 5\n3 1\n",
"output": "14\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4 4\n1 2 3 4\n3 4 2 1\n4 3 2 1\n4 1 2 3\n4 1 2 3\n",
"output": "59\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 1 100\n1 55 67 75 40 86 24 84 82 26 81 23 70 79 51 54 21 78 31 98 68 93 66 88 99 65 20 52 35 85 16 12 94 100 59 56 18 33 47 46 71 8 38 57 2 92 3 95 6 4 87 22 48 80 15 29 11 45 72 76 44 60 91 90 39 74 41 36 13 27 53 83 32 5 30 63 89 64 49 17 9 97 69 14 50 77 37 96 10 42 28 34 61 19 73 7 62 43 58 25\n33\n69\n51\n7\n68\n70\n1\n35\n24\n7\n",
"output": "335\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2117 | Solve the following coding problem using the programming language python:
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.
The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.
A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.
Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.
-----Input-----
The first line of the input contains an integer N (1 ≤ N ≤ 10^5) – the number of planets in the galaxy.
The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
-----Output-----
On a single line, print N space-separated integers. The K-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of K ships.
-----Examples-----
Input
3
1 2
2 3
Output
1 3 3
Input
4
1 2
3 2
4 2
Output
1 3 4 4
-----Note-----
Consider the first example. If K = 1, then Heidi can only send one ship to some planet and control it. However, for K ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.
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
from collections import defaultdict
import heapq
n = int(stdin.readline())
a = [[] for _ in range(n)]
for _ in range(n-1):
e = stdin.readline().split(' ')
u, v = int(e[0]), int(e[1])
a[u-1].append(v-1)
a[v-1].append(u-1)
leaves = [i for i in range(n) if len(a[i]) == 1]
def dfs_from(root):
depth = defaultdict(int)
child = {}
parent = defaultdict(lambda: -1)
stack = [root]
visited = [False for _ in range(n)]
while len(stack) > 0:
crt = stack[-1]
if visited[crt]:
stack.pop(-1)
if len(a[crt]) > 1: # not a leaf
child[crt], depth[crt] = max([(c, depth[c]+1) for c in a[crt]
if c != parent[crt]],
key=lambda x: x[1])
else:
child[crt] = -1
depth[crt] = 0
continue
visited[crt] = True
for next in a[crt]:
if next != parent[crt]:
stack.append(next)
parent[next] = crt
return depth, child
first_choice = leaves[0]
d1, child1 = dfs_from(first_choice)
root = max([(a[leaf][0], d1[a[leaf][0]]) for leaf in leaves],
key=lambda leaf_depth: leaf_depth[1])[0]
while child1[root] != -1:
root = child1[root]
depth, child = dfs_from(root)
solution = [1]
pq = []
for k, v in list(depth.items()):
heapq.heappush(pq, (-v, k))
seen = [False for _ in range(n)]
seen[root] = True
while len(pq) > 0:
_, best = heapq.heappop(pq)
if seen[best]:
continue
path = []
c = best
s = 0
while c != -1:
seen[c] = True
c = child[c]
s = s+1
s = s + solution[-1]
solution.append(s)
for _ in range(n - min(len(solution), n)):
solution.append(n)
print(' '.join([str(s) for s in solution]))
``` | vfc_18222 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/958/B2",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2\n2 3\n",
"output": "1 3 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 2\n3 2\n4 2\n",
"output": "1 3 4 4 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "19\n2 19\n7 15\n8 10\n16 1\n12 5\n11 5\n6 18\n12 14\n14 15\n2 6\n9 14\n4 17\n16 10\n4 2\n7 18\n3 2\n9 13\n11 10\n",
"output": "1 14 16 17 18 19 19 19 19 19 19 19 19 19 19 19 19 19 19 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20\n12 10\n5 19\n12 18\n4 2\n3 16\n11 8\n3 2\n17 4\n14 7\n6 5\n10 20\n14 9\n16 12\n9 13\n13 4\n1 15\n11 6\n15 19\n14 8\n",
"output": "1 17 18 19 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "21\n10 12\n12 9\n16 8\n18 11\n17 15\n4 11\n7 19\n10 14\n10 19\n8 5\n1 5\n20 3\n19 18\n2 20\n19 15\n9 16\n6 4\n4 13\n20 6\n13 21\n",
"output": "1 14 16 18 19 20 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "23\n5 14\n6 7\n6 17\n2 4\n6 13\n9 17\n14 10\n23 9\n1 18\n3 12\n15 11\n21 15\n10 23\n4 3\n8 15\n22 18\n22 16\n15 5\n12 22\n4 6\n19 16\n20 10\n",
"output": "1 15 17 18 19 20 21 22 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2118 | Solve the following coding problem using the programming language python:
Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array a with indices from [l, r) can be implemented as follows: If the segment [l, r) is already sorted in non-descending order (that is, for any i such that l ≤ i < r - 1 a[i] ≤ a[i + 1]), then end the function call; Let $\operatorname{mid} = \lfloor \frac{l + r}{2} \rfloor$; Call mergesort(a, l, mid); Call mergesort(a, mid, r); Merge segments [l, mid) and [mid, r), making the segment [l, r) sorted in non-descending order. The merge algorithm doesn't call any other functions.
The array in this problem is 0-indexed, so to sort the whole array, you need to call mergesort(a, 0, n).
The number of calls of function mergesort is very important, so Ivan has decided to calculate it while sorting the array. For example, if a = {1, 2, 3, 4}, then there will be 1 call of mergesort — mergesort(0, 4), which will check that the array is sorted and then end. If a = {2, 1, 3}, then the number of calls is 3: first of all, you call mergesort(0, 3), which then sets mid = 1 and calls mergesort(0, 1) and mergesort(1, 3), which do not perform any recursive calls because segments (0, 1) and (1, 3) are sorted.
Ivan has implemented the program that counts the number of mergesort calls, but now he needs to test it. To do this, he needs to find an array a such that a is a permutation of size n (that is, the number of elements in a is n, and every integer number from [1, n] can be found in this array), and the number of mergesort calls when sorting the array is exactly k.
Help Ivan to find an array he wants!
-----Input-----
The first line contains two numbers n and k (1 ≤ n ≤ 100000, 1 ≤ k ≤ 200000) — the size of a desired permutation and the number of mergesort calls required to sort it.
-----Output-----
If a permutation of size n such that there will be exactly k calls of mergesort while sorting it doesn't exist, output - 1. Otherwise output n integer numbers a[0], a[1], ..., a[n - 1] — the elements of a permutation that would meet the required conditions. If there are multiple answers, print any of them.
-----Examples-----
Input
3 3
Output
2 1 3
Input
4 1
Output
1 2 3 4
Input
5 6
Output
-1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def create_list(n, num_of_calls):
if n == 1:
return [1], 0
if n == 2:
return [2, 1], 2
if num_of_calls == 2:
return list(range(2, n // 2 + 2)) + [1] +\
list(range(n // 2 + 2, n + 1)), 2
list1, num_of_calls1 = create_list(n // 2, num_of_calls - 2)
if num_of_calls1 == num_of_calls - 2:
return list1 + list(range(n // 2 + 1, n + 1)), num_of_calls
list2, num_of_calls2 = create_list((n + 1) // 2,
num_of_calls - num_of_calls1 - 2)
return list1 + [x + n // 2 for x in list2], \
num_of_calls1 + num_of_calls2 + 2
def main():
n, k = [int(x) for x in input().split()]
if k % 2 != 1:
print(-1)
return
if k == 1:
print(' '.join([str(x) for x in range(1, n + 1)]))
return
num_list, num_of_calls = create_list(n, k - 1)
if num_of_calls != k - 1:
print(-1)
return
print(' '.join([str(x) for x in num_list]))
def __starting_point():
main()
__starting_point()
``` | vfc_18226 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/873/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3\n",
"output": "2 1 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n",
"output": "1 2 3 4 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2120 | Solve the following coding problem using the programming language python:
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as v_{i}. The child spend v_{f}_1 + v_{f}_2 + ... + v_{f}_{k} energy for removing part i where f_1, f_2, ..., f_{k} are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
-----Input-----
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v_1, v_2, ..., v_{n} (0 ≤ v_{i} ≤ 10^5). Then followed m lines, each line contains two integers x_{i} and y_{i}, representing a rope from part x_{i} to part y_{i} (1 ≤ x_{i}, y_{i} ≤ n; x_{i} ≠ y_{i}).
Consider all the parts are numbered from 1 to n.
-----Output-----
Output the minimum total energy the child should spend to remove all n parts of the toy.
-----Examples-----
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
-----Note-----
One of the optimal sequence of actions in the first sample is: First, remove part 3, cost of the action is 20. Then, remove part 2, cost of the action is 10. Next, remove part 4, cost of the action is 10. At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Codeforces Round 250 Div 2 Problem C
Author : chaotic_iak
Language: Python 3.3.4
"""
class IOHandlerObject(object):
def getInput(self, 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 writeOutput(self, s="\n"):
if isinstance(s, list): s = " ".join(s)
print(s)
IOHandler = IOHandlerObject()
g = IOHandler.getInput
w = IOHandler.writeOutput
############################## SOLUTION ##############################
n,m = g()
v = g()
sm = 0
for i in range(m):
x,y = g()
sm += min(v[x-1], v[y-1])
print(sm)
``` | vfc_18234 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/437/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n10 20 30 40\n1 4\n1 2\n2 3\n",
"output": "40\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2121 | Solve the following coding problem using the programming language python:
For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent a_{i} minutes building the i-th ball in the tree.
Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to search his whole tree to determine this; Jacob knows that she will examine the first k nodes in a DFS-order traversal of the tree. She will then assign Jacob a grade equal to the minimum a_{i} she finds among those k nodes.
Though Jacob does not have enough time to rebuild his model, he can choose the root node that his teacher starts from. Furthermore, he can rearrange the list of neighbors of each node in any order he likes. Help Jacob find the best grade he can get on this assignment.
A DFS-order traversal is an ordering of the nodes of a rooted tree, built by a recursive DFS-procedure initially called on the root of the tree. When called on a given node v, the procedure does the following: Print v. Traverse the list of neighbors of the node v in order and iteratively call DFS-procedure on each one. Do not call DFS-procedure on node u if you came to node v directly from u.
-----Input-----
The first line of the input contains two positive integers, n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ n) — the number of balls in Jacob's tree and the number of balls the teacher will inspect.
The second line contains n integers, a_{i} (1 ≤ a_{i} ≤ 1 000 000), the time Jacob used to build the i-th ball.
Each of the next n - 1 lines contains two integers u_{i}, v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) representing a connection in Jacob's tree between balls u_{i} and v_{i}.
-----Output-----
Print a single integer — the maximum grade Jacob can get by picking the right root of the tree and rearranging the list of neighbors.
-----Examples-----
Input
5 3
3 6 1 4 2
1 2
2 4
2 5
1 3
Output
3
Input
4 2
1 5 5 5
1 2
1 3
1 4
Output
1
-----Note-----
In the first sample, Jacob can root the tree at node 2 and order 2's neighbors in the order 4, 1, 5 (all other nodes have at most two neighbors). The resulting preorder traversal is 2, 4, 1, 3, 5, and the minimum a_{i} of the first 3 nodes is 3.
In the second sample, it is clear that any preorder traversal will contain node 1 as either its first or second node, so Jacob cannot do better than a grade of 1.
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, k = map(int, input().split())
a = [int(i) for i in input().split()]
g = [[] for _ in range(n)]
for i in range(n - 1):
u, v = map(int, input().split())
g[u-1].append(v-1)
g[v-1].append(u-1)
stack = [0]
done = [False] * n
par = [0] * n
order = []
while len(stack) > 0:
x = stack.pop()
done[x] = True
order.append(x)
for i in g[x]:
if done[i] == False:
par[i] = x
stack.append(i)
order = order[::-1]
sub = [0] * n
for i in order:
sub[i] = 1
for j in g[i]:
if par[j] == i:
sub[i] += sub[j]
def good(guess):
cnt = [0] * n
for i in order:
if a[i] < guess:
continue
cnt[i] = 1
opt = 0
for j in g[i]:
if par[j] == i:
if cnt[j] == sub[j]:
cnt[i] += cnt[j]
else:
opt = max(opt, cnt[j])
cnt[i] += opt
if cnt[0] >= k:
return True
up = [0] * n
for i in order[::-1]:
if a[i] < guess:
continue
opt, secondOpt = 0, 0
total = 1
for j in g[i]:
val, size = 0, 0
if par[j] == i:
val = cnt[j]
size = sub[j]
else:
val = up[i]
size = n - sub[i]
if val == size:
total += val
else:
if opt < val:
opt, secondOpt = val, opt
elif secondOpt < val:
secondOpt = val
for j in g[i]:
if par[j] == i:
up[j] = total
add = opt
if sub[j] == cnt[j]:
up[j] -= cnt[j]
elif cnt[j] == opt:
add = secondOpt
up[j] += add
for i in range(n):
if a[i] < guess:
continue
total, opt = 1, 0
for j in g[i]:
val, size = 0, 0
if par[j] == i:
val = cnt[j]
size = sub[j]
else:
val = up[i]
size = n - sub[i]
if val == size:
total += val
else:
opt = max(opt, val)
if total + opt >= k:
return True
return False
l, r = 0, max(a)
while l < r:
mid = (l + r + 1) // 2
if good(mid):
l = mid
else:
r = mid - 1
print(l)
``` | vfc_18238 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/627/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 3\n3 6 1 4 2\n1 2\n2 4\n2 5\n1 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2\n1 5 5 5\n1 2\n1 3\n1 4\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n1 100000\n2 1\n",
"output": "100000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2122 | Solve the following coding problem using the programming language python:
Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences.
-----Input-----
Same as the easy version, but the limits have changed: 1 ≤ n, k ≤ 400 000.
-----Output-----
Same as the easy version.
-----Examples-----
Input
4 100
1 2 2 1
Output
2
Input
4 1
1 2 2 1
Output
3
Input
4 2
1 2 3 1
Output
3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
import heapq
from collections import namedtuple
Record = namedtuple('Record', ['index', 'book_id'])
l1 = sys.stdin.readline()
l2 = sys.stdin.readline()
n, k = list(map(int, l1.split(' ')))
books = list(map(int, l2.split(' ')))
cost = 0
cache = set()
prev = dict() # book_id -> index
next = [n+1] * n # index of next with the same value
inactive_ids = set() # set of inactive object id()s
book_to_record = dict()
def serve_book(book_id, i):
cache.add(book_id)
record = Record(-next[i], book_id)
heapq.heappush(h, record)
book_to_record[book_id] = record
h = []
for i, book_id in enumerate(books):
if book_id in prev:
next[prev[book_id]] = i
prev[book_id] = i
for i, book_id in enumerate(books):
# print("book_id=%s, h=%s, inactive=%s" %(book_id, h, inactive_ids))
if book_id in cache:
previous_record = book_to_record[book_id]
inactive_ids.add(id(previous_record))
serve_book(book_id, i)
# print('--> Serve book from library ', book_id)
continue
if len(cache) < k:
cost += 1
serve_book(book_id, i)
# print('--> Buy book', book_id)
continue
while True:
item = heapq.heappop(h)
if id(item) in inactive_ids:
# print("--> Ignore record", item)
inactive_ids.remove(id(item))
continue
cache.remove(item.book_id)
serve_book(book_id, i)
cost += 1
# print('--> Throw away book', item.book_id)
# print('--> Add book to libary', book_id)
break
# print("To evict %s" % to_evict)
print(cost)
``` | vfc_18242 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/802/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 100\n1 2 2 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n1 2 2 1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2\n1 2 3 1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11 1\n1 2 3 5 1 10 10 1 1 3 5\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n1 2 3 1 2\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2\n1 2 3 2\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2123 | Solve the following coding problem using the programming language python:
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height h_{i}. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by h_{k} - h_{k} + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time.
Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5). The next line contains n integers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^5) representing the heights of the pylons.
-----Output-----
Print a single number representing the minimum number of dollars paid by Caisa.
-----Examples-----
Input
5
3 4 3 2 4
Output
4
Input
3
4 4 4
Output
4
-----Note-----
In the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Codeforces Contest 264 Div 2 Problem B
Author : chaotic_iak
Language: Python 3.3.4
"""
def main():
n, = read()
print(max(read()))
################################### NON-SOLUTION STUFF BELOW
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_18246 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/463/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n3 4 3 2 4\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n4 4 4\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "99\n1401 2019 1748 3785 3236 3177 3443 3772 2138 1049 353 908 310 2388 1322 88 2160 2783 435 2248 1471 706 2468 2319 3156 3506 2794 1999 1983 2519 2597 3735 537 344 3519 3772 3872 2961 3895 2010 10 247 3269 671 2986 942 758 1146 77 1545 3745 1547 2250 2565 217 1406 2070 3010 3404 404 1528 2352 138 2065 3047 3656 2188 2919 2616 2083 1280 2977 2681 548 4000 1667 1489 1109 3164 1565 2653 3260 3463 903 1824 3679 2308 245 2689 2063 648 568 766 785 2984 3812 440 1172 2730\n",
"output": "4000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "68\n477 1931 3738 3921 2306 1823 3328 2057 661 3993 2967 3520 171 1739 1525 1817 209 3475 1902 2666 518 3283 3412 3040 3383 2331 1147 1460 1452 1800 1327 2280 82 1416 2200 2388 3238 1879 796 250 1872 114 121 2042 1853 1645 211 2061 1472 2464 726 1989 1746 489 1380 1128 2819 2527 2939 622 678 265 2902 1111 2032 1453 3850 1621\n",
"output": "3993\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "30\n30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1\n",
"output": "30\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3 2 1\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2124 | Solve the following coding problem using the programming language python:
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.
At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.
Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.
He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
-----Input-----
The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format.
The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat.
The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line: <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat. <?>:<text> — the format of a message with unknown sender.
The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters.
We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha".
It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.
-----Output-----
Print the information about the t chats in the following format:
If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format:
<username>:<text>
If there are multiple answers, print any of them.
-----Examples-----
Input
1
2
Vladik netman
2
?: Hello, Vladik!
?: Hi
Output
netman: Hello, Vladik!
Vladik: Hi
Input
1
2
netman vladik
3
netman:how are you?
?:wrong message
vladik:im fine
Output
Impossible
Input
2
3
netman vladik Fedosik
2
?: users are netman, vladik, Fedosik
vladik: something wrong with this chat
4
netman tigerrrrr banany2001 klinchuh
4
?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
?: yes, netman
banany2001: yes of course.
Output
Impossible
netman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
tigerrrrr: yes, netman
banany2001: yes of course.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def pr( name , lvl , dp , u , tot ):
if lvl == 0:
print(name + ':' + tot[lvl])
return
pr( u[lvl][name] , lvl - 1 , dp , u , tot )
print(name + ':' + tot[lvl])
def solve():
n = int(input())
users = input().split()
m = int(input())
dp = []
u = []
tot = []
for i in range( m ) :
dp.append( set() )
u.append( {} )
line = input().split(':')
sender = line[0]
tot.append( line[1] )
line[1] = line[1].replace( '?' , ' ' )
line[1] = line[1].replace( '.' , ' ' )
line[1] = line[1].replace( ',' , ' ' )
line[1] = line[1].replace( '!' , ' ' )
mess = line[1].split()
if sender == '?' :
if i != 0:
for name in users:
for x in dp[i-1]:
if x != name and name not in mess:
dp[i].add( name )
u[i][name] = x
else :
for name in users:
if name not in mess:
dp[i].add( name )
else:
if i != 0:
for x in dp[i-1]:
if x != sender:
dp[i].add( sender )
u[i][sender] = x
else:
dp[i].add( sender )
if dp[m-1]:
pr( list(dp[m-1])[0] , m-1 , dp , u , tot )
else:
print("Impossible")
t = int(input())
for i in range( t ) :
solve()
``` | vfc_18250 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/754/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n2\nVladik netman\n2\n?: Hello, Vladik!\n?: Hi\n",
"output": "netman: Hello, Vladik!\nVladik: Hi\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2125 | Solve the following coding problem using the programming language python:
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $n \cdot m$ colored pieces that form a rectangle with $n$ rows and $m$ columns.
The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.
Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different. [Image] [Image] [Image]
These subrectangles are flags. [Image] [Image] [Image] [Image] [Image] [Image]
These subrectangles are not flags.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 1\,000$) — the number of rows and the number of columns on the blanket.
Each of the next $n$ lines contains $m$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
-----Output-----
In the only line print the number of subrectangles which form valid flags.
-----Examples-----
Input
4 3
aaa
bbb
ccb
ddd
Output
6
Input
6 1
a
a
b
b
c
c
Output
1
-----Note----- [Image] [Image]
The selected subrectangles are flags in the first example.
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 as dd
import math
import sys
#input=sys.stdin.readline
def nn():
return int(input())
def li():
return list(input())
def mi():
return list(map(int, input().split()))
def lm():
return list(map(int, input().split()))
n,m=mi()
quilt=[]
for i in range(n):
quilt.append(li())
def getflags(column):
flags=set()
breaks=[0]
for i in range(0,len(column)-1):
if not column[i]==column[i+1]:
breaks.append(i+1)
breaks.append(len(column))
#print(breaks)
for j in range(1,len(breaks)-2):
midlength=breaks[j+1]-breaks[j]
firstlength=breaks[j]-breaks[j-1]
endlength=breaks[j+2]-breaks[j+1]
if midlength<=firstlength and midlength<=endlength:
flags.add(((breaks[j+1],breaks[j]), (column[breaks[j+1]], column[breaks[j]],column[breaks[j-1]])))
return flags
flagdicts=[0]*m
for i in range(m):
col=[row[i] for row in quilt]
flagdicts[i]=getflags(col)
total=0
#print(flagdicts)
for i in range(m):
for flag in flagdicts[i]:
k=1
while i+k<m and flag in flagdicts[i+k]:
k+=1
#print(flagdicts[i+k])
#flagdicts[i+k].remove(flag)
for j in range(1,k):
flagdicts[i+j].remove(flag)
total+=k*(k+1)//2
print(total)
``` | vfc_18254 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1181/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\naaa\nbbb\nccb\nddd\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 1\na\na\nb\nb\nc\nc\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\na\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2127 | Solve the following coding problem using the programming language python:
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill $x \times y$ fits into some wallet $h \times w$ if either $x \le h$ and $y \le w$ or $y \le h$ and $x \le w$. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
$+~x~y$ — Polycarp earns a bill of size $x \times y$; $?~h~w$ — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $h \times w$.
It is guaranteed that there is at least one query of type $1$ before the first query of type $2$ and that there is at least one query of type $2$ in the input data.
For each query of type $2$ print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 5 \cdot 10^5$) — the number of queries.
Each of the next $n$ lines contains a query of one of these two types:
$+~x~y$ ($1 \le x, y \le 10^9$) — Polycarp earns a bill of size $x \times y$; $?~h~w$ ($1 \le h, w \le 10^9$) — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $h \times w$.
It is guaranteed that there is at least one query of type $1$ before the first query of type $2$ and that there is at least one query of type $2$ in the input data.
-----Output-----
For each query of type $2$ print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
-----Example-----
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
-----Note-----
The queries of type $2$ of the example:
Neither bill fits; Both bills fit (just checking that you got that bills can overlap); Both bills fit (both bills are actually the same); All bills fit (too much of free space in a wallet is not a problem); Only bill $1 \times 5$ fit (all the others don't, thus it's "NO").
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())
m = 0
M = 0
for i in range (0, n):
line = sys.stdin.readline().strip().split()
s = line[0]
x = min([int(line[1]), int(line[2])])
y = max([int(line[1]), int(line[2])])
if s == '+':
m = max([m, x])
M = max([M, y])
else:
if x >= m and y >= M:
print("YES")
else:
print("NO")
``` | vfc_18262 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1101/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "9\n+ 3 2\n+ 2 3\n? 1 20\n? 3 3\n? 2 3\n+ 1 5\n? 10 10\n? 1 5\n+ 1 1\n",
"output": "NO\nYES\nYES\nYES\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n+ 1 7\n+ 6 7\n+ 8 3\n? 10 10\n+ 5 4\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n+ 9 6\n? 4 7\n? 10 1\n? 5 6\n? 5 5\n",
"output": "NO\nNO\nNO\nNO\n",
"type": "stdin_stdout"
}
]
} |
Subsets and Splits