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 | 1886 | Solve the following coding problem using the programming language python:
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
-----Input-----
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 10^3.
-----Output-----
Output the given word after capitalization.
-----Examples-----
Input
ApPLe
Output
ApPLe
Input
konjac
Output
Konjac
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = str(input())
s = (s[:1].upper() + s[1:]).rstrip()
print(s)
``` | vfc_17298 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/281/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "ApPLe\n",
"output": "ApPLe\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "konjac\n",
"output": "Konjac\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "a\n",
"output": "A\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1887 | Solve the following coding problem using the programming language python:
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $2 \cdot n$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $n$ people in each row). Students are numbered from $1$ to $n$ in each row in order from left to right.
[Image]
Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all $2n$ students (there are no additional constraints), and a team can consist of any number of students.
Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.
-----Input-----
The first line of the input contains a single integer $n$ ($1 \le n \le 10^5$) — the number of students in each row.
The second line of the input contains $n$ integers $h_{1, 1}, h_{1, 2}, \ldots, h_{1, n}$ ($1 \le h_{1, i} \le 10^9$), where $h_{1, i}$ is the height of the $i$-th student in the first row.
The third line of the input contains $n$ integers $h_{2, 1}, h_{2, 2}, \ldots, h_{2, n}$ ($1 \le h_{2, i} \le 10^9$), where $h_{2, i}$ is the height of the $i$-th student in the second row.
-----Output-----
Print a single integer — the maximum possible total height of players in a team Demid can choose.
-----Examples-----
Input
5
9 3 5 7 3
5 8 1 4 5
Output
29
Input
3
1 2 9
10 1 1
Output
19
Input
1
7
4
Output
7
-----Note-----
In the first example Demid can choose the following team as follows: [Image]
In the second example Demid can choose the following team as follows: [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
h1 = list(map(int, input().split()))
h2 = list(map(int, input().split()))
r1 = r2 = 0
for i in range(n):
r1, r2 = max(r1, r2 + h1[i]), max(r2, r1 + h2[i])
print(max(r1, r2))
``` | vfc_17302 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1195/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n9 3 5 7 3\n5 8 1 4 5\n",
"output": "29\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 2 9\n10 1 1\n",
"output": "19\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n7\n4\n",
"output": "7\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1888 | Solve the following coding problem using the programming language python:
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.
This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.
-----Input-----
The first line contains two integers n and m (1 ≤ n ≤ 100; 0 ≤ m ≤ 10^4). The next m lines contain the debts. The i-th line contains three integers a_{i}, b_{i}, c_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}; 1 ≤ c_{i} ≤ 100), which mean that person a_{i} owes person b_{i} c_{i} rubles.
Assume that the people are numbered by integers from 1 to n.
It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x).
-----Output-----
Print a single integer — the minimum sum of debts in the optimal rearrangement.
-----Examples-----
Input
5 3
1 2 10
2 3 1
2 4 1
Output
10
Input
3 0
Output
0
Input
4 3
1 2 1
2 3 1
3 1 1
Output
0
-----Note-----
In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10.
In the second sample, there are no debts.
In the third sample, you can annul all the debts.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
data = input().split(" ")
n = int(data[0])
m = int(data[1])
debts = []
total = 0
for i in range(n):
debts.append(0)
for i in range(m):
data = input().split(" ")
data = [int(x) for x in data]
debts[data[0]-1] -= data[2]
debts[data[1]-1] += data[2]
for i in range(len(debts)):
if debts[i] < 0:
total += (debts[i]*-1)
print(total)
``` | vfc_17306 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/376/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 3\n1 2 10\n2 3 1\n2 4 1\n",
"output": "10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1890 | Solve the following coding problem using the programming language python:
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (10^9 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
-----Input-----
In the first line you're given a string a (1 ≤ |a| ≤ 10^5), containing digits only. In the second line you're given an integer k (1 ≤ k ≤ 10^9). The plate s is formed by concatenating k copies of a together. That is n = |a|·k.
-----Output-----
Print a single integer — the required number of ways modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
-----Note-----
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 2^6 - 1 = 63 possible ways to delete digits.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a = input()
k = int(input())
n = len(a)
ans = 0
MOD = 10 ** 9 + 7
m = 1 - pow(2, n * k, MOD)
m *= pow(1 - pow(2, n, MOD), MOD - 2, MOD)
m %= MOD
for i in range(n - 1, -1, -1):
if a[i] == '0' or a[i] == '5':
ans += (m * pow(2, i, MOD)) % MOD
ans = ans % MOD
if ans < 0:
ans += MOD
print(ans)
``` | vfc_17314 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/327/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1256\n1\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "13990\n2\n",
"output": "528\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "555\n2\n",
"output": "63\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "14\n178\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "27755776656210607832788619414635535178188775623838313967013958143619017005079991285469853503718562504927535176713879737569375166451462839457844835806559098448980069427607\n151\n",
"output": "319271478\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "205831218776360805549796263726315728152440389522084825015113219980083245807721536032762703389\n161\n",
"output": "97770312\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1891 | Solve the following coding problem using the programming language python:
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $2$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $2$, divide the base into $2$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $A$ amount of power, otherwise it takes his $B \cdot n_a \cdot l$ amount of power, where $n_a$ is the number of avengers and $l$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
-----Input-----
The first line contains four integers $n$, $k$, $A$ and $B$ ($1 \leq n \leq 30$, $1 \leq k \leq 10^5$, $1 \leq A,B \leq 10^4$), where $2^n$ is the length of the base, $k$ is the number of avengers and $A$ and $B$ are the constants explained in the question.
The second line contains $k$ integers $a_{1}, a_{2}, a_{3}, \ldots, a_{k}$ ($1 \leq a_{i} \leq 2^n$), where $a_{i}$ represents the position of avenger in the base.
-----Output-----
Output one integer — the minimum power needed to destroy the avengers base.
-----Examples-----
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
-----Note-----
Consider the first example.
One option for Thanos is to burn the whole base $1-4$ with power $2 \cdot 2 \cdot 4 = 16$.
Otherwise he can divide the base into two parts $1-2$ and $3-4$.
For base $1-2$, he can either burn it with power $2 \cdot 1 \cdot 2 = 4$ or divide it into $2$ parts $1-1$ and $2-2$.
For base $1-1$, he can burn it with power $2 \cdot 1 \cdot 1 = 2$. For $2-2$, he can destroy it with power $1$, as there are no avengers. So, the total power for destroying $1-2$ is $2 + 1 = 3$, which is less than $4$.
Similarly, he needs $3$ power to destroy $3-4$. The total minimum power needed is $6$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
ii = lambda: int(input())
mi = lambda: list(map(int, input().split()))
li = lambda: list(mi())
from bisect import bisect_left as lb, bisect_right as ub
n, k, A, B = mi()
a = li()
a.sort()
def f(l, r):
cnt = ub(a, r) - lb(a, l)
if cnt == 0:
return A
if l == r:
return B * cnt
m = (l + r) >> 1
return min(B * cnt * (r - l + 1), f(l, m) + f(m + 1, r))
print(f(1, 2 ** n))
``` | vfc_17318 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1111/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2 1 2\n1 3\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 1 2\n1 7\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 5 1\n7 8\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 7 1\n7 8\n",
"output": "15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 10000 5\n1 4 5\n",
"output": "40\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 5 10000\n1 4 5\n",
"output": "30020\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1892 | Solve the following coding problem using the programming language python:
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
-----Input-----
The first line contains a single integer N (1 ≤ N ≤ 5000) — the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
-----Output-----
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 10^9 + 7.
-----Examples-----
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
-----Note-----
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
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())
dp = [0] * (n + 1)
maxlev = 0
mod = 1000000007
lst = "s"
dp[0] = 1
for i in range(n):
s = input()
if lst == "f":
for j in reversed(range(1, maxlev+2)):
dp[j] = dp[j-1]
maxlev += 1
dp[0] = 0
else:
sum = 0
for j in reversed(range(0, maxlev+1)):
sum = (sum + dp[j]) % mod
dp[j] = sum
lst = s
res = 0
for i in range(0, maxlev + 1):
res = (res + dp[i]) % mod
print(res)
``` | vfc_17322 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/909/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\ns\nf\nf\ns\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\nf\ns\nf\ns\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "156\nf\ns\nf\ns\nf\ns\ns\ns\ns\nf\ns\ns\nf\nf\ns\nf\nf\nf\nf\ns\ns\ns\nf\ns\ns\nf\nf\nf\nf\nf\nf\ns\ns\ns\ns\nf\ns\nf\ns\nf\ns\nf\nf\nf\nf\ns\ns\nf\nf\ns\ns\ns\ns\nf\ns\nf\ns\nf\ns\nf\ns\ns\ns\nf\ns\ns\nf\ns\nf\nf\ns\ns\ns\nf\nf\nf\nf\ns\ns\nf\nf\nf\nf\nf\nf\nf\ns\nf\ns\ns\ns\nf\nf\ns\ns\ns\ns\ns\nf\nf\nf\nf\ns\nf\nf\ns\nf\ns\ns\nf\nf\nf\ns\ns\ns\nf\ns\ns\nf\ns\nf\nf\nf\ns\nf\nf\ns\ns\nf\ns\nf\nf\ns\ns\ns\ns\nf\ns\nf\nf\ns\ns\nf\nf\nf\ns\ns\nf\nf\nf\ns\nf\ns\nf\nf\ns\n",
"output": "666443222\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1893 | Solve the following coding problem using the programming language python:
The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.
Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.
You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times.
-----Input-----
The only line of the input contains a pair of integers n (1000 ≤ n ≤ 10 000) and t (0 ≤ t ≤ 2 000 000 000) — the number of transistors in the initial time and the number of seconds passed since the initial time.
-----Output-----
Output one number — the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10^{ - 6}.
-----Examples-----
Input
1000 1000000
Output
1011.060722383550382782399454922040
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, t = map(int, input().split())
print(n*pow(1.000000011, t))
``` | vfc_17326 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1000 1000000\n",
"output": "1011.060722383550382782399454922040\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000 0\n",
"output": "1000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000 1\n",
"output": "1000.000011000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000 2\n",
"output": "1000.000022000000121000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10000 3\n",
"output": "10000.000330000003630000013310000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10000 2000000000\n",
"output": "35849124123571.66604124267909180280\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1894 | Solve the following coding problem using the programming language python:
Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.
Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right.
Now Joe is on the n-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right.
Joe moves by a particular algorithm. Every second he makes one of the following actions: If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved. Otherwise consider the next cell in the current direction of the gaze. If the cell is empty, then Joe moves into it, the gaze direction is preserved. If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite. If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits).
Joe calms down as soon as he reaches any cell of the first floor.
The figure below shows an example Joe's movements around the house.
[Image]
Determine how many seconds Joe will need to calm down.
-----Input-----
The first line contains two integers n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 10^4).
Next n lines contain the description of Joe's house. The i-th of these lines contains the description of the (n - i + 1)-th floor of the house — a line that consists of m characters: "." means an empty cell, "+" means bricks and "#" means a concrete wall.
It is guaranteed that the first cell of the n-th floor is empty.
-----Output-----
Print a single number — the number of seconds Joe needs to reach the first floor; or else, print word "Never" (without the quotes), if it can never happen.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
3 5
..+.#
#+..+
+.#+.
Output
14
Input
4 10
...+.##+.+
+#++..+++#
++.#++++..
.+##.++#.+
Output
42
Input
2 2
..
++
Output
Never
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 math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n, m = mints()
a = list(minp())
x = 0
t = 0
d = 1
for i in range(n-1):
b = list(minp())
l = x
r = x
wall = 0
while True:
t += 1
if b[x] == '.':
break
if x + d == m or x + d < 0 or a[x+d] == '#':
wall += 1
d = -d
if wall == 2:
print("Never")
return
elif a[x+d] == '+':
wall = 0
a[x+d] = '.'
d = -d
elif l <= x+d and x+d <= r:
if d == 1:
t += r-x-1
x = r
else:
t += x-l-1
x = l
else:
x += d
r = max(r,x)
l = min(l,x)
a, b = b, a
print(t)
``` | vfc_17330 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/250/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5\n..+.#\n#+..+\n+.#+.\n",
"output": "14",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 10\n...+.##+.+\n+#++..+++#\n++.#++++..\n.+##.++#.+\n",
"output": "42",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n..\n++\n",
"output": "Never",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 1\n.\n.\n.\n.\n.\n",
"output": "4",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20 20\n..+#+.+++.+++#+..#++\n..####+++#..++#+.+.+\n+.+..+++..#.++++++++\n+##++..+.##..#+++.++\n++.+.+.+.++++.+++.++\n.+++++.+#+++++...+#+\n.+++#+++++++.+.++.++\n...+.++++++.++#...++\n+++.+++.+....#....+.\n.++++++.+.+..++.++##\n++++++..+.#++..+..+.\n+..#+++++..+##+#++.+\n+.+#+#....+.#+++#+.+\n++.+.+++.++.+.#..#..\n+.+..+++.+.+.++.++++\n..#+++.++.++.#+.+++.\n++++.#.+.+#..+++.+.+\n+..+.+...+....+.....\n#.###++++.+.++.+.+++\n++..+.+.++.+..+.++++\n",
"output": "155",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 100\n.++++.+++++..+++.++++.+++++++++++.++++++++.+++.++++.+++++.+.+++.+++++++++++.+++++++++.+.++++++++++++\n++++++++.++++++.++.++++++++.++.++...+++++++++++++++++++++++++.+++++++.++++++++++++++++++++++++++++.+\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++..++.++++.++++++++.+++++++++++.+++++++++.\n++++++++.+++++++++++.+.+.+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n",
"output": "4930",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1895 | Solve the following coding problem using the programming language python:
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.
Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types:
$1$ — Hiasat can change his handle. $2$ $s$ — friend $s$ visits Hiasat's profile.
The friend $s$ will be happy, if each time he visits Hiasat's profile his handle would be $s$.
Hiasat asks you to help him, find the maximum possible number of happy friends he can get.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n \le 10^5, 1 \le m \le 40$) — the number of events and the number of friends.
Then $n$ lines follow, each denoting an event of one of two types: $1$ — Hiasat can change his handle. $2$ $s$ — friend $s$ ($1 \le |s| \le 40$) visits Hiasat's profile.
It's guaranteed, that each friend's name consists only of lowercase Latin letters.
It's guaranteed, that the first event is always of the first type and each friend will visit Hiasat's profile at least once.
-----Output-----
Print a single integer — the maximum number of happy friends.
-----Examples-----
Input
5 3
1
2 motarack
2 mike
1
2 light
Output
2
Input
4 3
1
2 alice
2 bob
2 tanyaromanova
Output
1
-----Note-----
In the first example, the best way is to change the handle to the "motarack" in the first event and to the "light" in the fourth event. This way, "motarack" and "light" will be happy, but "mike" will not.
In the second example, you can choose either "alice", "bob" or "tanyaromanova" and only that friend will be happy.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import time
n, m =map(int, input().split())
names={None:0}
count={i:0 for i in range(1, m+1)}
a=[0]*(n+1)
for i in range(n):
l=list(input().split())
if l[0]=='2':
if l[1] not in names:
names[l[1]]=len(names)
a[i]=names[l[1]]
count[a[i]]=count[a[i]]+1
# else a[i] stays 0
dense=[set() for _ in range(m+1)]
bulk=set()
# filling dense array of arrays
for i in range(n):
if a[i]==0:
bulk.clear()
continue
if a[i] in bulk: continue
for j in bulk:
dense[j].add(a[i])
dense[a[i]].add(j)
bulk.add(a[i])
res=0
happy=set()
unhappy=set()
mindep=99
independent=set()
dependent=set()
for i in range(1, m+1):
if len(dense[i])==0: independent.add(i)
else:
dependent.add(i)
if len(dense[i])<mindep:
mindep=len(dense[i])
# print([i for i in dependent if mindep==len(dense[i])])
for k in list(dependent):
# iterate to... too sly
happy.clear()
unhappy.clear()
bulk.clear()
bulk.update(dependent)
happy.add(k)
bulk.remove(k)
for j in dense[k]:
if j in bulk:
unhappy.add(j)
bulk.remove(j)
# now making least connected happy
while bulk:
mini = min([len(dense[i]) for i in bulk])
for i in list(bulk):
if len(dense[i])==mini and (i in bulk):
happy.add(i)
bulk.remove(i)
for j in dense[i]:
if j in bulk:
unhappy.add(j)
bulk.remove(j)
continue
res=max(res,len(happy))
print(res+len(independent))
``` | vfc_17334 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1105/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 3\n1\n2 motarack\n2 mike\n1\n2 light\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3\n1\n2 alice\n2 bob\n2 tanyaromanova\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1896 | Solve the following coding problem using the programming language python:
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.
Some of magic effects are able to affect several field cells at once, cells that are situated not farther than n cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.
It is easy to see that the number of cells affected by a magic effect grows rapidly when n increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given n, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than n cells away from a given cell. [Image]
-----Input-----
The only line of the input contains one integer n (0 ≤ n ≤ 10^9).
-----Output-----
Output one integer — the number of hexagons situated not farther than n cells away from a given cell.
-----Examples-----
Input
2
Output
19
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())
print(3*n*(n+1)+1)
``` | vfc_17338 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n",
"output": "19",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "7",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "37",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "749431\n",
"output": "1684942719577",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1897 | Solve the following coding problem using the programming language python:
When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.
Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.
Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.
More formally, let's define the function vowel(c) which is equal to 1, if c is a vowel, and to 0 otherwise. Let s_{i} be the i-th character of string s, and s_{i}..j be the substring of word s, staring at the i-th character and ending at the j-th character (s_{is}_{i} + 1... s_{j}, i ≤ j).
Then the simple prettiness of s is defined by the formula:$\operatorname{simple}(s) = \frac{\sum_{i = 1}^{|s|} \operatorname{vowel}(s_{i})}{|s|}$
The prettiness of s equals $\sum_{1 \leq i \leq j \leq|s|} \operatorname{simple}(s_{i . . j})$
Find the prettiness of the given song title.
We assume that the vowels are I, E, A, O, U, Y.
-----Input-----
The input contains a single string s (1 ≤ |s| ≤ 5·10^5) — the title of the song.
-----Output-----
Print the prettiness of the song with the absolute or relative error of at most 10^{ - 6}.
-----Examples-----
Input
IEAIAIO
Output
28.0000000
Input
BYOB
Output
5.8333333
Input
YISVOWEL
Output
17.0500000
-----Note-----
In the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
arr = []
for i in input():
arr.append(i)
n = len(arr)
res = 0
add = [0] * (n + 10)
add[n] = 1 / n
for i in range(n - 1, 0, -1):
add[i] = add[i + 1] + 1 / i
for i in range(n):
if arr[i] in ['I', 'E', 'A', 'O', 'U', 'Y']:
x = min(i, n - i - 1)
y = max(i, n - i - 1)
res += x + 1
res += (x + 1) * (add[x + 2] - add[y + 1])
res += (n + 1) * add[y + 1] - (n - y)
print(res)
``` | vfc_17342 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/509/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "IEAIAIO\n",
"output": "28.0000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "BYOB\n",
"output": "5.8333333\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1898 | Solve the following coding problem using the programming language python:
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...
For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.
Please help Dr. Banner.
-----Input-----
The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.
-----Output-----
Print Dr.Banner's feeling in one line.
-----Examples-----
Input
1
Output
I hate it
Input
2
Output
I hate that I love it
Input
3
Output
I hate that I love that I hate it
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(1,n):
if i%2 == 1:
print('I hate that',end=' ')
else:
print('I love that',end=' ')
if n%2 == 1:
print('I hate it',end=' ')
else:
print('I love it',end=' ')
``` | vfc_17346 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/705/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n",
"output": "I hate it\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "I hate that I love it\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "I hate that I love that I hate it\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1900 | Solve the following coding problem using the programming language python:
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city a_{i}.
Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence a_1, a_2, ..., a_{n} repeated m times).
After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city.
Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected.
-----Input-----
The first line contains three integers n, k and m (1 ≤ n ≤ 10^5, 2 ≤ k ≤ 10^9, 1 ≤ m ≤ 10^9).
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5), where a_{i} is the number of city, person from which must take seat i in the bus.
-----Output-----
Output the number of remaining participants in the line.
-----Examples-----
Input
4 2 5
1 2 3 1
Output
12
Input
1 9 10
1
Output
1
Input
3 2 10
1 2 1
Output
0
-----Note-----
In the second example, the line consists of ten participants from the same city. Nine of them will form a team. At the end, only one participant will stay in the line.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
_, k, m = [int(x) for x in input().split()]
a = []
last = ("-1", 0)
a.append(last)
for ai in input().split():
if last[0] == ai:
last = (ai, last[1]+1)
a[-1] = last
else:
last = (ai, 1)
a.append(last)
if last[1] == k:
a.pop()
last = a[-1]
a.pop(0)
s1 = 0
while len(a) > 0 and a[0][0] == a[-1][0]:
if len(a) == 1:
s = a[0][1] * m
r1 = s % k
if r1 == 0:
print(s1 % k)
else:
print(r1 + s1)
return
join = a[0][1] + a[-1][1]
if join < k:
break
elif join % k == 0:
s1 += join
a.pop()
a.pop(0)
else:
s1 += (join // k) * k
a[0] = (a[0][0], join % k)
a.pop()
break
s = 0
for ai in a:
s += ai[1]
print(s*m + s1)
def __starting_point():
main()
__starting_point()
``` | vfc_17354 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/879/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2 5\n1 2 3 1\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 9 10\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 10\n1 2 1\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1902 | Solve the following coding problem using the programming language python:
Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor.
Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces».
With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols?
A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.».
-----Input-----
The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·10^5. It's guaranteed that all lines are non-empty.
-----Output-----
Print a single integer — the minimum number of clicks.
-----Examples-----
Input
snow affects sports such as skiing, snowboarding, and snowmachine travel.
snowboarding is a recreational activity and olympic and paralympic sport.
Output
141
Input
'co-co-co, codeforces?!'
Output
25
Input
thun-thun-thunder, thunder, thunder
thunder, thun-, thunder
thun-thun-thunder, thunder
thunder, feel the thunder
lightning then the thunder
thunder, feel the thunder
lightning then the thunder
thunder, thunder
Output
183
-----Note-----
In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks.
In sample case two it doesn't matter whether to use autocompletion or not.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
class Ddict:
def __init__(self):
self.dicts={}
def add(self,key):
d=self.dicts
for i in key:
if i not in d:
d[i]={}
d=d[i]
d[' ']=''
def find(self,key):
if key=='':
return '',''
d=self.dicts
q=[]
h=[key[0]]
for i in key:
if i not in d:
if ' ' in d and len(d)==1:
return ''.join(q),''.join(h)
return '',''
q.append(i)
if len(d)!=1:
h=q[:]
d=d[i]
if ' ' in d and len(d)==1:
return ''.join(q),''.join(h)
return '',''
words = Ddict()
ans=0
while True:
try:
x=input()
if not x:
break
except:
break
ans+=len(x)+1
ws=[[]]
for i in x:
if i in '.,?!\'- ':
if ws[-1]:
ws.append([])
else:
ws[-1].append(i)
ws=list([''.join(e) for e in ws])
for w in ws:
next_word,helped_word = words.find(w)
if next_word and next_word!=helped_word:
ans-=len(next_word)-len(helped_word)-1
words.add(w)
print(ans)
``` | vfc_17362 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/928/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "snow affects sports such as skiing, snowboarding, and snowmachine travel.\nsnowboarding is a recreational activity and olympic and paralympic sport.\n",
"output": "141\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "'co-co-co, codeforces?!'\n",
"output": "25\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "thun-thun-thunder, thunder, thunder\nthunder, thun-, thunder\nthun-thun-thunder, thunder\nthunder, feel the thunder\nlightning then the thunder\nthunder, feel the thunder\nlightning then the thunder\nthunder, thunder\n",
"output": "183\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "a'b-c-aa'ab.ac.ba!bb-bc-ca?cb-cc.aaa,aab'aac'aba-abb'abc-aca.acb!acc?baa'bab'bac!bba-bbb.bbc.bca\n",
"output": "97\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1903 | Solve the following coding problem using the programming language python:
Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters — its significance c_{i} and width w_{i}.
Stepan decided to expose some of his cups on a shelf with width d in such a way, that: there is at least one Physics cup and at least one Informatics cup on the shelf, the total width of the exposed cups does not exceed d, from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too).
Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups.
-----Input-----
The first line contains three integers n, m and d (1 ≤ n, m ≤ 100 000, 1 ≤ d ≤ 10^9) — the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf.
Each of the following n lines contains two integers c_{i} and w_{i} (1 ≤ c_{i}, w_{i} ≤ 10^9) — significance and width of the i-th cup for Physics olympiads.
Each of the following m lines contains two integers c_{j} and w_{j} (1 ≤ c_{j}, w_{j} ≤ 10^9) — significance and width of the j-th cup for Informatics olympiads.
-----Output-----
Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement.
If there is no way to expose cups on the shelf, then print 0.
-----Examples-----
Input
3 1 8
4 2
5 5
4 2
3 2
Output
8
Input
4 3 12
3 4
2 4
3 5
3 4
3 5
5 2
3 4
Output
11
Input
2 2 2
5 3
6 3
4 2
8 1
Output
0
-----Note-----
In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m, d = list(map(int, input().split()))
a = []
b = []
for i in range(n):
a.append(list(map(int, input().split())))
for i in range(m):
b.append(list(map(int, input().split())))
a = sorted(a, key=lambda x: x[0] + (1- x[1] * 1e-10))
b = sorted(b, key=lambda x: x[0] + (1- x[1] * 1e-10))
tc, td = 0, 0
tc += a[-1][0]
tc += b[-1][0]
td += a[-1][1]
td += b[-1][1]
ai = n - 1
bi = m - 1
if td > d:
print(0)
return
while ai > 0:
t = ai - 1
if td + a[t][1] <= d:
td += a[t][1]
tc += a[t][0]
ai -= 1
continue
else:
break
cmax = tc
while bi > 0:
bi -= 1
tc += b[bi][0]
td += b[bi][1]
while td > d and ai < n:
tc -= a[ai][0]
td -= a[ai][1]
ai += 1
if ai == n:
break
if td <= d:
cmax = max(cmax, tc)
print(cmax)
``` | vfc_17366 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/774/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 1 8\n4 2\n5 5\n4 2\n3 2\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3 12\n3 4\n2 4\n3 5\n3 4\n3 5\n5 2\n3 4\n",
"output": "11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2 2\n5 3\n6 3\n4 2\n8 1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10 229\n15 17\n5 4\n4 15\n4 17\n15 11\n7 6\n5 19\n14 8\n4 1\n10 12\n20 13\n20 14\n16 13\n7 15\n2 16\n11 11\n19 20\n6 7\n4 11\n14 16\n",
"output": "198\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 20 498\n40 12\n23 25\n20 9\n8 1\n23 8\n31 24\n33 2\n22 33\n4 13\n25 20\n40 5\n27 5\n17 6\n8 5\n4 19\n33 23\n30 19\n27 12\n13 22\n16 32\n28 36\n20 18\n36 38\n9 24\n21 35\n20 9\n33 29\n29 33\n18 25\n11 8\n",
"output": "644\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1905 | Solve the following coding problem using the programming language python:
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.
That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.
Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.
Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
-----Input-----
The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 100, 1 ≤ q ≤ 10 000) — dimensions of the matrix and the number of turns in the experiment, respectively.
Next q lines contain turns descriptions, one per line. Each description starts with an integer t_{i} (1 ≤ t_{i} ≤ 3) that defines the type of the operation. For the operation of first and second type integer r_{i} (1 ≤ r_{i} ≤ n) or c_{i} (1 ≤ c_{i} ≤ m) follows, while for the operations of the third type three integers r_{i}, c_{i} and x_{i} (1 ≤ r_{i} ≤ n, 1 ≤ c_{i} ≤ m, - 10^9 ≤ x_{i} ≤ 10^9) are given.
Operation of the first type (t_{i} = 1) means that signal comes to the input corresponding to row r_{i}, that is it will shift cyclically. Operation of the second type (t_{i} = 2) means that column c_{i} will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row r_{i} and column c_{i} stores value x_{i}.
-----Output-----
Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 10^9 by their absolute value.
If there are multiple valid solutions, output any of them.
-----Examples-----
Input
2 2 6
2 1
2 2
3 1 1 1
3 2 2 2
3 1 2 8
3 2 1 8
Output
8 2
1 8
Input
3 3 2
1 2
3 2 2 5
Output
0 0 0
0 0 5
0 0 0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
nmq = input().split(' ')
n, m, q = int(nmq[0]), int(nmq[1]), int(nmq[2])
mt = []
for i in range(0, n):
mt.append([])
for j in range(0, m):
mt[-1].append((i, j))
res = []
for i in range(0, n):
res.append([])
for j in range(0, m):
res[-1].append(0)
for i in range(0, q):
ins = input().split(' ')
if ins[0] == '1':
r = int(ins[1]) - 1
b = mt[r][0]
for j in range(0, m-1):
mt[r][j] = mt[r][j+1]
mt[r][m-1] = b
if ins[0] == '2':
c = int(ins[1]) - 1
b = mt[0][c]
for j in range(0, n-1):
mt[j][c] = mt[j+1][c]
mt[n-1][c] = b
if ins[0] == '3':
r = int(ins[1]) - 1
c = int(ins[2]) - 1
x = int(ins[3])
p = mt[r][c]
res[p[0]][p[1]] = x
for i in range(0, n):
for j in range(0, m-1):
print(res[i][j],' ', end='')
print(res[i][-1])
``` | vfc_17374 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/641/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2 6\n2 1\n2 2\n3 1 1 1\n3 2 2 2\n3 1 2 8\n3 2 1 8\n",
"output": "8 2 \n1 8 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 2\n1 2\n3 2 2 5\n",
"output": "0 0 0 \n0 0 5 \n0 0 0 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5 1\n1 5\n",
"output": "0 0 0 0 0 \n0 0 0 0 0 \n0 0 0 0 0 \n0 0 0 0 0 \n0 0 0 0 0 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 3\n1 1\n2 1\n3 1 1 1000000000\n",
"output": "1000000000 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 3\n1 1\n2 1\n3 1 1 -1000000000\n",
"output": "-1000000000 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2 6\n2 1\n2 2\n3 1 1 -1\n3 2 2 -1\n3 1 2 -1\n3 2 1 -1\n",
"output": "-1 -1 \n-1 -1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1906 | Solve the following coding problem using the programming language python:
IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible by any number from 2 to 10 every developer of this game gets a small bonus.
A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that n people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.
-----Input-----
The only line of the input contains one integer n (1 ≤ n ≤ 10^18) — the prediction on the number of people who will buy the game.
-----Output-----
Output one integer showing how many numbers from 1 to n are not divisible by any number from 2 to 10.
-----Examples-----
Input
12
Output
2
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = [2, 3 ,5, 7]
ans = 0
import operator
import itertools
import functools
for i in range(1, 5):
for p in itertools.combinations(a, i):
x = functools.reduce(operator.mul, p)
ans += (-1) ** (i + 1) * (n // x)
print(n - ans)
``` | vfc_17378 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/K",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "12\n",
"output": "2",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1907 | Solve the following coding problem using the programming language python:
The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?
The discotheque can be seen as an infinite xy-plane, in which there are a total of n dancers. Once someone starts moving around, they will move only inside their own movement range, which is a circular area C_{i} described by a center (x_{i}, y_{i}) and a radius r_{i}. No two ranges' borders have more than one common point, that is for every pair (i, j) (1 ≤ i < j ≤ n) either ranges C_{i} and C_{j} are disjoint, or one of them is a subset of the other. Note that it's possible that two ranges' borders share a single common point, but no two dancers have exactly the same ranges.
Tsukihi, being one of them, defines the spaciousness to be the area covered by an odd number of movement ranges of dancers who are moving. An example is shown below, with shaded regions representing the spaciousness if everyone moves at the same time. [Image]
But no one keeps moving for the whole night after all, so the whole night's time is divided into two halves — before midnight and after midnight. Every dancer moves around in one half, while sitting down with friends in the other. The spaciousness of two halves are calculated separately and their sum should, of course, be as large as possible. The following figure shows an optimal solution to the example above. [Image]
By different plans of who dances in the first half and who does in the other, different sums of spaciousness over two halves are achieved. You are to find the largest achievable value of this sum.
-----Input-----
The first line of input contains a positive integer n (1 ≤ n ≤ 1 000) — the number of dancers.
The following n lines each describes a dancer: the i-th line among them contains three space-separated integers x_{i}, y_{i} and r_{i} ( - 10^6 ≤ x_{i}, y_{i} ≤ 10^6, 1 ≤ r_{i} ≤ 10^6), describing a circular movement range centered at (x_{i}, y_{i}) with radius r_{i}.
-----Output-----
Output one decimal number — the largest achievable sum of spaciousness over two halves of the night.
The output is considered correct if it has a relative or absolute error of at most 10^{ - 9}. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if $\frac{|a - b|}{\operatorname{max}(1,|b|)} \leq 10^{-9}$.
-----Examples-----
Input
5
2 1 6
0 4 1
2 -1 3
1 -2 1
4 -1 1
Output
138.23007676
Input
8
0 0 1
0 0 2
0 0 3
0 0 4
0 0 5
0 0 6
0 0 7
0 0 8
Output
289.02652413
-----Note-----
The first sample corresponds to the illustrations in the legend.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
def inside(a,b):
return ((a[0]-b[0])**2 + (a[1]-b[1])**2) < (a[2]+b[2])**2
def main():
pi = 3.14159265358979323
n = int(sys.stdin.readline())
a = []
p = [-1]*n
for i in range(n):
x,y,r = map(int,sys.stdin.readline().split())
a.append([x,y,r])
for i in range(n):
for j in range(n):
if i==j :
continue
if inside(a[i],a[j]):
if a[i][2] < a[j][2]:
if p[i] == -1:
p[i] = j
elif a[p[i]][2]>a[j][2]:
p[i] = j
else:
if p[j] == -1:
p[j] = i
elif a[p[j]][2]>a[i][2]:
p[j] = i
q = []
for i in range(n):
if p[i] == -1:
q.append((i,True))
s = len(q)
ans = 0.0
for i in range(s):
c, b = q[i]
for j in range(n):
if p[j] == c:
q.append((j,True))
ans+= pi * a[c][2] * a[c][2]
q = q[s:]
while len(q)!=0 :
c,b = q.pop()
for j in range(n):
if p[j] == c:
q.append((j,not b))
if b:
ans+= pi * a[c][2] * a[c][2]
else:
ans-= pi * a[c][2] * a[c][2]
print(ans)
main()
``` | vfc_17382 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/814/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n2 1 6\n0 4 1\n2 -1 3\n1 -2 1\n4 -1 1\n",
"output": "138.23007676\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n0 0 1\n0 0 2\n0 0 3\n0 0 4\n0 0 5\n0 0 6\n0 0 7\n0 0 8\n",
"output": "289.02652413\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1909 | Solve the following coding problem using the programming language python:
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.
Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.
Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.
-----Input-----
The first line of the input contains two integers n, k (1 ≤ k ≤ n ≤ 10^5). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^3), where a_{i} is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task.
It is guaranteed that n is divisible by k.
-----Output-----
In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.
-----Examples-----
Input
6 2
3 2 1 6 5 4
Output
1
Input
10 5
1 3 5 7 9 9 4 1 8 5
Output
3
-----Note-----
Explanation of the first example.
If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12.
Explanation of the second example.
In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,k=list(map(int,input().split()))
A=list(map(int,input().split()))
L=[]
for i in range(k):
s=0
for j in range(i,n,k):
s+=A[j]
L.append(s)
x=min(L)
print(L.index(x)+1)
``` | vfc_17390 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/366/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 2\n3 2 1 6 5 4\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1910 | Solve the following coding problem using the programming language python:
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.
The parking lot before the office consists of one line of (2n - 2) parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever.
Looking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly n successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way.
-----Input-----
The only line of the input contains one integer n (3 ≤ n ≤ 30) — the amount of successive cars of the same make.
-----Output-----
Output one integer — the number of ways to fill the parking lot by cars of four makes using the described way.
-----Examples-----
Input
3
Output
24
-----Note-----
Let's denote car makes in the following way: A — Aston Martin, B — Bentley, M — Mercedes-Maybach, Z — Zaporozhets. For n = 3 there are the following appropriate ways to fill the parking lot: AAAB AAAM AAAZ ABBB AMMM AZZZ BBBA BBBM BBBZ BAAA BMMM BZZZ MMMA MMMB MMMZ MAAA MBBB MZZZ ZZZA ZZZB ZZZM ZAAA ZBBB ZMMM
Originally it was planned to grant sport cars of Ferrari, Lamborghini, Maserati and Bugatti makes but this idea was renounced because it is impossible to drive these cars having small road clearance on the worn-down roads of IT City.
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())
print(4 * ((n - 3) * 3 * 3 * 4 ** max(0, n - 4) + 2 * 3 * 4 ** (n - 3)))
``` | vfc_17394 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/I",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n",
"output": "24",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "132",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "672",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n",
"output": "3264",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n",
"output": "15360",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "12\n",
"output": "27525120",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1912 | Solve the following coding problem using the programming language python:
Boboniu gives you
$r$ red balls, $g$ green balls, $b$ blue balls, $w$ white balls.
He allows you to do the following operation as many times as you want:
Pick a red ball, a green ball, and a blue ball and then change their color to white.
You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations.
-----Input-----
The first line contains one integer $T$ ($1\le T\le 100$) denoting the number of test cases.
For each of the next $T$ cases, the first line contains four integers $r$, $g$, $b$ and $w$ ($0\le r,g,b,w\le 10^9$).
-----Output-----
For each test case, print "Yes" if it's possible to arrange all the balls into a palindrome after doing several (possibly zero) number of described operations. Otherwise, print "No".
-----Example-----
Input
4
0 1 1 1
8 1 9 3
0 0 0 0
1000000000 1000000000 1000000000 1000000000
Output
No
Yes
Yes
Yes
-----Note-----
In the first test case, you're not able to do any operation and you can never arrange three balls of distinct colors into a palindrome.
In the second test case, after doing one operation, changing $(8,1,9,3)$ to $(7,0,8,6)$, one of those possible palindromes may be "rrrwwwbbbbrbbbbwwwrrr".
A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. For example, "rggbwbggr", "b", "gg" are palindromes while "rgbb", "gbbgr" are not. Notice that an empty word, phrase, or sequence is palindrome.
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())
while t:
arr = list(map(int, input().split()))
c = 0
for i in arr:
if i % 2 == 1:
c += 1
if c <= 1:
print("Yes")
else:
if arr[0] and arr[1] and arr[2]:
arr[3] += 3
arr[0] -= 1
arr[1] -= 1
arr[2] -= 1
c = 0
for i in arr:
if i % 2 == 1:
c += 1
if c <= 1:
print("Yes")
else:
print("No")
else:
print("No")
t -= 1
``` | vfc_17402 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1395/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n0 1 1 1\n8 1 9 3\n0 0 0 0\n1000000000 1000000000 1000000000 1000000000\n",
"output": "No\nYes\nYes\nYes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2 0 0 0\n",
"output": "Yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n0 2 2 3\n",
"output": "Yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3 0 3 3\n",
"output": "No\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 1 0 101\n",
"output": "No\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n0 0 1 2\n",
"output": "Yes\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1913 | Solve the following coding problem using the programming language python:
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!
There are exactly n distinct countries in the world and the i-th country added a_{i} tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.
Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
-----Input-----
The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers a_{i} without leading zeroes — the number of tanks of the i-th country.
It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000.
-----Output-----
Print a single number without leading zeroes — the product of the number of tanks presented by each country.
-----Examples-----
Input
3
5 10 1
Output
50
Input
4
1 1 10 11
Output
110
Input
5
0 3 1 100 1
Output
0
-----Note-----
In sample 1 numbers 10 and 1 are beautiful, number 5 is not not.
In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.
In sample 3 number 3 is not beautiful, all others are beautiful.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# import sys
# sys.stdin = open('cf614b.in', 'r')
import re
p = re.compile(r'^10*$')
n = int(input())
a = input().split()
extra = '1'
numzero = 0
for ai in a:
if ai == '0':
print(0)
return
elif p.match(ai):
numzero += len(ai) - 1
else:
extra = ai
print(extra + '0' * numzero)
``` | vfc_17406 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/614/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n5 10 1\n",
"output": "50",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 1 10 11\n",
"output": "110",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n0 3 1 100 1\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "40\n10 100 10 1 10 10 100 10 10 100 10 100 100 10 1824868942 100 100 1 10 100 100 10 100 100 10 100 10 1 10 100 100 100 10 1 10 1 10 10 100 100\n",
"output": "1824868942000000000000000000000000000000000000000000000000000",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n1000000000000000000000000000000000000 6643573784 1000000000000000000000000000000000000 1000000000000000000000000000000000000 1000000000000000000000000000000000000 1000000000000000000000000000000000000\n",
"output": "6643573784000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n0\n",
"output": "0",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1914 | Solve the following coding problem using the programming language python:
You are given a string $t$ and $n$ strings $s_1, s_2, \dots, s_n$. All strings consist of lowercase Latin letters.
Let $f(t, s)$ be the number of occurences of string $s$ in string $t$. For example, $f('\text{aaabacaa}', '\text{aa}') = 3$, and $f('\text{ababa}', '\text{aba}') = 2$.
Calculate the value of $\sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j)$, where $s + t$ is the concatenation of strings $s$ and $t$. Note that if there are two pairs $i_1$, $j_1$ and $i_2$, $j_2$ such that $s_{i_1} + s_{j_1} = s_{i_2} + s_{j_2}$, you should include both $f(t, s_{i_1} + s_{j_1})$ and $f(t, s_{i_2} + s_{j_2})$ in answer.
-----Input-----
The first line contains string $t$ ($1 \le |t| \le 2 \cdot 10^5$).
The second line contains integer $n$ ($1 \le n \le 2 \cdot 10^5$).
Each of next $n$ lines contains string $s_i$ ($1 \le |s_i| \le 2 \cdot 10^5$).
It is guaranteed that $\sum\limits_{i=1}^{n} |s_i| \le 2 \cdot 10^5$. All strings consist of lowercase English letters.
-----Output-----
Print one integer — the value of $\sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j)$.
-----Examples-----
Input
aaabacaa
2
a
aa
Output
5
Input
aaabacaa
4
a
a
a
b
Output
33
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
class Node(object):
def __init__(self):
super(Node, self).__init__()
self.next = [-1] * 26
self.trans = []
self.matches = 0
self.leaf = 0
self.link = 0
class AhoCorasick(object):
def __init__(self):
super(AhoCorasick, self).__init__()
self.T = [Node()]
self.T[0].link = 0
def insert_trie(self, s):
v = 0
for i in range(len(s)):
c = ord(s[i]) - ord('a')
if(self.T[v].next[c] == -1):
self.T[v].trans.append(c)
self.T[v].next[c] = len(self.T)
self.T.append(Node())
v = self.T[v].next[c]
self.T[v].leaf += 1
self.T[v].matches += 1
def set_suffix_link(self, S):
Q = []
for j in range(len(S)):
Q.append((j, 0, 0, 0))
#string index, index in string, state, suff state,
i = 0
while(i < len(Q)):
j,ind,v,suff = Q[i]
i += 1
c = ord(S[j][ind]) - ord('a')
if(ind>0):
while(suff>0 and self.T[suff].next[c]==-1):
suff = self.T[suff].link
if(self.T[suff].next[c] != -1):
suff = self.T[suff].next[c]
v = self.T[v].next[c]
self.T[v].link = suff
if(ind+1 < len(S[j])):
Q.append((j,ind+1,v,suff))
def set_matches(self):
i = 0
Q = [0]
while(i < len(Q)):
v = Q[i]
self.T[v].matches = self.T[v].leaf + self.T[self.T[v].link].matches
for c in self.T[v].trans:
Q.append(self.T[v].next[c])
i += 1
def build(self, S):
for i in range(len(S)):
self.insert_trie(S[i])
self.set_suffix_link(S)
#self.printTree()
self.set_matches()
def get(self, s):
v = 0
matches = []
for i in range(len(s)):
c = ord(s[i]) - ord('a')
while(v>0 and self.T[v].next[c] == -1):
v = self.T[v].link
if(self.T[v].next[c] != -1):
v = self.T[v].next[c]
matches.append(self.T[v].matches)
return matches
def printTree(self):
for i in range(len(self.T)):
print(str(i)+" leaf:"+str(self.T[i].leaf)+" link:"+str(self.T[i].link)+" matches:"+str(self.T[i].matches)+" : " , end='')
for j in range(26):
print(" "+str(chr(j+ord('a')))+"-"+(str(self.T[i].next[j]) if (self.T[i].next[j]!=-1) else "_")+" ", end='')
print()
t = input()
n = int(input())
patterns = []
patterns_rev = []
for i in range(n):
s = input()
patterns.append(s)
patterns_rev.append(s[::-1])
t1 = AhoCorasick()
t2 = AhoCorasick()
t1.build(patterns)
t2.build(patterns_rev)
x1 = t1.get(t)
x2 = t2.get(t[::-1])[::-1]
#print(x1)
#print(x2)
ans = 0
for i in range(len(x1)-1):
ans += x1[i] * x2[i+1]
print(ans)
``` | vfc_17410 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1202/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "aaabacaa\n2\na\naa\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aaabacaa\n4\na\na\na\nb\n",
"output": "33\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "abacabadabacaba\n22\na\nb\nc\nd\naba\naca\nabacabadabacaba\naa\ndab\nac\nca\nba\nab\nad\nda\nabacaba\nabacaba\nabacabad\nabacabad\ndabacaba\ndabacaba\nabacabadabacabaa\n",
"output": "108\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aa\n7\na\naa\naaa\naaaa\naaaaa\naaaaaa\naaaaaaa\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1915 | Solve the following coding problem using the programming language python:
An n × n table a is defined as follows:
The first row and the first column contain ones, that is: a_{i}, 1 = a_{1, }i = 1 for all i = 1, 2, ..., n. Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula a_{i}, j = a_{i} - 1, j + a_{i}, j - 1.
These conditions define all the values in the table.
You are given a number n. You need to determine the maximum value in the n × n table defined by the rules above.
-----Input-----
The only line of input contains a positive integer n (1 ≤ n ≤ 10) — the number of rows and columns of the table.
-----Output-----
Print a single line containing a positive integer m — the maximum value in the table.
-----Examples-----
Input
1
Output
1
Input
5
Output
70
-----Note-----
In the second test the rows of the table look as follows: {1, 1, 1, 1, 1}, {1, 2, 3, 4, 5}, {1, 3, 6, 10, 15}, {1, 4, 10, 20, 35}, {1, 5, 15, 35, 70}.
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 = [[1] * n for i in range(n)]
for i in range(1, n):
for j in range(1, n):
a[i][j] = a[i - 1][j] + a[i][j - 1]
print(a[n - 1][n - 1])
``` | vfc_17414 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/509/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "70",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "6",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "20",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n",
"output": "252",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1916 | Solve the following coding problem using the programming language python:
Boboniu likes bit operations. He wants to play a game with you.
Boboniu gives you two sequences of non-negative integers $a_1,a_2,\ldots,a_n$ and $b_1,b_2,\ldots,b_m$.
For each $i$ ($1\le i\le n$), you're asked to choose a $j$ ($1\le j\le m$) and let $c_i=a_i\& b_j$, where $\&$ denotes the bitwise AND operation. Note that you can pick the same $j$ for different $i$'s.
Find the minimum possible $c_1 | c_2 | \ldots | c_n$, where $|$ denotes the bitwise OR operation.
-----Input-----
The first line contains two integers $n$ and $m$ ($1\le n,m\le 200$).
The next line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($0\le a_i < 2^9$).
The next line contains $m$ integers $b_1,b_2,\ldots,b_m$ ($0\le b_i < 2^9$).
-----Output-----
Print one integer: the minimum possible $c_1 | c_2 | \ldots | c_n$.
-----Examples-----
Input
4 2
2 6 4 0
2 4
Output
2
Input
7 6
1 9 1 9 8 1 0
1 1 4 5 1 4
Output
0
Input
8 5
179 261 432 162 82 43 10 38
379 357 202 184 197
Output
147
-----Note-----
For the first example, we have $c_1=a_1\& b_2=0$, $c_2=a_2\& b_1=2$, $c_3=a_3\& b_1=0$, $c_4 = a_4\& b_1=0$.Thus $c_1 | c_2 | c_3 |c_4 =2$, and this is the minimal answer we can get.
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()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
possible = [[] for i in range(n)]
for i in range(n):
for j in range(m):
possible[i].append(a[i] & b[j])
import sys
for answer in range(2 ** 9):
answer_flag = 1
for i in range(n):
flag = 0
for x in possible[i]:
if answer | x == answer:
flag = 1
break
if flag == 0:
answer_flag = 0
break
if answer_flag:
print(answer)
return
``` | vfc_17418 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1395/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2\n2 6 4 0\n2 4\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 6\n1 9 1 9 8 1 0\n1 1 4 5 1 4\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8 5\n179 261 432 162 82 43 10 38\n379 357 202 184 197\n",
"output": "147",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n119\n395\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15 20\n481 473 132 353 449 2 140 216 145 159 453 511 275 245 421\n197 149 377 395 11 77 473 452 203 61 468 35 64 282 110 501 170 331 400 147\n",
"output": "11",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 16\n241 430 17 294 131 242 230 221 103\n355 374 171 445 329 375 167 102 11 177 449 160 326 396 124 390\n",
"output": "11",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1917 | Solve the following coding problem using the programming language python:
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)
You have completed many programming projects. In fact, there are exactly $n$ types of programming projects, and you have completed $a_i$ projects of type $i$. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.
You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:
$$ f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). $$
Here, $b_i$ denotes the number of projects of type $i$ you include in your résumé. Of course, you cannot include more projects than you have completed, so you require $0\le b_i \le a_i$ for all $i$.
Your résumé only has enough room for $k$ projects, and you will absolutely not be hired if your résumé has empty space, so you require $\sum\limits_{i=1}^n b_i=k$.
Find values for $b_1,\ldots, b_n$ that maximize the value of $f(b_1,\ldots,b_n)$ while satisfying the above two constraints.
-----Input-----
The first line contains two integers $n$ and $k$ ($1\le n\le 10^5$, $1\le k\le \sum\limits_{i=1}^n a_i$) — the number of types of programming projects and the résumé size, respectively.
The next line contains $n$ integers $a_1,\ldots,a_n$ ($1\le a_i\le 10^9$) — $a_i$ is equal to the number of completed projects of type $i$.
-----Output-----
In a single line, output $n$ integers $b_1,\ldots, b_n$ that achieve the maximum value of $f(b_1,\ldots,b_n)$, while satisfying the requirements $0\le b_i\le a_i$ and $\sum\limits_{i=1}^n b_i=k$. If there are multiple solutions, output any.
Note that you do not have to output the value $f(b_1,\ldots,b_n)$.
-----Examples-----
Input
10 32
1 2 3 4 5 5 5 5 5 5
Output
1 2 3 3 3 4 4 4 4 4
Input
5 8
4 4 8 2 1
Output
2 2 2 1 1
-----Note-----
For the first test, the optimal answer is $f=-269$. Note that a larger $f$ value is possible if we ignored the constraint $\sum\limits_{i=1}^n b_i=k$.
For the second test, the optimal answer is $f=9$.
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 as hq
readline = sys.stdin.readline
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
eps = 10**-7
def solve():
n, k = nm()
a = nl()
ans = [0]*n
ok = 10**9; ng = -4*10**18
while ok - ng > 1:
mid = (ok + ng) // 2
ck = 0
for i in range(n):
d = 9 - 12 * (mid + 1 - a[i])
if d < 0:
continue
ck += min(a[i], int((3 + d**.5) / 6 + eps))
# print(mid, ck)
if ck > k:
ng = mid
else:
ok = mid
for i in range(n):
d = 9 - 12 * (ok + 1 - a[i])
if d < 0:
continue
ans[i] = min(a[i], int((3 + d**.5) / 6 + eps))
# print(ans)
rk = k - sum(ans)
l = list()
for i in range(n):
if ans[i] < a[i]:
hq.heappush(l, (-a[i] + 3 * ans[i]**2 - 3 * ans[i] + 1, i))
for _ in range(rk):
v, i = hq.heappop(l)
ans[i] += 1
if ans[i] < a[i]:
hq.heappush(l, (-a[i] + 3 * ans[i]**2 - 3 * ans[i] + 1, i))
print(*ans)
return
solve()
``` | vfc_17422 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1345/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 32\n1 2 3 4 5 5 5 5 5 5\n",
"output": "1 2 3 3 3 4 4 4 4 4 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 8\n4 4 8 2 1\n",
"output": "2 2 2 1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 353\n191 148 145 73 150\n",
"output": "71 71 70 70 71 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 12436\n827 238 69 955 468 828 762 562 285 690 406 39 814 447 871 560 224 677 65 764 864 827 659 43 512 547 619 313 206 605 446 471 980 115 561 746 150 787 963 426 239 984 752 212 732 977 831 521 943 921 661 221 133 309 897 113 265 873 85 89 799 492 459 110 417 423 190 885 886 465 653 950 6 990 851 62 327 235 410 45 939 660 139 33 64 767 151 737 334 414 513 83 509 561 122 759 68 170 516 402\n",
"output": "136 135 69 136 135 136 135 135 135 135 135 39 136 135 136 135 135 135 65 135 136 136 135 43 135 135 135 135 135 135 135 135 136 115 135 135 135 135 136 135 135 136 135 135 135 136 136 135 136 136 135 135 133 135 136 113 135 136 85 89 135 135 135 110 135 135 135 136 136 135 135 136 6 136 136 62 135 135 135 45 136 135 135 33 64 135 135 135 135 135 135 83 135 135 122 135 68 135 135 135 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1918 | Solve the following coding problem using the programming language python:
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength p_{i}.
The way to split up game pieces is split into several steps:
First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 5·10^5) — the number of game pieces.
The second line contains n integers p_{i} (1 ≤ p_{i} ≤ 10^9) — the strength of the i-th piece.
The third line contains n characters A or B — the assignment of teams after the first step (after Alice's step).
-----Output-----
Print the only integer a — the maximum strength Bob can achieve.
-----Examples-----
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
-----Note-----
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = input()
s = [int(x) for x in input().split(' ')]
g = input()
A = 0
B = 0
for i in range(len(g)):
if g[i] == 'A':
A += s[i]
else:
B += s[i]
startA, startB = A, B
maximum = B
for i in range(len(g)):
if g[i] == 'A':
A -= s[i]
B += s[i]
else:
A += s[i]
B -= s[i]
if B > maximum:
maximum = B
A, B = startA, startB
for i in reversed(range(len(g))):
if g[i] == 'A':
A -= s[i]
B += s[i]
else:
A += s[i]
B -= s[i]
if B > maximum:
maximum = B
print(maximum)
``` | vfc_17426 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/632/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 3 4 5\nABABA\n",
"output": "11\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1919 | Solve the following coding problem using the programming language python:
There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor.
The game is played on a square field consisting of n × n cells. Initially all cells are empty. On each turn a player chooses and paint an empty cell that has no common sides with previously painted cells. Adjacent corner of painted cells is allowed. On the next turn another player does the same, then the first one and so on. The player with no cells to paint on his turn loses.
The professor have chosen the field size n and allowed the student to choose to be the first or the second player in the game. What should the student choose to win the game? Both players play optimally.
-----Input-----
The only line of the input contains one integer n (1 ≤ n ≤ 10^18) — the size of the field.
-----Output-----
Output number 1, if the player making the first turn wins when both players play optimally, otherwise print number 2.
-----Examples-----
Input
1
Output
1
Input
2
Output
2
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
print(1 if n % 2 == 1 else 2)
``` | vfc_17430 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/R",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1920 | Solve the following coding problem using the programming language python:
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from a_{i} to b_{i}. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers a_{i} and b_{i} (1 ≤ a_{i} ≤ b_{i} ≤ 366), providing that the i-th friend can come to the party from day a_{i} to day b_{i} inclusive.
-----Output-----
Print the maximum number of people that may come to Famil Door's party.
-----Examples-----
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
-----Note-----
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
d = 367
F = [0 for i in range(d)]
M = [0 for i in range(d)]
for i in range(n):
sex, l, r = input().split()
l, r = int(l), int(r)
if sex == 'F':
for j in range(l, r+1): F[j] += 1
else:
for j in range(l, r+1): M[j] += 1
print(2*max(min(F[i], M[i]) for i in range(d)))
``` | vfc_17434 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/629/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\nM 151 307\nF 343 352\nF 117 145\nM 24 128\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\nM 128 130\nF 128 131\nF 131 140\nF 131 141\nM 131 200\nM 140 200\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nF 68 307\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "40\nM 55 363\nF 117 252\nM 157 282\nF 322 345\nM 330 363\nF 154 231\nF 216 352\nF 357 365\nM 279 292\nF 353 359\nF 82 183\nM 78 297\nM 231 314\nM 107 264\nF 34 318\nM 44 244\nF 42 339\nM 253 307\nM 128 192\nF 119 328\nM 135 249\nF 303 358\nF 348 352\nF 8 364\nF 126 303\nM 226 346\nF 110 300\nF 47 303\nF 201 311\nF 287 288\nM 270 352\nM 227 351\nF 8 111\nF 39 229\nM 163 315\nF 269 335\nF 147 351\nF 96 143\nM 97 99\nM 177 295\n",
"output": "22\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\nF 1 1\nM 1 1\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1921 | Solve the following coding problem using the programming language python:
Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.
Let's represent the city as an area of $n \times n$ square blocks. Yura needs to move from the block with coordinates $(s_x,s_y)$ to the block with coordinates $(f_x,f_y)$. In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are $m$ instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate $x$ or with the same coordinate $y$ as the location.
Help Yura to find the smallest time needed to get home.
-----Input-----
The first line contains two integers $n$ and $m$ — the size of the city and the number of instant-movement locations ($1 \le n \le 10^9$, $0 \le m \le 10^5$).
The next line contains four integers $s_x$ $s_y$ $f_x$ $f_y$ — the coordinates of Yura's initial position and the coordinates of his home ($ 1 \le s_x, s_y, f_x, f_y \le n$).
Each of the next $m$ lines contains two integers $x_i$ $y_i$ — coordinates of the $i$-th instant-movement location ($1 \le x_i, y_i \le n$).
-----Output-----
In the only line print the minimum time required to get home.
-----Examples-----
Input
5 3
1 1 5 5
1 2
4 1
3 3
Output
5
Input
84 5
67 59 41 2
39 56
7 2
15 3
74 18
22 7
Output
42
-----Note-----
In the first example Yura needs to reach $(5, 5)$ from $(1, 1)$. He can do that in $5$ minutes by first using the second instant-movement location (because its $y$ coordinate is equal to Yura's $y$ coordinate), and then walking $(4, 1) \to (4, 2) \to (4, 3) \to (5, 3) \to (5, 4) \to (5, 5)$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict
# available on Google, not available on Codeforces
# import numpy as np
# import scipy
import heapq as hq
import math
def dijkstra(G, s):
n = len(G)
visited = [False]*n
weights = [math.inf]*n
path = [None]*n
queue = []
weights[s] = 0
hq.heappush(queue, (0, s))
while len(queue) > 0:
g, u = hq.heappop(queue)
visited[u] = True
for v, w in G[u]:
if not visited[v]:
f = g + w
if f < weights[v]:
weights[v] = f
path[v] = u
hq.heappush(queue, (f, v))
return path, weights
def solve(grid,sx,sy,ex,ey): # fix inputs here
console("----- solving ------")
# console(grid,sx,sy,ex,ey)
minres = abs(sx-ex) + abs(sy-ey)
console(minres)
if grid == []:
return minres
d = defaultdict(list)
grid = [(i,x,y) for i,(x,y) in enumerate(grid)]
# x-order
grid = sorted(grid, key=lambda x: x[1])
for (i1,x1,y1),(i2,x2,y2) in zip(grid, grid[1:]):
d[i1].append((i2,x2-x1))
d[i2].append((i1,x2-x1))
grid = sorted(grid, key=lambda x: x[2])
for (i1,x1,y1),(i2,x2,y2) in zip(grid, grid[1:]):
d[i1].append((i2,y2-y1))
d[i2].append((i1,y2-y1))
for i,x,y in grid:
# start to x-axis
d[-2].append((i,abs(x-sx)))
# start to y-axis
d[-2].append((i,abs(y-sy)))
# point to destination
d[i].append((-1, abs(x-ex) + abs(y-ey)))
d[-1] = []
console(list(d.keys()))
idxs = {k:i for i,k in enumerate(d.keys())}
G = [[] for _ in range(len(idxs))]
for e,vrr in list(d.items()):
for v,cost in vrr:
G[idxs[e]].append((idxs[v],cost))
# console(G)
_,costs = dijkstra(G, idxs[-2])
res = costs[idxs[-1]]
return min(minres, res)
def console(*args): # the judge will not read these print statement
# print('\033[36m', *args, '\033[0m', file=sys.stderr)
return
# fast read all
inp = sys.stdin.readlines()
for case_num in [1]:
# read line as a string
# strr = input()
# read line as an integer
# k = int(input())
# read one line and parse each word as a string
# lst = input().split()
# read one line and parse each word as an integer
_, nrows = list(map(int,inp[0].split()))
sx,sy,ex,ey = list(map(int,inp[1].split()))
currow = 2
# read matrix and parse as integers (after reading read nrows)
# lst = list(map(int,input().split()))
# nrows = lst[0] # index containing information, please change
grid = []
for _ in range(nrows):
grid.append(list(map(int,inp[currow].split())))
currow += 1
res = solve(grid,sx,sy,ex,ey) # please change
# Google - case number required
# print("Case #{}: {}".format(case_num+1, res))
# Codeforces - no case number required
print(res)
``` | vfc_17438 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1422/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 3\n1 1 5 5\n1 2\n4 1\n3 3\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "84 5\n67 59 41 2\n39 56\n7 2\n15 3\n74 18\n22 7\n",
"output": "42\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "88294752 4\n35290308 52335089 69408342 32650662\n53981397 84728746\n56670292 81664574\n16110353 77620219\n45476005 495904\n",
"output": "53802461\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "41323044 1\n28208465 38217978 31290636 25974675\n39500641 36959975\n",
"output": "15325474\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1926 | Solve the following coding problem using the programming language python:
Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.
The teacher gave Andrew an array of n numbers a_1, ..., a_{n}. After that he asked Andrew for each k from 1 to n - 1 to build a k-ary heap on the array and count the number of elements for which the property of the minimum-rooted heap is violated, i.e. the value of an element is less than the value of its parent.
Andrew looked up on the Wikipedia that a k-ary heap is a rooted tree with vertices in elements of the array. If the elements of the array are indexed from 1 to n, then the children of element v are elements with indices k(v - 1) + 2, ..., kv + 1 (if some of these elements lie outside the borders of the array, the corresponding children are absent). In any k-ary heap every element except for the first one has exactly one parent; for the element 1 the parent is absent (this element is the root of the heap). Denote p(v) as the number of the parent of the element with the number v. Let's say that for a non-root element v the property of the heap is violated if a_{v} < a_{p}(v).
Help Andrew cope with the task!
-----Input-----
The first line contains a single integer n (2 ≤ n ≤ 2·10^5).
The second line contains n space-separated integers a_1, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9).
-----Output-----
in a single line print n - 1 integers, separate the consecutive numbers with a single space — the number of elements for which the property of the k-ary heap is violated, for k = 1, 2, ..., n - 1.
-----Examples-----
Input
5
1 5 4 3 2
Output
3 2 1 0
Input
6
2 2 2 2 2 2
Output
0 0 0 0 0
-----Note-----
Pictures with the heaps for the first sample are given below; elements for which the property of the heap is violated are marked with red. [Image] [Image] $\therefore$ [Image]
In the second sample all elements are equal, so the property holds for all pairs.
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 myargsort(a):
b = list(zip(a, list(range(0, len(a)))))
b.sort()
r = [pr[1] for pr in b]
return r
fin = sys.stdin
n = int(fin.readline())
a = [int(number) for number in fin.readline().split()]
p = myargsort(a)
p.reverse()
j = 0
aib = [0] * (n + 1)
def ultb(x):
return -(x ^ (-x)) // 2
def add(p, a, aib, n):
while p <= n:
aib[p] += a
p += ultb(p)
def suma(p, aib):
r = 0
while p > 0:
r += aib[p]
p -= ultb(p)
return r
for i in range(0, n):
add(i + 1, 1, aib, n)
r = [0] * (n + 1)
for i in range(0, n):
if i > 0 and a[i - 1] > a[i]:
r[1] += 1
while j < n and a[p[j]] == a[p[i]]:
add(p[j] + 1, -1, aib, n)
j += 1
k = 2
while k < n and p[i] * k + 1 < n:
dr = min(n, p[i] * k + k + 1)
st = p[i] * k + 2
r[k] += suma(dr, aib) - suma(st - 1, aib)
k += 1
print(*r[1:n])
``` | vfc_17458 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/538/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 5 4 3 2\n",
"output": "3 2 1 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n2 2 2 2 2 2\n",
"output": "0 0 0 0 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n0 0\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1927 | Solve the following coding problem using the programming language python:
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has $n$ friends, numbered from $1$ to $n$.
Recall that a permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array.
So his recent chat list can be represented with a permutation $p$ of size $n$. $p_1$ is the most recent friend Polycarp talked to, $p_2$ is the second most recent and so on.
Initially, Polycarp's recent chat list $p$ looks like $1, 2, \dots, n$ (in other words, it is an identity permutation).
After that he receives $m$ messages, the $j$-th message comes from the friend $a_j$. And that causes friend $a_j$ to move to the first position in a permutation, shifting everyone between the first position and the current position of $a_j$ by $1$. Note that if the friend $a_j$ is in the first position already then nothing happens.
For example, let the recent chat list be $p = [4, 1, 5, 3, 2]$: if he gets messaged by friend $3$, then $p$ becomes $[3, 4, 1, 5, 2]$; if he gets messaged by friend $4$, then $p$ doesn't change $[4, 1, 5, 3, 2]$; if he gets messaged by friend $2$, then $p$ becomes $[2, 4, 1, 5, 3]$.
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 3 \cdot 10^5$) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains $m$ integers $a_1, a_2, \dots, a_m$ ($1 \le a_i \le n$) — the descriptions of the received messages.
-----Output-----
Print $n$ pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
-----Examples-----
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
-----Note-----
In the first example, Polycarp's recent chat list looks like this: $[1, 2, 3, 4, 5]$ $[3, 1, 2, 4, 5]$ $[5, 3, 1, 2, 4]$ $[1, 5, 3, 2, 4]$ $[4, 1, 5, 3, 2]$
So, for example, the positions of the friend $2$ are $2, 3, 4, 4, 5$, respectively. Out of these $2$ is the minimum one and $5$ is the maximum one. Thus, the answer for the friend $2$ is a pair $(2, 5)$.
In the second example, Polycarp's recent chat list looks like this: $[1, 2, 3, 4]$ $[1, 2, 3, 4]$ $[2, 1, 3, 4]$ $[4, 2, 1, 3]$
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
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
mod = 1000000007
def solve():
def add(i,x):
while i < len(bit):
bit[i] += x
i += i&-i
def sum(i):
res = 0
while i > 0:
res += bit[i]
i -= i&-i
return res
n,m = LI()
a = LI()
bit = [0]*(n+m+2)
MIN = [i+1 for i in range(n)]
MAX = [i+1 for i in range(n)]
f = [i+m+1 for i in range(n)]
for i in range(n):
add(f[i],1)
M = m
for i in range(m):
ai = a[i]-1
MIN[ai] = 1
index = sum(f[ai])
if MAX[ai] < index:
MAX[ai] = index
add(M,1)
add(f[ai],-1)
f[ai] = M
M -= 1
for i in range(n):
index = sum(f[i])
if MAX[i] < index:
MAX[i] = index
for i in range(n):
print(MIN[i],MAX[i])
return
#Solve
def __starting_point():
solve()
__starting_point()
``` | vfc_17462 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1288/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 4\n3 5 1 4\n",
"output": "1 3\n2 5\n1 4\n1 5\n1 5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1928 | Solve the following coding problem using the programming language python:
Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix".
Inna sees an n × m matrix and k candies. We'll index the matrix rows from 1 to n and the matrix columns from 1 to m. We'll represent the cell in the i-th row and j-th column as (i, j). Two cells (i, j) and (p, q) of the matrix are adjacent if |i - p| + |j - q| = 1. A path is a sequence of the matrix cells where each pair of neighbouring cells in the sequence is adjacent. We'll call the number of cells in the sequence the path's length.
Each cell of the matrix can have at most one candy. Initiallly, all the cells are empty. Inna is trying to place each of the k candies in the matrix one by one. For each candy Inna chooses cell (i, j) that will contains the candy, and also chooses the path that starts in cell (1, 1) and ends in cell (i, j) and doesn't contain any candies. After that Inna moves the candy along the path from cell (1, 1) to cell (i, j), where the candy stays forever. If at some moment Inna can't choose a path for the candy, she loses. If Inna can place all the candies in the matrix in the described manner, then her penalty equals the sum of lengths of all the paths she has used.
Help Inna to minimize the penalty in the game.
-----Input-----
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 1 ≤ k ≤ n·m).
-----Output-----
In the first line print an integer — Inna's minimum penalty in the game.
In the next k lines print the description of the path for each candy. The description of the path of the candy that is placed i-th should follow on the i-th line. The description of a path is a sequence of cells. Each cell must be written in the format (i, j), where i is the number of the row and j is the number of the column. You are allowed to print extra whitespaces in the line. If there are multiple optimal solutions, print any of them.
Please follow the output format strictly! If your program passes the first pretest, then the output format is correct.
-----Examples-----
Input
4 4 4
Output
8
(1,1) (2,1) (2,2)
(1,1) (1,2)
(1,1) (2,1)
(1,1)
-----Note-----
Note to the sample. Initially the matrix is empty. Then Inna follows her first path, the path penalty equals the number of cells in it — 3. Note that now no path can go through cell (2, 2), as it now contains a candy. The next two candies go to cells (1, 2) and (2, 1). Inna simply leaves the last candy at cell (1, 1), the path contains only this cell. The total penalty is: 3 + 2 + 2 + 1 = 8.
Note that Inna couldn't use cell (1, 1) to place, for instance, the third candy as in this case she couldn't have made the path for the fourth candy.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
string = input()
l = string.split(" ")
n, m, k = int(l[0]),int(l[1]),int(l[2])
l = [{(1,1),}]
count = 1
In = 0
while count < k:
s = set()
for i in l[In]:
x = i[0]+1
y = i[1]
if x<=n and y<=m:
t = [0,0]
t[0],t[1] = x, y
s.add(tuple(t))
x = i[0]
y = i[1]+1
if x<=n and y<=m:
t = [0,0]
t[0],t[1] = x, y
s.add(tuple(t))
l.append(s)
In+=1
count+=len(l[In])
l2 = []
Count = 0
flag = 0
for i in l:
for h in i:
if Count==k:
flag = 1
break
l3 = [h]
x,y = h[0],h[1]
while x!=1 or y!=1:
if x>y:
x-=1
l3.append((x,y))
else:
y-=1
l3.append((x,y))
l2.append(l3)
Count+=1
if flag==1:
break
cost = 0
string = ""
for i in range(k):
length = len(l2[k-i-1])
cost+=length
for j in range(length):
t = l2[k-i-1][length - j - 1]
x,y = t[0],t[1]
string += "("+str(x)+","+str(y)+") "
string += "\n"
print(cost)
print(string)
``` | vfc_17466 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/390/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 4 4\n",
"output": "8\n(1,1) (2,1) (2,2)\n(1,1) (1,2)\n(1,1) (2,1)\n(1,1)\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n",
"output": "1\n(1,1)\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1929 | Solve the following coding problem using the programming language python:
The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.
For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.
Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,
The chosen c prisoners has to form a contiguous segment of prisoners. Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer.
Find the number of ways you can choose the c prisoners.
-----Input-----
The first line of input will contain three space separated integers n (1 ≤ n ≤ 2·10^5), t (0 ≤ t ≤ 10^9) and c (1 ≤ c ≤ n). The next line will contain n space separated integers, the i^{th} integer is the severity i^{th} prisoner's crime. The value of crime severities will be non-negative and will not exceed 10^9.
-----Output-----
Print a single integer — the number of ways you can choose the c prisoners.
-----Examples-----
Input
4 3 3
2 3 1 1
Output
2
Input
1 1 1
2
Output
0
Input
11 4 2
2 2 0 7 3 2 2 4 9 1 4
Output
6
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Codeforces Round 244 Div 1 Problem B
Author : chaotic_iak
Language: Python 3.3.4
"""
class InputHandlerObject(object):
inputs = []
def getInput(self, n = 0):
res = ""
inputs = self.inputs
if not inputs: inputs.extend(input().split(" "))
if n == 0:
res = inputs[:]
inputs[:] = []
while n > len(inputs):
inputs.extend(input().split(" "))
if n > 0:
res = inputs[:n]
inputs[:n] = []
return res
InputHandler = InputHandlerObject()
g = InputHandler.getInput
############################## SOLUTION ##############################
n,t,c = [int(x) for x in g()]
a = [False if int(x) > t else True for x in g()]
ct = 0
res = 0
for i in a:
if i:
ct += 1
if ct >= c: res += 1
else:
ct = 0
print(res)
``` | vfc_17470 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/427/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3 3\n2 3 1 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11 4 2\n2 2 0 7 3 2 2 4 9 1 4\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "57 2 10\n7 5 2 7 4 1 0 5 2 9 2 9 8 6 6 5 9 6 8 1 0 1 0 3 2 6 5 2 8 8 8 8 0 9 4 3 6 6 2 4 5 1 2 0 1 7 1 1 5 4 5 0 7 5 1 9 6\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1930 | Solve the following coding problem using the programming language python:
A permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. An inversion in a permutation $p$ is a pair of indices $(i, j)$ such that $i > j$ and $a_i < a_j$. For example, a permutation $[4, 1, 3, 2]$ contains $4$ inversions: $(2, 1)$, $(3, 1)$, $(4, 1)$, $(4, 3)$.
You are given a permutation $p$ of size $n$. However, the numbers on some positions are replaced by $-1$. Let the valid permutation be such a replacement of $-1$ in this sequence back to numbers from $1$ to $n$ in such a way that the resulting sequence is a permutation of size $n$.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the sequence.
The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($-1 \le p_i \le n$, $p_i \ne 0$) — the initial sequence.
It is guaranteed that all elements not equal to $-1$ are pairwise distinct.
-----Output-----
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$.
-----Examples-----
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
-----Note-----
In the first example two resulting valid permutations are possible:
$[3, 1, 2]$ — $2$ inversions; $[3, 2, 1]$ — $3$ inversions.
The expected value is $\frac{2 \cdot 1 + 3 \cdot 1}{2} = 2.5$.
In the second example no $-1$ are present, thus the only valid permutation is possible — the given one. It has $0$ inversions.
In the third example there are two resulting valid permutations — one with $0$ inversions and one with $1$ inversion.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
MOD = 998244353
def power(x, n) :
ans = 1
while (n) :
if ((n & 1) == 1) :
ans = ans * x % MOD
x = x * x % MOD
n = n // 2
return ans
n = int(input())
a = list(map(int, input().split()))
b = [0 for i in range(n + 1)]
def add(x, v) :
while (x <= n) :
b[x] = b[x] + v
x = x + (x & -x)
def get(x) :
ans = 0
while (x) :
ans = ans + b[x]
x = x - (x & -x)
return ans
anss = 0
for i in range(n) :
if (a[i] != -1) :
add(a[i], 1)
anss = anss + get(n) - get(a[i])
anss = anss % MOD
total = 0
sur = [0] + [1 for i in range(n)]
for i in range(n) :
if (a[i] == -1) :
total = total + 1
else :
sur[a[i]] = 0
if (total == 0) :
print(anss)
return
for i in range(1, n + 1) :
sur[i] = sur[i] + sur[i - 1]
dead = 0
ansa = 0
for i in range(n) :
if (a[i] != -1) :
ansa = ansa + sur[a[i]] * (total - dead) + (sur[n] - sur[a[i]]) * dead
else :
dead = dead + 1
ans = (ansa * 4 + anss * 4 * total + total * total * (total - 1)) % MOD
ans = (ans * power(4 * total, MOD - 2)) % MOD
print(ans)
``` | vfc_17474 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1096/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 -1 -1\n",
"output": "499122179\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n-1 -1\n",
"output": "499122177\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n-1 -1 5 -1 1\n",
"output": "499122183\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1931 | Solve the following coding problem using the programming language python:
A card pyramid of height $1$ is constructed by resting two cards against each other. For $h>1$, a card pyramid of height $h$ is constructed by placing a card pyramid of height $h-1$ onto a base. A base consists of $h$ pyramids of height $1$, and $h-1$ cards on top. For example, card pyramids of heights $1$, $2$, and $3$ look as follows: $\wedge A A$
You start with $n$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?
-----Input-----
Each test consists of multiple test cases. The first line contains a single integer $t$ ($1\le t\le 1000$) — the number of test cases. Next $t$ lines contain descriptions of test cases.
Each test case contains a single integer $n$ ($1\le n\le 10^9$) — the number of cards.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^9$.
-----Output-----
For each test case output a single integer — the number of pyramids you will have constructed in the end.
-----Example-----
Input
5
3
14
15
24
1
Output
1
2
1
3
0
-----Note-----
In the first test, you construct a pyramid of height $1$ with $2$ cards. There is $1$ card remaining, which is not enough to build a pyramid.
In the second test, you build two pyramids, each of height $2$, with no cards remaining.
In the third test, you build one pyramid of height $3$, with no cards remaining.
In the fourth test, you build one pyramid of height $3$ with $9$ cards remaining. Then you build a pyramid of height $2$ with $2$ cards remaining. Then you build a final pyramid of height $1$ with no cards remaining.
In the fifth test, one card is not enough to build any pyramids.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
for zz in range(int(input())):
n = int(input())
ans = 0
while n > 1:
ans += 1
cr = 2
while n >= cr:
n -= cr
cr += 3
print(ans)
``` | vfc_17478 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1345/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n3\n14\n15\n24\n1\n",
"output": "1\n2\n1\n3\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000000\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n486008999\n486009000\n",
"output": "7\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1932 | Solve the following coding problem using the programming language python:
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
[Image]
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string s_{i} — the name of the i-th polyhedron in Anton's collection. The string can look like this:
"Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
-----Output-----
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
-----Examples-----
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
-----Note-----
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
cnt = {
"Tetrahedron": 4,
"Cube": 6,
"Octahedron": 8,
"Dodecahedron": 12,
"Icosahedron": 20}
n = int(input())
c = 0
for _ in range(n):
s = input()
c += cnt[s]
print(c)
``` | vfc_17482 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/785/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\nIcosahedron\nCube\nTetrahedron\nDodecahedron\n",
"output": "42\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nDodecahedron\nOctahedron\nOctahedron\n",
"output": "28\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "25\nIcosahedron\nOctahedron\nTetrahedron\nDodecahedron\nCube\nIcosahedron\nOctahedron\nCube\nTetrahedron\nIcosahedron\nIcosahedron\nTetrahedron\nOctahedron\nDodecahedron\nIcosahedron\nOctahedron\nIcosahedron\nTetrahedron\nDodecahedron\nTetrahedron\nOctahedron\nCube\nCube\nDodecahedron\nTetrahedron\n",
"output": "256\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nTetrahedron\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nCube\n",
"output": "6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1934 | Solve the following coding problem using the programming language python:
You are given sequence a_1, a_2, ..., a_{n} and m queries l_{j}, r_{j} (1 ≤ l_{j} ≤ r_{j} ≤ n). For each query you need to print the minimum distance between such pair of elements a_{x} and a_{y} (x ≠ y), that: both indexes of the elements lie within range [l_{j}, r_{j}], that is, l_{j} ≤ x, y ≤ r_{j}; the values of the elements are equal, that is a_{x} = a_{y}.
The text above understands distance as |x - y|.
-----Input-----
The first line of the input contains a pair of integers n, m (1 ≤ n, m ≤ 5·10^5) — the length of the sequence and the number of queries, correspondingly.
The second line contains the sequence of integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9).
Next m lines contain the queries, one per line. Each query is given by a pair of numbers l_{j}, r_{j} (1 ≤ l_{j} ≤ r_{j} ≤ n) — the indexes of the query range limits.
-----Output-----
Print m integers — the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query.
-----Examples-----
Input
5 3
1 1 2 3 2
1 5
2 4
3 5
Output
1
-1
2
Input
6 5
1 2 1 3 2 3
4 6
1 3
2 5
2 4
1 6
Output
2
2
3
-1
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
class Fenwick(object):
def __init__(self, n):
self.n = n
self.a = [10**9 for i in range(n)]
self.w= 10**9
def zag(self, i, zn):
self.w= min(self.w, zn)
while i < self.n:
self.a[i] = min(self.a[i], zn)
i = (i | (i + 1))
def pol(self, r):
ans= 10**9
while r >= 0:
if ans> self.a[r]:
ans= self.a[r]
if ans== self.w:
break
r = (r & (r + 1)) - 1
return ans
n, m = [int(x) for x in sys.stdin.readline().split()]
a = [int(x) for x in sys.stdin.readline().split()]
nd= [-1 for i in range(0, len(a))]
vi= {}
for i in range(0, len(a)):
if a[i] in vi:
nd[i] = vi[a[i]]
vi[a[i]] = i
inp= sys.stdin.readlines()
och= [[] for i in range(n)]
for i in range(m):
l, r = inp[i].split()
och[int(r) - 1].append((int(l) - 1, i))
der = Fenwick(2 ** 19)
ans= [None for i in range(0, m)]
le= -1
for r in range(n):
if nd[r] != -1:
der.zag(500000 - nd[r] + 1, r - nd[r])
le = max(le, nd[r])
for (l, ind) in och[r]:
if l > le:
ans[ind] = -1
continue
zn= der.pol(500000 - l + 1)
if zn== 10**9:
zn= -1
ans[ind] = zn
print('\n'.join(str(zn) for zn in ans))
``` | vfc_17490 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/522/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 3\n1 1 2 3 2\n1 5\n2 4\n3 5\n",
"output": "1\n-1\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 5\n1 2 1 3 2 3\n4 6\n1 3\n2 5\n2 4\n1 6\n",
"output": "2\n2\n3\n-1\n2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1935 | Solve the following coding problem using the programming language python:
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of $n$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $g$ seconds green, and then $r$ seconds red, then again $g$ seconds green and so on.
Formally, the road can be represented as a segment $[0, n]$. Initially, Denis is at point $0$. His task is to get to point $n$ in the shortest possible time.
He knows many different integers $d_1, d_2, \ldots, d_m$, where $0 \leq d_i \leq n$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $\pm 1$ in $1$ second. While doing so, he must always stay inside the segment $[0, n]$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $+1$ and he walked on a safety island, then he can change his position by $\pm 1$. Otherwise, he can change his position only by $+1$. Similarly, if in the previous second he changed his position by $-1$, on a safety island he can change position by $\pm 1$, and at any other point by $-1$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to $n$.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
-----Input-----
The first line contains two integers $n$ and $m$ $(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$ — road width and the number of safety islands.
The second line contains $m$ distinct integers $d_1, d_2, \ldots, d_m$ $(0 \leq d_i \leq n)$ — the points where the safety islands are located. It is guaranteed that there are $0$ and $n$ among them.
The third line contains two integers $g, r$ $(1 \leq g, r \leq 1000)$ — the time that the green light stays on and the time that the red light stays on.
-----Output-----
Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.
If it is impossible to cross the road output $-1$.
-----Examples-----
Input
15 5
0 3 7 14 15
11 11
Output
45
Input
13 4
0 3 7 13
9 9
Output
-1
-----Note-----
In the first test, the optimal route is: for the first green light, go to $7$ and return to $3$. In this case, we will change the direction of movement at the point $7$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $3$, where there is also a safety island. The next $11$ seconds we have to wait for the red light. for the second green light reaches $14$. Wait for the red light again. for $1$ second go to $15$. As a result, Denis is at the end of the road.
In total, $45$ seconds are obtained.
In the second test, it is impossible to cross the road according to all the rules.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import collections
n,m=map(int,input().split())
m+=2
arr=list(map(int,input().split()))
arr.append(0)
arr.append(n)
arr=sorted(arr)
g,r=map(int,input().split())
q=collections.deque()
q.append((0,0))
dist=[[0]*(g+1) for _ in range(m+2)]
checked=[[0]*(g+1) for _ in range(m+2)]
checked[0][0]=1
ans=-1
while len(q)!=0:
v,t=q.popleft()
if t==0:
if n-arr[v]<=g:
tmp=dist[v][t]*(g+r)+n-arr[v]
if ans==-1 or ans>tmp:
ans=tmp
if t==g:
if checked[v][0]==0:
checked[v][0]=1
dist[v][0]=dist[v][t]+1
q.append((v,0))
continue
if v!=0:
cost=t+arr[v]-arr[v-1]
if cost<=g and checked[v-1][cost]==0:
checked[v-1][cost]=1
dist[v-1][cost]=dist[v][t]
q.appendleft((v-1,cost))
if v!=m-1:
cost=t+arr[v+1]-arr[v]
if cost<=g and checked[v+1][cost]==0:
checked[v+1][cost]=1
dist[v+1][cost]=dist[v][t]
q.appendleft((v+1,cost))
print(ans)
``` | vfc_17494 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1341/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "15 5\n0 3 7 14 15\n11 11\n",
"output": "45",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "13 4\n0 3 7 13\n9 9\n",
"output": "-1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 5\n0 3 1 2 4\n1 1\n",
"output": "7",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 5\n0 3 1 2 4\n2 1\n",
"output": "5",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15 5\n15 3 7 0 14\n11 11\n",
"output": "45",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15 5\n15 14 7 3 0\n11 11\n",
"output": "45",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1936 | Solve the following coding problem using the programming language python:
Let $LCM(x, y)$ be the minimum positive integer that is divisible by both $x$ and $y$. For example, $LCM(13, 37) = 481$, $LCM(9, 6) = 18$.
You are given two integers $l$ and $r$. Find two integers $x$ and $y$ such that $l \le x < y \le r$ and $l \le LCM(x, y) \le r$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10000$) — the number of test cases.
Each test case is represented by one line containing two integers $l$ and $r$ ($1 \le l < r \le 10^9$).
-----Output-----
For each test case, print two integers:
if it is impossible to find integers $x$ and $y$ meeting the constraints in the statement, print two integers equal to $-1$; otherwise, print the values of $x$ and $y$ (if there are multiple valid answers, you may print any of them).
-----Example-----
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
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())
while t:
l, r = list(map(int, input().split()))
if l * 2 <= r:
print(l, 2 * l)
else:
print(-1, -1)
t -= 1
``` | vfc_17498 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1389/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1 1337\n13 69\n2 4\n88 89\n",
"output": "1 2\n13 26\n2 4\n-1 -1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n55556 55557\n",
"output": "-1 -1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n2 4\n2 4\n2 4\n2 4\n2 4\n",
"output": "2 4\n2 4\n2 4\n2 4\n2 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n78788 157576\n",
"output": "78788 157576\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n8743 17489\n",
"output": "8743 17486\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1937 | Solve the following coding problem using the programming language python:
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.
There were $n$ classes of that subject during the semester and on $i$-th class professor mentioned some non-negative integer $a_i$ to the students. It turned out, the exam was to tell the whole sequence back to the professor.
Sounds easy enough for those who attended every class, doesn't it?
Obviously Mishka didn't attend any classes. However, professor left some clues on the values of $a$ to help out students like Mishka: $a$ was sorted in non-decreasing order ($a_1 \le a_2 \le \dots \le a_n$); $n$ was even; the following sequence $b$, consisting of $\frac n 2$ elements, was formed and given out to students: $b_i = a_i + a_{n - i + 1}$.
Professor also mentioned that any sequence $a$, which produces sequence $b$ with the presented technique, will be acceptable.
Help Mishka to pass that last exam. Restore any sorted sequence $a$ of non-negative integers, which produces sequence $b$ with the presented technique. It is guaranteed that there exists at least one correct sequence $a$, which produces the given sequence $b$.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the length of sequence $a$. $n$ is always even.
The second line contains $\frac n 2$ integers $b_1, b_2, \dots, b_{\frac n 2}$ ($0 \le b_i \le 10^{18}$) — sequence $b$, where $b_i = a_i + a_{n - i + 1}$.
It is guaranteed that there exists at least one correct sequence $a$, which produces the given sequence $b$.
-----Output-----
Print $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^{18}$) in a single line.
$a_1 \le a_2 \le \dots \le a_n$ should be satisfied.
$b_i = a_i + a_{n - i + 1}$ should be satisfied for all valid $i$.
-----Examples-----
Input
4
5 6
Output
2 3 3 3
Input
6
2 1 2
Output
0 0 1 1 1 2
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#
import collections, atexit, math, sys, bisect
sys.setrecursionlimit(1000000)
def getIntList():
return list(map(int, input().split()))
try :
#raise ModuleNotFoundError
import numpy
def dprint(*args, **kwargs):
#print(*args, **kwargs, file=sys.stderr)
# in python 3.4 **kwargs is invalid???
print(*args, file=sys.stderr)
dprint('debug mode')
except Exception:
def dprint(*args, **kwargs):
pass
inId = 0
outId = 0
if inId>0:
dprint('use input', inId)
sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件
if outId>0:
dprint('use output', outId)
sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件
atexit.register(lambda :sys.stdout.close()) #idle 中不会执行 atexit
N, = getIntList()
#print(N)
zb = getIntList()
za1 = [0]
za2 = [zb[0]]
for i in range(1, N//2):
t1 = zb[i] - za1[-1]
if t1 <= za2[-1]:
za1.append(za1[-1])
za2.append(t1)
continue
t2 = zb[i] - za2[-1]
if t2 >= za1[-1]:
za1.append(t2)
za2.append(za2[-1])
continue
assert False
zr = za1 + za2[ : :-1]
zs = []
for x in zr:
zs .append(str(x))
r = ' '.join(zs)
print(r)
``` | vfc_17502 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1093/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n5 6\n",
"output": "0 1 5 5 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n2 1 2\n",
"output": "0 0 1 1 1 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n7\n",
"output": "0 7 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1938 | Solve the following coding problem using the programming language python:
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that $f(\varnothing) = 0$). You are given two integers n and k and n closed intervals [l_{i}, r_{i}] on OX axis and you have to find: $\sum_{1 \leq i_{1} < i_{2} < \ldots < i_{k} \leq n} f([ l_{i_{1}}, r_{i_{1}} ] \cap [ l_{i_{2}}, r_{i_{2}} ] \cap \ldots \cap [ l_{i_{k}}, r_{i_{k}} ])$
In other words, you should find the sum of the number of integer points in the intersection of any k of the segments.
As the answer may be very large, output it modulo 1000000007 (10^9 + 7).
Mike can't solve this problem so he needs your help. You will help him, won't you?
-----Input-----
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively.
Then n lines follow, the i-th line contains two integers l_{i}, r_{i} ( - 10^9 ≤ l_{i} ≤ r_{i} ≤ 10^9), describing i-th segment bounds.
-----Output-----
Print one integer number — the answer to Mike's problem modulo 1000000007 (10^9 + 7) in the only line.
-----Examples-----
Input
3 2
1 2
1 3
2 3
Output
5
Input
3 3
1 3
1 3
1 3
Output
3
Input
3 1
1 2
2 3
3 4
Output
6
-----Note-----
In the first example:
$f([ 1,2 ] \cap [ 1,3 ]) = f([ 1,2 ]) = 2$;
$f([ 1,2 ] \cap [ 2,3 ]) = f([ 2,2 ]) = 1$;
$f([ 1,3 ] \cap [ 2,3 ]) = f([ 2,3 ]) = 2$.
So the answer is 2 + 1 + 2 = 5.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
MOD = 10**9 + 7
from sys import stderr
def readints():
return [int(fld) for fld in input().strip().split()]
def combk(n, k, MOD=MOD, tbl=[]):
if len(tbl) < k:
tbl += [0] * k + [1]
while n >= len(tbl):
tbl.append(tbl[-1] * len(tbl) * pow(len(tbl) - k, MOD-2, MOD) % MOD)
return tbl[n]
def main():
n, k = readints()
pairs = [readints() for _ in range(n)]
oplist = [p for l, r in pairs for p in (2*l, 2*r+1)]
oplist.sort()
count = total = 0
pos = oplist[0] // 2
for op in oplist:
if op & 1:
i, delta = (op+1)//2, -1
else:
i, delta = op//2, 1
total = (total + combk(count, k) * (i - pos)) % MOD
pos = i
count += delta
print(total)
main()
``` | vfc_17506 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/689/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n1 2\n1 3\n2 3\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n1 3\n1 3\n1 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1\n1 2\n2 3\n3 4\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n45 70\n",
"output": "26\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n-35 -8\n",
"output": "28\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n-79 -51\n",
"output": "29\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1939 | Solve the following coding problem using the programming language python:
Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
-----Input-----
The single line contains two integers, n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000).
-----Output-----
Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.
If there are multiple suitable tables, you are allowed to print any of them.
-----Examples-----
Input
2 4
Output
1 3
3 1
Input
4 7
Output
2 1 0 4
4 0 2 1
1 3 3 0
0 3 2 2
-----Note-----
In the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.
In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.
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())
ind=0
for i in range(N):
for j in range(N):
if(j!=N-1):
if(j==i):
print(k,end=" ")
else:
print(0,end=" ")
else:
if(j==i):
print(k)
else:
print(0)
``` | vfc_17510 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/361/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 4\n",
"output": "4 0 \n0 4 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 7\n",
"output": "7 0 0 0 \n0 7 0 0 \n0 0 7 0 \n0 0 0 7 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 8\n",
"output": "8 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1940 | Solve the following coding problem using the programming language python:
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are w_{i} pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.
Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
-----Input-----
The first line contains two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^9) — the number of different pebble types and number of pebbles Anastasia can place in one pocket.
The second line contains n integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 10^4) — number of pebbles of each type.
-----Output-----
The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.
-----Examples-----
Input
3 2
2 3 4
Output
3
Input
5 4
3 1 8 9 7
Output
5
-----Note-----
In the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.
Optimal sequence of actions in the second sample case: In the first day Anastasia collects 8 pebbles of the third type. In the second day she collects 8 pebbles of the fourth type. In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type. In the fourth day she collects 7 pebbles of the fifth type. In the fifth day she collects 1 pebble of the second type.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = [int(i) for i in input().split()]
w = [int(i) for i in input().split()]
tot = 0
for wi in w:
tot += (wi+k-1)//k
ans = (tot+1)//2
print(ans)
``` | vfc_17514 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/789/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n2 3 4\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1941 | Solve the following coding problem using the programming language python:
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. [Image]
Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is s_{i} = A + (i - 1) × B.
For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.
Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence s_{l}, s_{l} + 1, ..., s_{r} can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.
-----Input-----
The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 10^6, 1 ≤ n ≤ 10^5).
Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 10^6) for i-th query.
-----Output-----
For each query, print its answer in a single line.
-----Examples-----
Input
2 1 4
1 5 3
3 3 10
7 10 2
6 4 8
Output
4
-1
8
-1
Input
1 5 2
1 5 10
2 7 4
Output
1
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
import math
a, b, n = list(map(int, str.split(sys.stdin.readline())))
s = lambda i: a + (i - 1) * b
S = lambda i: a * i + b * i * (i - 1) // 2
for _ in range(n):
l, t, m = list(map(int, str.split(sys.stdin.readline())))
# Si = a * r + b * r * (r - 1) / 2
# Si = b / 2 * r ^ 2 - (b / 2 - a) * r
# si = a + (i - 1) * b => (si - a) / b + 1 = i
# (S(r) - S(l-1)) / t <= m
# S(r) <= m * t + S(l-1)
# b / 2 * r ^ 2 - (b / 2 - a) * r - m * t - S(l-1) <= 0
# D = (b / 2 - a) ^ 2 + 4 * b / 2 * (m * t + S(l-1))
d = (b / 2 - a) ** 2 + 4 * b / 2 * (m * t + S(l - 1))
if d < 0:
print(-1)
continue
r = min(
math.floor((t - a) / b + 1),
math.floor(((b / 2 - a) + math.sqrt(d)) / b)
)
if r < l:
print(-1)
else:
print(r)
``` | vfc_17518 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/535/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 1 4\n1 5 3\n3 3 10\n7 10 2\n6 4 8\n",
"output": "4\n-1\n8\n-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 5 2\n1 5 10\n2 7 4\n",
"output": "1\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 4\n1 1000000 1000000\n1 1 1000000\n1 1000000 1\n1 1 1\n",
"output": "1000000\n1\n1413\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000 1000000 1\n1000000 1000000 1000000\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1942 | Solve the following coding problem using the programming language python:
You are given a complete directed graph $K_n$ with $n$ vertices: each pair of vertices $u \neq v$ in $K_n$ have both directed edges $(u, v)$ and $(v, u)$; there are no self-loops.
You should find such a cycle in $K_n$ that visits every directed edge exactly once (allowing for revisiting vertices).
We can write such cycle as a list of $n(n - 1) + 1$ vertices $v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$ — a visiting order, where each $(v_i, v_{i + 1})$ occurs exactly once.
Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.
Since the answer can be too large print its $[l, r]$ segment, in other words, $v_l, v_{l + 1}, \dots, v_r$.
-----Input-----
The first line contains the single integer $T$ ($1 \le T \le 100$) — the number of test cases.
Next $T$ lines contain test cases — one per line. The first and only line of each test case contains three integers $n$, $l$ and $r$ ($2 \le n \le 10^5$, $1 \le l \le r \le n(n - 1) + 1$, $r - l + 1 \le 10^5$) — the number of vertices in $K_n$, and segment of the cycle to print.
It's guaranteed that the total sum of $n$ doesn't exceed $10^5$ and the total sum of $r - l + 1$ doesn't exceed $10^5$.
-----Output-----
For each test case print the segment $v_l, v_{l + 1}, \dots, v_r$ of the lexicographically smallest cycle that visits every edge exactly once.
-----Example-----
Input
3
2 1 3
3 3 6
99995 9998900031 9998900031
Output
1 2 1
1 3 2 3
1
-----Note-----
In the second test case, the lexicographically minimum cycle looks like: $1, 2, 1, 3, 2, 3, 1$.
In the third test case, it's quite obvious that the cycle should start and end in vertex $1$.
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 *
import sys
try: inp = raw_input
except: inp = input
def err(s):
sys.stderr.write('{}\n'.format(s))
def ni():
return int(inp())
def nl():
return [int(_) for _ in inp().split()]
def solve():
n, L, R = nl()
L -= 1
R -= 1
SM = 0
out = []
for i in range(1, n):
no = (n - i)*2
if no + SM <= L:
SM += no
continue
if SM > R: continue
ARR = [i if j%2 == 0 else i + j//2 + 1 for j in range(no)]
start = max(0, L - SM)
end = R - SM + 1
out.extend(ARR[start:end])
SM += no
if R == SM:
out.append(1)
print(' '.join(map(str, out)))
T = ni()
for _ in range(T):
solve()
``` | vfc_17522 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1334/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 1 3\n3 3 6\n99995 9998900031 9998900031\n",
"output": "1 2 1 \n1 3 2 3 \n1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n4 13 13\n",
"output": "1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n2 1 3\n2 1 3\n2 1 3\n2 1 3\n2 1 3\n2 1 3\n2 1 3\n2 1 3\n2 1 3\n2 1 3\n",
"output": "1 2 1 \n1 2 1 \n1 2 1 \n1 2 1 \n1 2 1 \n1 2 1 \n1 2 1 \n1 2 1 \n1 2 1 \n1 2 1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1943 | Solve the following coding problem using the programming language python:
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2^{N} teams participating in the tournament, numbered from 1 to 2^{N}. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2^{N} - 1 games, numbered starting from 1. In game i, team 2·i - 1 will play against team 2·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2·i - 1 will play against the winner of the previous round's game 2·i.
Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2^{N} - 1 points.
For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
-----Input-----
Input will begin with a line containing N (2 ≤ N ≤ 6).
2^{N} lines follow, each with 2^{N} integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.
-----Output-----
Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10^{ - 9}.
Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if $\frac{|a - b|}{\operatorname{max}(1,|b|)} \leq 10^{-9}$.
-----Examples-----
Input
2
0 40 100 100
60 0 40 40
0 60 0 45
0 60 55 0
Output
1.75
Input
3
0 0 100 0 100 0 0 0
100 0 100 0 0 0 100 100
0 0 0 100 100 0 0 0
100 100 0 0 0 0 100 100
0 100 0 100 0 0 100 0
100 100 100 100 100 0 0 0
100 0 100 0 0 100 0 0
100 0 100 0 100 100 100 0
Output
12
Input
2
0 21 41 26
79 0 97 33
59 3 0 91
74 67 9 0
Output
3.141592
-----Note-----
In the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import functools
n = int(input())
props = []
def preproc(a):
return float(a)/100.
for i in range(pow(2,n)):
props.append(list(map(preproc, input().split())))
wining_props = [] # list of lists. First index -- number of round, second -- num of team, value -- prop of wining
wining_props_first_round = []
for i in range(0, (2 ** n), 2):
# i, and i+1 teams playing
wining_prop_for_i = props[i][i + 1]
wining_props_first_round.append(wining_prop_for_i)
wining_props_first_round.append(1. - wining_prop_for_i)
wining_props.append(wining_props_first_round)
assert len(wining_props_first_round) == len(props)
for round_num in range(2, n + 1):
# calculate propabilitys for winning in i round for each team
# prop of winning in i round = prop of winning prev round + mo of win this one
# mo win this = for each team we can meet prop of them wining prev * prop we win them
# each team we can meet on round i = all teems // 2^i == we//2^i
this_round_wining_props = []
for team_num in range(2 ** n):
t = team_num // (2 ** round_num) * (2 ** (round_num))
teams_we_meet_this_round = [t + x for x in range(2 ** round_num)]
t = team_num // (2 ** (round_num-1)) * (2 ** (round_num-1))
teams_we_meet_prev_round = [t + x for x in range(2 ** (round_num-1))]
for tt in teams_we_meet_prev_round:
teams_we_meet_this_round.remove(tt)
this_team_wining_props = wining_props[round_num - 2][team_num] # -2 cause numeration
chances_win_i_team = []
for tm in teams_we_meet_this_round:
# chances we meet them * chances we win
chances_win_i_team.append(wining_props[round_num - 2][tm] * props[team_num][tm])
mo_win_this_round = sum(chances_win_i_team)
this_team_wining_props *= mo_win_this_round
this_round_wining_props.append(this_team_wining_props)
#assert 0.99 < sum(this_round_wining_props) < 1.01
wining_props.append(this_round_wining_props)
# now we got props of each win on each round. Lets bet on most propable winer and calculate revenue
#from left to right-1 is playing
@functools.lru_cache(maxsize=None)
def revenue(round_num, teams_left, teams_right, winner=-1):
split = ((teams_left + teams_right) // 2)
# let the strongest team win, we bet, and calculate to the bottom
if round_num == 1:
return wining_props[0][winner] if winner != -1 else max(wining_props[0][teams_left:teams_right])
if winner == -1:
results = []
for winner in range(teams_left, teams_right):
winner_prop = wining_props[round_num - 1][winner]
if winner >= split:
res = sum(
[revenue(round_num - 1, teams_left, split), revenue(round_num - 1, split, teams_right, winner),
winner_prop * (2 ** (round_num - 1))])
else:
res = sum(
[revenue(round_num - 1, teams_left, split, winner), revenue(round_num - 1, split, teams_right),
winner_prop * (2 ** (round_num - 1))])
results.append(res)
return max(results)
else:
winner_prop = wining_props[round_num - 1][winner]
if winner >= split:
res = sum(
[revenue(round_num - 1, teams_left, split), revenue(round_num - 1, split, teams_right, winner),
winner_prop * (2 ** (round_num - 1))])
else:
res = sum(
[revenue(round_num - 1, teams_left, split, winner), revenue(round_num - 1, split, teams_right),
winner_prop * (2 ** (round_num - 1))])
return res
print(revenue(n, 0, (2 ** n)))
``` | vfc_17526 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/859/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n0 40 100 100\n60 0 40 40\n0 60 0 45\n0 60 55 0\n",
"output": "1.75\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n0 0 100 0 100 0 0 0\n100 0 100 0 0 0 100 100\n0 0 0 100 100 0 0 0\n100 100 0 0 0 0 100 100\n0 100 0 100 0 0 100 0\n100 100 100 100 100 0 0 0\n100 0 100 0 0 100 0 0\n100 0 100 0 100 100 100 0\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n0 21 41 26\n79 0 97 33\n59 3 0 91\n74 67 9 0\n",
"output": "3.141592\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n0 7 38 22 3 66 32 77\n93 0 93 61 45 40 6 92\n62 7 0 32 8 46 56 29\n78 39 68 0 37 24 84 42\n97 55 92 63 0 46 62 100\n34 60 54 76 54 0 39 67\n68 94 44 16 38 61 0 98\n23 8 71 58 0 33 2 0\n",
"output": "6.8196427571\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1944 | Solve the following coding problem using the programming language python:
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.
Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist.
-----Input-----
The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of laptops.
Next n lines contain two integers each, a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n), where a_{i} is the price of the i-th laptop, and b_{i} is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality).
All a_{i} are distinct. All b_{i} are distinct.
-----Output-----
If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes).
-----Examples-----
Input
2
1 2
2 1
Output
Happy Alex
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
arr = []
for i in range(n):
a,b = map(int, input().split(' '))
arr.append((a,b))
arr = sorted(arr)
for i in range(n-1):
if(arr[i][1]>arr[i+1][1]):
print("Happy Alex")
break
else:
print("Poor Alex")
``` | vfc_17530 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/456/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 2\n2 1\n",
"output": "Happy Alex\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1\n2 2\n",
"output": "Poor Alex\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1945 | Solve the following coding problem using the programming language python:
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
-----Input-----
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests.
Next q lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
-----Output-----
In the first line output the integer n — the number of users that changed their handles at least once.
In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description.
-----Examples-----
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
n = int(input())
b_a = {}
for n_ in range(n):
b, a = input().split()
replaced = False
for k in b_a:
if b_a[k] == b:
b_a[k] = a
replaced = True
if not replaced:
b_a[b] = a
print(len(b_a))
for k in b_a:
print(k + " " + b_a[k])
``` | vfc_17534 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/501/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov\n",
"output": "3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nMisha Vasya\n",
"output": "1\nMisha Vasya\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\na b\nb c\nc d\nd e\ne f\nf g\ng h\nh i\ni j\nj k\n",
"output": "1\na k\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1946 | Solve the following coding problem using the programming language python:
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies.
In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies.
All elements are enumerated with integers. The ChemForces company has discovered $n$ distinct chemical elements with indices $a_1, a_2, \ldots, a_n$, and will get an income of $x_i$ Berland rubles if the $i$-th element from this list is in the set of this company.
The TopChemist company discovered $m$ distinct chemical elements with indices $b_1, b_2, \ldots, b_m$, and it will get an income of $y_j$ Berland rubles for including the $j$-th element from this list to its set.
In other words, the first company can present any subset of elements from $\{a_1, a_2, \ldots, a_n\}$ (possibly empty subset), the second company can present any subset of elements from $\{b_1, b_2, \ldots, b_m\}$ (possibly empty subset). There shouldn't be equal elements in the subsets.
Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of elements discovered by ChemForces.
The $i$-th of the next $n$ lines contains two integers $a_i$ and $x_i$ ($1 \leq a_i \leq 10^9$, $1 \leq x_i \leq 10^9$) — the index of the $i$-th element and the income of its usage on the exhibition. It is guaranteed that all $a_i$ are distinct.
The next line contains a single integer $m$ ($1 \leq m \leq 10^5$) — the number of chemicals invented by TopChemist.
The $j$-th of the next $m$ lines contains two integers $b_j$ and $y_j$, ($1 \leq b_j \leq 10^9$, $1 \leq y_j \leq 10^9$) — the index of the $j$-th element and the income of its usage on the exhibition. It is guaranteed that all $b_j$ are distinct.
-----Output-----
Print the maximum total income you can obtain by choosing the sets for both companies in such a way that no element is presented in both sets.
-----Examples-----
Input
3
1 2
7 2
3 10
4
1 4
2 4
3 4
4 4
Output
24
Input
1
1000000000 239
3
14 15
92 65
35 89
Output
408
-----Note-----
In the first example ChemForces can choose the set ($3, 7$), while TopChemist can choose ($1, 2, 4$). This way the total income is $(10 + 2) + (4 + 4 + 4) = 24$.
In the second example ChemForces can choose the only element $10^9$, while TopChemist can choose ($14, 92, 35$). This way the total income is $(239) + (15 + 65 + 89) = 408$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
d={}
n=int(input())
for _ in range(n):
i,j=map(int,input().split())
d[i]=j
m=int(input())
for _ in range(m):
i,j=map(int,input().split())
if i in d and d[i]>j: continue
d[i]=j
ans=0
for i,j in d.items():
ans+=j
print(ans)
``` | vfc_17538 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/981/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2\n7 2\n3 10\n4\n1 4\n2 4\n3 4\n4 4\n",
"output": "24\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000000 239\n3\n14 15\n92 65\n35 89\n",
"output": "408\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n598654597 488228616\n544064902 21923894\n329635457 980089248\n988262691 654502493\n967529230 543358150\n835120075 128123793\n809901567 613170206\n152157661 479980560\n859252956 318029856\n614959273 735298093\n10\n849172317 361325206\n341655282 740807372\n453949939 809030434\n813199219 765838311\n725032511 427644854\n631233366 115983627\n825067417 721190169\n463026366 953335259\n881501578 987288937\n500099903 427659916\n",
"output": "11272808994\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n598654597 488228616\n544064902 21923894\n329635457 980089248\n988262691 654502493\n967529230 543358150\n835120075 128123793\n809901567 613170206\n152157661 479980560\n859252956 318029856\n614959273 735298093\n10\n544064902 740807372\n859252956 765838311\n835120075 115983627\n825067417 463026366\n809901567 500099903\n614959273 322932832\n33955432 657532637\n816892960 927933923\n916770606 754371712\n967529230 566149252\n",
"output": "8955052582\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n259021863 682413763\n1\n554146726 693647287\n",
"output": "1376061050\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n259021863 682413763\n1\n554146726 425883728\n",
"output": "1108297491\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1947 | Solve the following coding problem using the programming language python:
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...
To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $l$ centimeters after haircut, where $l$ is her favorite number. Suppose, that the Alice's head is a straight line on which $n$ hairlines grow. Let's number them from $1$ to $n$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $l$, given that all hairlines on that segment had length strictly greater than $l$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.
Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types: $0$ — Alice asks how much time the haircut would take if she would go to the hairdresser now. $1$ $p$ $d$ — $p$-th hairline grows by $d$ centimeters.
Note, that in the request $0$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.
-----Input-----
The first line contains three integers $n$, $m$ and $l$ ($1 \le n, m \le 100\,000$, $1 \le l \le 10^9$) — the number of hairlines, the number of requests and the favorite number of Alice.
The second line contains $n$ integers $a_i$ ($1 \le a_i \le 10^9$) — the initial lengths of all hairlines of Alice.
Each of the following $m$ lines contains a request in the format described in the statement.
The request description starts with an integer $t_i$. If $t_i = 0$, then you need to find the time the haircut would take. Otherwise, $t_i = 1$ and in this moment one hairline grows. The rest of the line than contains two more integers: $p_i$ and $d_i$ ($1 \le p_i \le n$, $1 \le d_i \le 10^9$) — the number of the hairline and the length it grows by.
-----Output-----
For each query of type $0$ print the time the haircut would take.
-----Example-----
Input
4 7 3
1 2 3 4
0
1 2 3
0
1 1 3
0
1 3 1
0
Output
1
2
2
1
-----Note-----
Consider the first example: Initially lengths of hairlines are equal to $1, 2, 3, 4$ and only $4$-th hairline is longer $l=3$, and hairdresser can cut it in $1$ second. Then Alice's second hairline grows, the lengths of hairlines are now equal to $1, 5, 3, 4$ Now haircut takes two seonds: two swings are required: for the $4$-th hairline and for the $2$-nd. Then Alice's first hairline grows, the lengths of hairlines are now equal to $4, 5, 3, 4$ The haircut still takes two seconds: with one swing hairdresser can cut $4$-th hairline and with one more swing cut the segment from $1$-st to $2$-nd hairline. Then Alice's third hairline grows, the lengths of hairlines are now equal to $4, 5, 4, 4$ Now haircut takes only one second: with one swing it is possible to cut the segment from $1$-st hairline to the $4$-th.
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 -*-
import math
import collections
import bisect
import heapq
import time
import itertools
import sys
"""
created by shhuan at 2018/11/10 22:33
"""
N, M, L = list(map(int, input().split()))
A = [int(x) for x in input().split()]
ans = 0
i = 0
while i < N:
j = i
while j < N and A[j] > L:
j += 1
if j > i:
ans += 1
i = j + 1
else:
i += 1
for mi in range(M):
line = input()
if len(line) == 1:
print(ans)
else:
t, p, d = list(map(int, line.split()))
prev = A[p-1]
A[p-1] += d
if prev <= L < A[p-1]:
if p-2 >= 0 and p < N:
if A[p-2] > L and A[p] > L:
ans -= 1
elif A[p-2] <= L and A[p] <= L:
ans += 1
else:
pass
elif p-2 >= 0:
if A[p-2] > L:
pass
else:
ans += 1
elif p < N:
if A[p] > L:
pass
else:
ans += 1
else:
ans += 1
``` | vfc_17542 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1055/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 7 3\n1 2 3 4\n0\n1 2 3\n0\n1 1 3\n0\n1 3 1\n0\n",
"output": "1\n2\n2\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 3 1\n1\n0\n1 1 1\n0\n",
"output": "0\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1948 | Solve the following coding problem using the programming language python:
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
-----Input-----
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·10^5, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
-----Output-----
Print the total number of moves Alice and Bob will make.
-----Examples-----
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
-----Note-----
In the first example the tree looks like this:
[Image]
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
[Image]
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from collections import deque
from sys import stdin
n, x = map(int, stdin.readline().split())
leafs = set(range(n))
graph = [[] for i in range(n)]
count = [False for i in range(n)]
for i in range(n - 1):
a, b = map(int, stdin.readline().split())
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
if not count[a - 1]:
count[a - 1] = True
else:
leafs.discard(a - 1)
if not count[b - 1]:
count[b - 1] = True
else:
leafs.discard(b - 1)
queue = deque()
way_a = [10 ** 6 for i in range(n)]
way_b = [10 ** 6 for i in range(n)]
used = [False for i in range(n)]
queue.append([0, 0])
while queue:
j = queue.popleft()
way_a[j[0]] = min(way_a[j[0]], j[1])
for i in graph[j[0]]:
if not used[i]:
used[i] = True
queue.append([i, j[1] + 1])
queue.append([x - 1, 0])
used = [False for i in range(n)]
while queue:
j = queue.popleft()
way_b[j[0]] = min(way_b[j[0]], j[1])
for i in graph[j[0]]:
if not used[i]:
used[i] = True
queue.append([i, j[1] + 1])
res = way_a[x - 1]
for i in leafs:
if way_a[i] > way_b[i]:
res = max(res, way_a[i])
print(res * 2)
``` | vfc_17546 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/813/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n1 2\n2 3\n2 4\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1949 | Solve the following coding problem using the programming language python:
You're given an array $a$. You should repeat the following operation $k$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
-----Input-----
The first line contains integers $n$ and $k$ $(1 \le n,k \le 10^5)$, the length of the array and the number of operations you should perform.
The second line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ $(1 \le a_i \le 10^9)$, the elements of the array.
-----Output-----
Print the minimum non-zero element before each operation in a new line.
-----Examples-----
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
-----Note-----
In the first sample:
In the first step: the array is $[1,2,3]$, so the minimum non-zero element is 1.
In the second step: the array is $[0,1,2]$, so the minimum non-zero element is 1.
In the third step: the array is $[0,0,1]$, so the minimum non-zero element is 1.
In the fourth and fifth step: the array is $[0,0,0]$, so we printed 0.
In the second sample:
In the first step: the array is $[10,3,5,3]$, so the minimum non-zero element is 3.
In the second step: the array is $[7,0,2,0]$, so the minimum non-zero element is 2.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
cur = 0
idx = 0
for i in range(k):
ans = 0
while idx < n:
ans = a[idx] - cur
idx += 1
if ans != 0:
break
print(ans)
cur += ans
``` | vfc_17550 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1088/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5\n1 2 3\n",
"output": "1\n1\n1\n0\n0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1950 | Solve the following coding problem using the programming language python:
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following: Ivan chooses any non-empty box and takes all balls from this box; Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
-----Input-----
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is the number of balls with color i.
-----Output-----
Print one number — the minimum possible penalty of the game.
-----Examples-----
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
-----Note-----
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns: Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14; Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
r = lambda: map(int, input().split())
import heapq
def main():
n, = r()
a = list(r())
if len(a) % 2 == 0:
a.append(0)
heapq.heapify(a)
ret = 0
while len(a) > 1:
x = heapq.heappop(a)
y = heapq.heappop(a)
z = heapq.heappop(a)
ret += x + y + z
heapq.heappush(a, x + y + z)
print(ret)
main()
``` | vfc_17554 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/884/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2 3 4 5\n",
"output": "19\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n1 4 4 4 4 4\n",
"output": "38\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n821407370 380061316 428719552 90851747 825473738 704702117 845629927 245820158\n",
"output": "8176373828\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1951 | Solve the following coding problem using the programming language python:
Tenten runs a weapon shop for ninjas. Today she is willing to sell $n$ shurikens which cost $1$, $2$, ..., $n$ ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
+ means that she placed another shuriken on the showcase; - x means that the shuriken of price $x$ was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
-----Input-----
The first line contains the only integer $n$ ($1\leq n\leq 10^5$) standing for the number of shurikens.
The following $2n$ lines describe the events in the format described above. It's guaranteed that there are exactly $n$ events of the first type, and each price from $1$ to $n$ occurs exactly once in the events of the second type.
-----Output-----
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain $n$ space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
-----Examples-----
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
-----Note-----
In the first example Tenten first placed shurikens with prices $4$ and $2$. After this a customer came in and bought the cheapest shuriken which costed $2$. Next, Tenten added a shuriken with price $3$ on the showcase to the already placed $4$-ryo. Then a new customer bought this $3$-ryo shuriken. After this she added a $1$-ryo shuriken. Finally, the last two customers bought shurikens $1$ and $4$, respectively. Note that the order $[2, 4, 3, 1]$ is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price $2$. This is impossible since the shuriken was not the cheapest, we know that the $1$-ryo shuriken was also there.
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
input = sys.stdin.readline
def main():
N = int(input())
S = [[x for x in input().split()] for _ in range(2 * N)]
q = []
ans = []
for s in S[::-1]:
if s[0] == "-":
heapq.heappush(q, int(s[1]))
else:
if q:
c = heapq.heappop(q)
ans.append(c)
else:
print("NO")
return
ans2 = ans[::-1]
q = []
current = 0
for s in S:
if s[0] == "-":
c = heapq.heappop(q)
if c != int(s[1]):
print("NO")
return
else:
heapq.heappush(q, ans2[current])
current += 1
print("YES")
print(*ans2)
def __starting_point():
main()
__starting_point()
``` | vfc_17558 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1413/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n+\n+\n- 2\n+\n- 3\n+\n- 1\n- 4\n",
"output": "YES\n4 2 3 1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1953 | Solve the following coding problem using the programming language python:
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time t_{i} needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.
Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5).
The next line contains n integers t_{i} (1 ≤ t_{i} ≤ 10^9), separated by spaces.
-----Output-----
Print a single number — the maximum number of not disappointed people in the queue.
-----Examples-----
Input
5
15 2 1 5 3
Output
4
-----Note-----
Value 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
num = 0
res = 0
for i in range(n):
if int(a[i]) >= num:
res += 1
num += int(a[i])
#print(res, a[i])
print(res)
``` | vfc_17566 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/545/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n15 2 1 5 3\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1954 | Solve the following coding problem using the programming language python:
Today is Devu's birthday. For celebrating the occasion, he bought n sweets from the nearby market. He has invited his f friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend.
He wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed n sweets to his friends such that i^{th} friend is given a_{i} sweets. He wants to make sure that there should not be any positive integer x > 1, which divides every a_{i}.
Please find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo 1000000007 (10^9 + 7).
To make the problem more interesting, you are given q queries. Each query contains an n, f pair. For each query please output the required number of ways modulo 1000000007 (10^9 + 7).
-----Input-----
The first line contains an integer q representing the number of queries (1 ≤ q ≤ 10^5). Each of the next q lines contains two space space-separated integers n, f (1 ≤ f ≤ n ≤ 10^5).
-----Output-----
For each query, output a single integer in a line corresponding to the answer of each query.
-----Examples-----
Input
5
6 2
7 2
6 3
6 4
7 4
Output
2
6
9
10
20
-----Note-----
For first query: n = 6, f = 2. Possible partitions are [1, 5] and [5, 1].
For second query: n = 7, f = 2. Possible partitions are [1, 6] and [2, 5] and [3, 4] and [4, 3] and [5, 3] and [6, 1]. So in total there are 6 possible ways of partitioning.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import itertools
import functools
import operator
N = 100001
P = 10**9 + 7
fact = [1]
for i in range(1, N):
fact.append(fact[-1] * i % P)
inv = [0, 1]
for i in range(2, N):
inv.append(P - P // i * inv[P % i] % P)
inv_fact = [1]
for i in range(1, N):
inv_fact.append(inv_fact[-1] * inv[i] % P)
least_div = [-1] * N
primes = []
for p in range(2, N):
if least_div[p] == -1:
primes.append(p)
least_div[p] = p
ldiv = least_div[p]
for mult in primes:
mark = mult * p
if (mult > ldiv) or (mark >= N):
break
least_div[mark] = mult
t = int(input())
def powerset(iterable):
s = list(iterable)
return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s) + 1))
memo_factor = dict()
def factor(n):
if n in memo_factor:
return memo_factor[n]
ret = []
while n != 1:
tmp = least_div[n]
if not(ret and ret[-1] == tmp):
ret.append(tmp)
n //= tmp
memo_factor[n] = ret
return ret
@functools.lru_cache(maxsize = None)
def solve(n, k):
divs = factor(n)
# print(divs)
ret = 0
for subset in powerset(divs):
div = functools.reduce(operator.mul, subset, 1)
# print(div, f(n // div, k))
if n // div >= k:
tmp = fact[n // div - 1] * inv_fact[n // div - k] % P * inv_fact[k - 1] % P
ret += (-1 if len(subset) % 2 == 1 else 1) * tmp
ret %= P
return ret
for _ in range(t):
n, k = list(map(int, input().split()))
print(solve(n, k))
``` | vfc_17570 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/439/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n6 2\n7 2\n6 3\n6 4\n7 4\n",
"output": "2\n6\n9\n10\n20\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1\n1 1\n1 1\n7 2\n6 3\n9 5\n4 1\n2 1\n3 1\n2 2\n",
"output": "1\n1\n1\n6\n9\n70\n0\n0\n0\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "40\n37 15\n48 10\n16 5\n25 23\n32 20\n24 4\n46 19\n16 13\n1 1\n37 22\n44 29\n24 6\n27 10\n39 16\n28 13\n5 4\n31 22\n9 2\n30 26\n23 16\n16 12\n43 5\n29 1\n20 5\n40 12\n18 14\n22 15\n29 2\n3 2\n6 3\n45 28\n42 34\n43 32\n10 10\n12 8\n10 8\n4 1\n17 17\n16 7\n8 7\n",
"output": "796297179\n361826943\n1330\n276\n141120525\n1572\n884475620\n455\n1\n567902525\n532655639\n33166\n3124550\n471286455\n17383847\n4\n14307150\n6\n23751\n170544\n1365\n111930\n0\n3750\n675980455\n2380\n116280\n28\n2\n9\n353793174\n95548245\n280561348\n1\n330\n36\n0\n1\n4998\n7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n201 98\n897 574\n703 669\n238 199\n253 71\n619 577\n656 597\n827 450\n165 165\n17 5\n",
"output": "161386475\n287013046\n190482739\n953794468\n858506105\n813510912\n157101041\n44730040\n1\n1820\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1955 | Solve the following coding problem using the programming language python:
Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m.
About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day.
On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest.
About each subject Vasiliy know a number a_{i} — the number of days he should prepare to pass the exam number i. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during a_{i} days for the exam number i. He can mix the order of preparation for exams in any way.
Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of days in the exam period and the number of subjects.
The second line contains n integers d_1, d_2, ..., d_{n} (0 ≤ d_{i} ≤ m), where d_{i} is the number of subject, the exam of which can be passed on the day number i. If d_{i} equals 0, it is not allowed to pass any exams on the day number i.
The third line contains m positive integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^5), where a_{i} is the number of days that are needed to prepare before passing the exam on the subject i.
-----Output-----
Print one integer — the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1.
-----Examples-----
Input
7 2
0 1 0 2 1 0 2
2 1
Output
5
Input
10 3
0 0 1 2 3 0 2 0 1 2
1 1 4
Output
9
Input
5 1
1 1 1 1 1
5
Output
-1
-----Note-----
In the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day.
In the second example Vasiliy should prepare for the exam number 3 during the first four days and pass it on the fifth day. Then on the sixth day he should prepare for the exam number 2 and then pass it on the seventh day. After that he needs to prepare for the exam number 1 on the eighth day and pass it on the ninth day.
In the third example Vasiliy can't pass the only exam because he hasn't anough time to prepare for it.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,m = list(map(int,input().split()))
A = list(map(int,input().split()))
B = list(map(int,input().split()))
sums = sum(B)+len(B)
last = [-1] * m
cou = 0
ans = 0
per = 0
for j in range(n):
if A[j] == 0:
cou +=1
else:
if last[A[j]-1] == -1:
if j >= B[A[j]-1]:
ans += 1
last[A[j]-1] = 0
if ans == m:
if (j+1) >= sums:
per=1
print(j+1)
break
if per == 0:
print(-1)
``` | vfc_17574 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/732/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 2\n0 1 0 2 1 0 2\n2 1\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 3\n0 0 1 2 3 0 2 0 1 2\n1 1 4\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 1\n1 1 1 1 1\n5\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1957 | Solve the following coding problem using the programming language python:
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole.
Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\frac{s_i \cdot A}{S}$ liters of water will flow out of it.
What is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?
-----Input-----
The first line contains three integers $n$, $A$, $B$ ($1 \le n \le 100\,000$, $1 \le B \le A \le 10^4$) — the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole.
The second line contains $n$ integers $s_1, s_2, \ldots, s_n$ ($1 \le s_i \le 10^4$) — the sizes of the holes.
-----Output-----
Print a single integer — the number of holes Arkady should block.
-----Examples-----
Input
4 10 3
2 2 2 2
Output
1
Input
4 80 20
3 2 1 4
Output
0
Input
5 10 10
1000 1 1 1 1
Output
4
-----Note-----
In the first example Arkady should block at least one hole. After that, $\frac{10 \cdot 2}{6} \approx 3.333$ liters of water will flow out of the first hole, and that suits Arkady.
In the second example even without blocking any hole, $\frac{80 \cdot 3}{10} = 24$ liters will flow out of the first hole, that is not less than $20$.
In the third example Arkady has to block all holes except the first to make all water flow out of the first hole.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, a, b = [int(x) for x in input().split()]
hs = [int(x) for x in input().split()]
target = 1.0 * hs[0] * a / b
left = sorted(hs[1:])
s = sum(hs)
res = 0
while s > target:
res += 1
s -= left[-res]
print(res)
``` | vfc_17582 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/967/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 10 3\n2 2 2 2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 80 20\n3 2 1 4\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 10 10\n1000 1 1 1 1\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1958 | Solve the following coding problem using the programming language python:
Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.
She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had.
So each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd).
For each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is p (the number p is even).
Print the total money grandma should have at the end of the day to check if some buyers cheated her.
-----Input-----
The first line contains two integers n and p (1 ≤ n ≤ 40, 2 ≤ p ≤ 1000) — the number of the buyers and the cost of one apple. It is guaranteed that the number p is even.
The next n lines contains the description of buyers. Each buyer is described with the string half if he simply bought half of the apples and with the string halfplus if grandma also gave him a half of an apple as a gift.
It is guaranteed that grandma has at least one apple at the start of the day and she has no apples at the end of the day.
-----Output-----
Print the only integer a — the total money grandma should have at the end of the day.
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
2 10
half
halfplus
Output
15
Input
3 10
halfplus
halfplus
halfplus
Output
55
-----Note-----
In the first sample at the start of the day the grandma had two apples. First she sold one apple and then she sold a half of the second apple and gave a half of the second apple as a present to the second buyer.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,p = list(map(int,input().split()))
temp = [input() for i in range(n)]
num = 0
num2 = 0
for i in range(n-1,-1,-1):
if temp[i] == "halfplus":
num *= 2
num += 1
num2 += num/2*p
else:
num2 += num*p
num *= 2
print(int(num2))
``` | vfc_17586 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/632/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 10\nhalf\nhalfplus\n",
"output": "15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 10\nhalfplus\nhalfplus\nhalfplus\n",
"output": "55\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 328\nhalf\nhalfplus\nhalfplus\nhalf\nhalfplus\nhalf\nhalf\nhalf\nhalfplus\nhalfplus\n",
"output": "258300\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1959 | Solve the following coding problem using the programming language python:
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct.
Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on.
A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
-----Input-----
The first line contains two integers n and m (2 ≤ n ≤ 2·10^5, 1 ≤ m ≤ 10^9) — the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even.
The second line contains a sequence of n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the numbers on Eugeny's cards.
-----Output-----
If there is no answer, print -1.
Otherwise, in the first line print the minimum number of exchanges. In the second line print n integers — Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to.
If there are multiple answers, it is allowed to print any of them.
-----Examples-----
Input
6 2
5 6 7 9 4 5
Output
1
5 6 7 9 4 2
Input
8 6
7 7 7 7 8 8 8 8
Output
6
7 2 4 6 8 1 3 5
Input
4 1
4 2 1 10
Output
-1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#!/usr/bin/env python3
class CantException(Exception):
pass
def odd_v(value):
return 1 if value % 2 == 1 else -1
change_idx = 1
acceptable = {-1: set(), 1: set()}
def change(card_values, oddv, m):
nonlocal change_idx
if acceptable[oddv]:
res = acceptable[oddv].pop()
card_values.add(res)
return res
change_idx_start = change_idx
while change_idx in card_values or odd_v(change_idx) != oddv:
if change_idx not in card_values:
acceptable[odd_v(change_idx)].add(change_idx)
change_idx += 1
if change_idx > m:
change_idx = 1
if change_idx == change_idx_start:
raise CantException()
res = change_idx
card_values.add(res)
change_idx += 1
if change_idx > m:
change_idx = 1
return res
def solve():
n, m = list(map(int, input().split()))
cards = list(map(int, input().split()))
odd_balance = 0
card_values = set()
indices_to_be_changed = set()
for i, c in enumerate(cards):
odd_balance += odd_v(c)
if c in card_values:
indices_to_be_changed.add(i)
card_values.add(c)
# print("indices to be changed: ", indices_to_be_changed)
change_count = len(indices_to_be_changed)
for i in indices_to_be_changed:
if odd_v(cards[i]) * odd_balance <= 0:
#print("Changing ", cards[i])
cards[i] = change(card_values, odd_v(cards[i]), m)
#print("Changed to ", cards[i])
else:
#print("For teh balance changing ", cards[i])
odd_balance -= 2 * odd_v(cards[i])
cards[i] = change(card_values, - odd_v(cards[i]), m)
#print("Changed to ", cards[i])
#print("current odd balance:", odd_balance)
for i in range(len(cards)):
if odd_balance == 0:
break
if odd_v(cards[i]) * odd_balance > 0:
# print("gonna change")
change_count += 1
odd_balance -= 2 * odd_v(cards[i])
cards[i] = change(card_values, -odd_v(cards[i]), m)
odd_balance = 0
for i, c in enumerate(cards):
odd_balance += odd_v(c)
if odd_balance != 0:
print(odd_balance)
print("WTFFFFF")
return change_count, cards
def __starting_point():
try:
change_cnt, cards = solve()
print(change_cnt)
print(" ".join(map(str, cards)))
except CantException:
print("-1")
__starting_point()
``` | vfc_17590 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/746/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 2\n5 6 7 9 4 5\n",
"output": "1\n5 6 7 9 4 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8 6\n7 7 7 7 8 8 8 8\n",
"output": "6\n7 2 4 6 8 1 3 5 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n4 2 1 10\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n12 13 10 20 13 10 19 15 21 11\n",
"output": "2\n12 13 10 20 2 4 19 15 21 11 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20 16\n23 27 17 29 23 21 24 23 19 25 16 24 20 17 18 17 16 17 28 17\n",
"output": "8\n23 27 17 29 2 21 24 4 19 25 16 6 20 8 18 10 1 3 28 5 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1960 | Solve the following coding problem using the programming language python:
The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.
Nam created a sequence a consisting of n (1 ≤ n ≤ 10^5) elements a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5). A subsequence a_{i}_1, a_{i}_2, ..., a_{i}_{k} where 1 ≤ i_1 < i_2 < ... < i_{k} ≤ n is called increasing if a_{i}_1 < a_{i}_2 < a_{i}_3 < ... < a_{i}_{k}. An increasing subsequence is called longest if it has maximum length among all increasing subsequences.
Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes i (1 ≤ i ≤ n), into three groups: group of all i such that a_{i} belongs to no longest increasing subsequences. group of all i such that a_{i} belongs to at least one but not every longest increasing subsequence. group of all i such that a_{i} belongs to every longest increasing subsequence.
Since the number of longest increasing subsequences of a may be very large, categorizing process is very difficult. Your task is to help him finish this job.
-----Input-----
The first line contains the single integer n (1 ≤ n ≤ 10^5) denoting the number of elements of sequence a.
The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5).
-----Output-----
Print a string consisting of n characters. i-th character should be '1', '2' or '3' depending on which group among listed above index i belongs to.
-----Examples-----
Input
1
4
Output
3
Input
4
1 3 2 5
Output
3223
Input
4
1 5 2 3
Output
3133
-----Note-----
In the second sample, sequence a consists of 4 elements: {a_1, a_2, a_3, a_4} = {1, 3, 2, 5}. Sequence a has exactly 2 longest increasing subsequences of length 3, they are {a_1, a_2, a_4} = {1, 3, 5} and {a_1, a_3, a_4} = {1, 2, 5}.
In the third sample, sequence a consists of 4 elements: {a_1, a_2, a_3, a_4} = {1, 5, 2, 3}. Sequence a have exactly 1 longest increasing subsequence of length 3, that is {a_1, a_3, a_4} = {1, 2, 3}.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
N = int( input() )
A = list( map( int, input().split() ) )
maxa = max( A )
def upd( ftree, x, v ):
while x <= maxa:
ftree[ x ] = max( ftree[ x ], v )
x += x & -x
def qry( ftree, x ):
res = 0
while x:
res = max( res, ftree[ x ] )
x -= x & -x
return res
st_len = [ 0 for i in range( N ) ]
ftree = [ 0 for i in range( maxa + 1 ) ]
for i in range( N - 1, -1, -1 ):
st_len[ i ] = qry( ftree, maxa + 1 - A[ i ] - 1 ) + 1
upd( ftree, maxa + 1 - A[ i ], st_len[ i ] )
ed_len = [ 0 for i in range( N ) ]
ftree = [ 0 for i in range( maxa + 1 ) ]
for i in range( N ):
ed_len[ i ] = qry( ftree, A[ i ] - 1 ) + 1
upd( ftree, A[ i ], ed_len[ i ] )
max_len = max( st_len )
st_cnt_len = [ 0 for i in range( N + 1 ) ]
for i in range( N ):
if ed_len[ i ] + st_len[ i ] - 1 == max_len:
st_cnt_len[ st_len[ i ] ] += 1
for i in range( N ):
if ed_len[ i ] + st_len[ i ] - 1 != max_len:
print( 1, end = "" )
elif st_cnt_len[ st_len[ i ] ] > 1:
print( 2, end = "" )
else:
print( 3, end = "" )
print()
``` | vfc_17594 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/486/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n4\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1961 | Solve the following coding problem using the programming language python:
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an $n\times m$ grid, where every cell is either filled with ink or empty. Andrey's pen can fill a $3\times3$ square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty $n\times m$ grid.
-----Input-----
The first line of input contains two integers $n$ and $m$ ($3 \le n, m \le 1000$).
Then $n$ lines follow, each contains $m$ characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
-----Output-----
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
-----Examples-----
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
-----Note-----
In the first sample Andrey can paint the border of the square with the center in $(2, 2)$.
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in $(2, 2)$ and $(3, 2)$: we have a clear paper:
...
...
...
...
use the pen with center at $(2, 2)$.
###
#.#
###
...
use the pen with center at $(3, 2)$.
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in $(3, 3)$ and $(3, 5)$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = [int(i) for i in input().split()]
A = []
ct = []
for i in range(n):
x = list(input())
y = [0]*m
A.append(x)
ct.append(y)
ok = 1
for i in range(n-2):
for j in range(m-2):
if A[i][j]=='#' and A[i][j+1]=='#' and A[i][j+2]=='#' and A[i+1][j]=='#' and A[i+2][j]=='#' and A[i+2][j+1]=='#' and A[i+2][j+2]=='#' and A[i+1][j+2]=='#':
ct[i][j] = 1
ct[i][j+1] = 1
ct[i][j+2] = 1
ct[i+1][j] = 1
ct[i+1][j+2] = 1
ct[i+2][j] = 1
ct[i+2][j+1] = 1
ct[i+2][j+2] = 1
xct = 0
xhs = 0
for i in range(len(ct)):
for j in range(len(ct[i])):
if ct[i][j] == 1:
xct+=1
if A[i][j] == '#':
xhs+=1
if xhs==xct:
print('YES')
else:
print('NO')
``` | vfc_17598 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1059/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3\n###\n#.#\n###\n",
"output": "YES",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n###\n###\n###\n",
"output": "NO",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3\n###\n###\n###\n###\n",
"output": "YES",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 7\n.......\n.#####.\n.#.#.#.\n.#####.\n.......\n",
"output": "YES",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1962 | Solve the following coding problem using the programming language python:
You have m = n·k wooden staves. The i-th stave has length a_{i}. You have to assemble n barrels consisting of k staves each, you can use any k staves to construct a barrel. Each stave must belong to exactly one barrel.
Let volume v_{j} of barrel j be equal to the length of the minimal stave in it. [Image]
You want to assemble exactly n barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed l, i.e. |v_{x} - v_{y}| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.
Print maximal total sum of volumes of equal enough barrels or 0 if it's impossible to satisfy the condition above.
-----Input-----
The first line contains three space-separated integers n, k and l (1 ≤ n, k ≤ 10^5, 1 ≤ n·k ≤ 10^5, 0 ≤ l ≤ 10^9).
The second line contains m = n·k space-separated integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^9) — lengths of staves.
-----Output-----
Print single integer — maximal total sum of the volumes of barrels or 0 if it's impossible to construct exactly n barrels satisfying the condition |v_{x} - v_{y}| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.
-----Examples-----
Input
4 2 1
2 2 1 2 3 2 2 3
Output
7
Input
2 1 0
10 10
Output
20
Input
1 2 1
5 2
Output
2
Input
3 2 1
1 2 3 4 5 6
Output
0
-----Note-----
In the first example you can form the following barrels: [1, 2], [2, 2], [2, 3], [2, 3].
In the second example you can form the following barrels: [10], [10].
In the third example you can form the following barrels: [2, 5].
In the fourth example difference between volumes of barrels in any partition is at least 2 so it is impossible to make barrels equal enough.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def ii():
return int(input())
def mi():
return list(map(int, input().split()))
def li():
return list(mi())
N, K, L = mi()
A = li()
A.sort()
end = 1
while end < N * K and A[end] <= A[0] + L:
end += 1
B = A[:end]
if len(B) < N:
ans = 0
else:
cur = ans = 0
for i in range(N):
ans += B[cur]
cur = min(cur + K, len(B) - (N - i - 1))
print(ans)
``` | vfc_17602 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/985/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2 1\n2 2 1 2 3 2 2 3\n",
"output": "7\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1963 | Solve the following coding problem using the programming language python:
Simon has an array a_1, a_2, ..., a_{n}, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers a_{l}, a_{l} + 1, ..., a_{r} are divisible by a_{j}; value r - l takes the maximum value among all pairs for which condition 1 is true;
Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 3·10^5).
The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6).
-----Output-----
Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order.
-----Examples-----
Input
5
4 6 9 3 6
Output
1 3
2
Input
5
1 3 5 7 9
Output
1 4
1
Input
5
2 3 5 7 11
Output
5 0
1 2 3 4 5
-----Note-----
In the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.
In the second sample all numbers are divisible by number 1.
In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input()) + 1
t = [1] + list(map(int, input().split())) + [1]
p = [True] * n
s, q = 0, list(range(1, n))
for i in range(1, n):
if p[i]:
a = b = i
d = t[i]
if d == 1:
s, q = n - 2, [1]
break
while t[a - 1] % d == 0: a -= 1
while t[b + 1] % d == 0:
b += 1
p[b] = False
d = b - a
if d > s: s, q = d, [a]
elif d == s != 0: q.append(a)
print(len(q), s)
print(' '.join(map(str, q)))
``` | vfc_17606 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/359/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n4 6 9 3 6\n",
"output": "1 3\n2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 3 5 7 9\n",
"output": "1 4\n1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n2 3 5 7 11\n",
"output": "5 0\n1 2 3 4 5 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1343\n",
"output": "1 0\n1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000\n",
"output": "1 0\n1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n5\n",
"output": "1 0\n1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1964 | Solve the following coding problem using the programming language python:
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.
There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has k_{i} people. The j-th person standing in the queue to the i-th cashier has m_{i}, j items in the basket. Vasya knows that: the cashier needs 5 seconds to scan one item; after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change.
Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k_1, k_2, ..., k_{n} (1 ≤ k_{i} ≤ 100), where k_{i} is the number of people in the queue to the i-th cashier.
The i-th of the next n lines contains k_{i} space-separated integers: m_{i}, 1, m_{i}, 2, ..., m_{i}, k_{i} (1 ≤ m_{i}, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.
-----Output-----
Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.
-----Examples-----
Input
1
1
1
Output
20
Input
4
1 4 3 2
100
1 2 2 3
1 9 1
7 8
Output
100
-----Note-----
In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.
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())
k = map(int, input().split())
times = []
for i in range(n):
people = list(map(int, input().split()))
time = len(people) * 15
for p in people:
time += p*5
times.append(time)
print(min(times))
``` | vfc_17610 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/408/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n1\n1\n",
"output": "20\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 4 3 2\n100\n1 2 2 3\n1 9 1\n7 8\n",
"output": "100\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n5 4 5 5\n3 1 3 1 2\n3 1 1 3\n1 1 1 2 2\n2 2 1 1 3\n",
"output": "100\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n5 3 6 6 4\n7 5 3 3 9\n6 8 2\n1 10 8 5 9 2\n9 7 8 5 9 10\n9 8 3 3\n",
"output": "125\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n10 10 10 10 10\n6 7 8 6 8 5 9 8 10 5\n9 6 9 8 7 8 8 10 8 5\n8 7 7 8 7 5 6 8 9 5\n6 5 10 5 5 10 7 8 5 5\n10 9 8 7 6 9 7 9 6 5\n",
"output": "480\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n9 10 10 10 9 5 9 7 8 7\n11 6 10 4 4 15 7 15 5\n3 9 11 12 11 1 13 13 1 5\n6 15 9 12 3 2 8 12 11 10\n7 1 1 6 10 2 6 1 14 2\n8 14 2 3 6 1 14 1 12\n6 10 9 3 5\n13 12 12 7 13 4 4 8 10\n5 6 4 3 14 9 13\n8 12 1 5 7 4 13 1\n1 9 5 3 5 1 4\n",
"output": "240\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1965 | Solve the following coding problem using the programming language python:
A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).
Killjoy's account is already infected and has a rating equal to $x$. Its rating is constant. There are $n$ accounts except hers, numbered from $1$ to $n$. The $i$-th account's initial rating is $a_i$. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.
Contests are regularly held on Codeforces. In each contest, any of these $n$ accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.
Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.
It can be proven that all accounts can be infected in some finite number of contests.
-----Input-----
The first line contains a single integer $t$ $(1 \le t \le 100)$ — the number of test cases. The next $2t$ lines contain the descriptions of all test cases.
The first line of each test case contains two integers $n$ and $x$ ($2 \le n \le 10^3$, $-4000 \le x \le 4000$) — the number of accounts on Codeforces and the rating of Killjoy's account.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ $(-4000 \le a_i \le 4000)$ — the ratings of other accounts.
-----Output-----
For each test case output the minimal number of contests needed to infect all accounts.
-----Example-----
Input
3
2 69
68 70
6 4
4 4 4 4 4 4
9 38
-21 83 50 -59 -77 15 -71 -78 20
Output
1
0
2
-----Note-----
In the first test case it's possible to make all ratings equal to $69$. First account's rating will increase by $1$, and second account's rating will decrease by $1$, so the sum of all changes will be equal to zero.
In the second test case all accounts will be instantly infected, because all ratings (including Killjoy's account's rating) are equal to $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 random
from fractions import Fraction
from math import *
def input():
return sys.stdin.readline().strip()
def iinput():
return int(input())
def finput():
return float(input())
def tinput():
return input().split()
def linput():
return list(input())
def rinput():
return list(map(int, tinput()))
def fiinput():
return list(map(float, tinput()))
def rlinput():
return list(map(int, input().split()))
def trinput():
return tuple(rinput())
def srlinput():
return sorted(list(map(int, input().split())))
def NOYES(fl):
if fl:
print("NO")
else:
print("YES")
def YESNO(fl):
if fl:
print("YES")
else:
print("NO")
def main():
#n = iinput()
#k = iinput()
#m = iinput()
#n = int(sys.stdin.readline().strip())
n, k = rinput()
#n, m = rinput()
#m, k = rinput()
#n, k, m = rinput()
#n, m, k = rinput()
#k, n, m = rinput()
#k, m, n = rinput()
#m, k, n = rinput()
#m, n, k = rinput()
q = srlinput()
#q = linput()
print((q.count(k) != n) * (k in q) + (1 + (k * n != sum(q))) * (k not in q))
for i in range(iinput()):
main()
``` | vfc_17614 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1419/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 69\n68 70\n6 4\n4 4 4 4 4 4\n9 38\n-21 83 50 -59 -77 15 -71 -78 20\n",
"output": "1\n0\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n4 4\n3 6 6 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n4 4\n3 3 5 6\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3 3\n4 2 3\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3 4\n5 5 5\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1966 | Solve the following coding problem using the programming language python:
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color a_{k}, i, j; 1 being black and 0 being white.
Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
-----Input-----
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board.
Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
-----Output-----
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
-----Examples-----
Input
1
0
0
1
0
Output
1
Input
3
101
010
101
101
000
101
010
101
011
010
101
010
Output
2
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from itertools import permutations
n = int(input())
p1, _, p2, _, p3, _, p4 = [input() for _ in range(n)], input(), [input() for _ in range(n)], input(), [input() for _ in range(n)], input(), [input() for _ in range(n)]
def count(a,b,c,d):
board = [a[i] + b[i] for i in range(n)] + [c[i] + d[i] for i in range(n)]
res = 0
for i in range(2*n):
for j in range(2*n):
clr = '1' if (i+j)%2 == 0 else '0'
res += board[i][j] != clr
return res
print(min(count(*p) for p in permutations([p1, p2, p3, p4])))
``` | vfc_17618 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/961/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n0\n\n0\n\n1\n\n0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1967 | Solve the following coding problem using the programming language python:
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.
He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).
Implement this feature to help Polycarp test his editor.
-----Input-----
The first line contains two integers, w and h (1 ≤ w, h ≤ 100) — the width and height of an image in pixels. The picture is given in h lines, each line contains w characters — each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.
-----Output-----
Print 2w lines, each containing 2h characters — the result of consecutive implementing of the three transformations, described above.
-----Examples-----
Input
3 2
.*.
.*.
Output
....
....
****
****
....
....
Input
9 20
**.......
****.....
******...
*******..
..******.
....****.
......***
*.....***
*********
*********
*********
*********
....**...
...****..
..******.
.********
****..***
***...***
**.....**
*.......*
Output
********......**********........********
********......**********........********
********........********......********..
********........********......********..
..********......********....********....
..********......********....********....
..********......********..********......
..********......********..********......
....********....****************........
....********....****************........
....********....****************........
....********....****************........
......******************..**********....
......******************..**********....
........****************....**********..
........****************....**********..
............************......**********
............************......**********
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
w, h = map(int, input().split())
image = [input() for i in range(h)]
for i in range(w):
image2 = ""
for j in range(h):
temp = image[j][i]
print(temp+temp,end="")
image2 += temp + temp
print()
print(image2)
``` | vfc_17622 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/523/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n.*.\n.*.\n",
"output": "....\n....\n****\n****\n....\n....\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1968 | Solve the following coding problem using the programming language python:
Valera is a collector. Once he wanted to expand his collection with exactly one antique item.
Valera knows n sellers of antiques, the i-th of them auctioned k_{i} items. Currently the auction price of the j-th object of the i-th seller is s_{ij}. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.
Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.
-----Input-----
The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 10^4 ≤ v ≤ 10^6) — the number of sellers and the units of money the Valera has.
Then n lines follow. The i-th line first contains integer k_{i} (1 ≤ k_{i} ≤ 50) the number of items of the i-th seller. Then go k_{i} space-separated integers s_{i}1, s_{i}2, ..., s_{ik}_{i} (10^4 ≤ s_{ij} ≤ 10^6) — the current prices of the items of the i-th seller.
-----Output-----
In the first line, print integer p — the number of sellers with who Valera can make a deal.
In the second line print p space-separated integers q_1, q_2, ..., q_{p} (1 ≤ q_{i} ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.
-----Examples-----
Input
3 50000
1 40000
2 20000 60000
3 10000 70000 190000
Output
3
1 2 3
Input
3 50000
1 50000
3 100000 120000 110000
3 120000 110000 120000
Output
0
-----Note-----
In the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller.
In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, v = map(int, input().split())
ans = []
for i in range(n):
a = list(map(int, input().split()))[1:]
if v > min(a):
ans.append(i + 1)
print(len(ans))
print(*ans)
``` | vfc_17626 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/441/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000\n",
"output": "3\n1 2 3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1969 | Solve the following coding problem using the programming language python:
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix $M$ of size $n \times n$ contains only 'X' and '.' (without quotes). The element in the $i$-th row and the $j$-th column $(i, j)$ is defined as $M(i, j)$, where $1 \leq i, j \leq n$. We define a cross appearing in the $i$-th row and the $j$-th column ($1 < i, j < n$) if and only if $M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $ 'X'.
The following figure illustrates a cross appearing at position $(2, 2)$ in a $3 \times 3$ matrix.
X.X
.X.
X.X
Your task is to find out the number of crosses in the given matrix $M$. Two crosses are different if and only if they appear in different rows or columns.
-----Input-----
The first line contains only one positive integer $n$ ($1 \leq n \leq 500$), denoting the size of the matrix $M$.
The following $n$ lines illustrate the matrix $M$. Each line contains exactly $n$ characters, each of them is 'X' or '.'. The $j$-th element in the $i$-th line represents $M(i, j)$, where $1 \leq i, j \leq n$.
-----Output-----
Output a single line containing only one integer number $k$ — the number of crosses in the given matrix $M$.
-----Examples-----
Input
5
.....
.XXX.
.XXX.
.XXX.
.....
Output
1
Input
2
XX
XX
Output
0
Input
6
......
X.X.X.
.X.X.X
X.X.X.
.X.X.X
......
Output
4
-----Note-----
In the first sample, a cross appears at $(3, 3)$, so the answer is $1$.
In the second sample, no crosses appear since $n < 3$, so the answer is $0$.
In the third sample, crosses appear at $(3, 2)$, $(3, 4)$, $(4, 3)$, $(4, 5)$, so the answer is $4$.
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() for i in range(n)]
ans = 0
for i in range(1, n - 1):
for j in range(1, n - 1):
if a[i][j] == 'X' and a[i + 1][j + 1] == 'X' and a[i - 1][j + 1] == 'X' and a[i + 1][j - 1] == 'X' and a[i - 1][j - 1] == 'X':
ans += 1
print(ans)
``` | vfc_17630 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1106/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n.....\n.XXX.\n.XXX.\n.XXX.\n.....\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\nXX\nXX\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1970 | Solve the following coding problem using the programming language python:
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
-----Input-----
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
-----Output-----
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
-----Examples-----
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
-----Note-----
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def check(x, y):
return 0 <= x < 8 and 0 <= y < 8
def dfs1(x, y, T=0):
nonlocal first, used
if not(check(x, y)) or used[x][y]:
return
used[x][y] = True
first.add((x, y, T))
for pair in (2, 2), (2, -2), (-2, 2), (-2, -2):
dfs1(x + pair[0], y + pair[1], 1 - T)
def dfs2(x, y, T=0):
nonlocal second, used
if not(check(x, y)) or used[x][y]:
return
used[x][y] = True
second.add((x, y, T))
for pair in (2, 2), (2, -2), (-2, 2), (-2, -2):
dfs2(x + pair[0], y + pair[1], 1 - T)
t = int(input())
for i in range(t):
if i > 0:
kuzma = input()
board = [input() for i in range(8)]
FoundFirst = False
for i in range(8):
for j in range(8):
if board[i][j] == 'K':
if not(FoundFirst):
First = (i, j)
FoundFirst = True
else:
Second = (i, j)
used = [[0 for i in range(8)] for j in range(8)]
first = set()
dfs1(First[0], First[1])
used = [[0 for i in range(8)] for j in range(8)]
second = set()
dfs2(Second[0], Second[1])
intersection = first & second
IsOk = False
for x, y, t in intersection:
if board[x][y] != '#':
print("YES")
IsOk = True
break
if not(IsOk):
print("NO")
board = []
``` | vfc_17634 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/362/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#\n",
"output": "YES\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n####K#K#\n\n........\nK......K\n........\n#......#\n.#....#.\n..####..\n........\n........\n\n.#..#...\n.##.##..\n..###...\n..#K###.\n..####..\n......K.\n..#####.\n..#####.\n",
"output": "NO\nNO\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n...#...#\n........\n.#...K..\n........\n...#...#\n........\n.K...#..\n........\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nK.#....#\n...#..#.\n..#.....\n..#.###.\n..#.....\n...#....\n.#.....#\n.#...##K\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1971 | Solve the following coding problem using the programming language python:
A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q^2 = [2, 3, 4, 5, 1].
This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q^2 = p. If there are several such q find any of them.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^6) — the number of elements in permutation p.
The second line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the elements of permutation p.
-----Output-----
If there is no permutation q such that q^2 = p print the number "-1".
If the answer exists print it. The only line should contain n different integers q_{i} (1 ≤ q_{i} ≤ n) — the elements of the permutation q. If there are several solutions print any of them.
-----Examples-----
Input
4
2 1 4 3
Output
3 4 2 1
Input
4
2 1 3 4
Output
-1
Input
5
2 3 4 5 1
Output
4 5 1 2 3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math
import sys
input = sys.stdin.readline
n = int(input())
a = [int(_) - 1 for _ in input().split()]
vis = [False] * n
cycles = [[] for _ in range(n + 1)]
for i in range(n):
if vis[i]: continue
cur = i
cycle = []
while not vis[cur]:
vis[cur] = True
cycle.append(cur)
cur = a[cur]
cycles[len(cycle)].append(cycle)
p = [0] * n
for i in range(n + 1):
if i % 2 == 1:
for j in cycles[i]:
for k in range(i):
p[j[k]] = j[(k + (i + 1) // 2) % i]
else:
if len(cycles[i]) % 2 == 1:
print(-1)
return
for j in range(0, len(cycles[i]), 2):
for k in range(i):
p[cycles[i][j][k]] = cycles[i][j + 1][k]
p[cycles[i][j + 1][k]] = cycles[i][j][(k + 1) % i]
print(' '.join([str(i + 1) for i in p]))
``` | vfc_17638 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/612/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n2 1 4 3\n",
"output": "3 4 2 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2 1 3 4\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n2 3 4 5 1\n",
"output": "4 5 1 2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1972 | Solve the following coding problem using the programming language python:
You are given an array $a$ consisting of $500000$ integers (numbered from $1$ to $500000$). Initially all elements of $a$ are zero.
You have to process two types of queries to this array: $1$ $x$ $y$ — increase $a_x$ by $y$; $2$ $x$ $y$ — compute $\sum\limits_{i \in R(x, y)} a_i$, where $R(x, y)$ is the set of all integers from $1$ to $500000$ which have remainder $y$ modulo $x$.
Can you process all the queries?
-----Input-----
The first line contains one integer $q$ ($1 \le q \le 500000$) — the number of queries.
Then $q$ lines follow, each describing a query. The $i$-th line contains three integers $t_i$, $x_i$ and $y_i$ ($1 \le t_i \le 2$). If $t_i = 1$, then it is a query of the first type, $1 \le x_i \le 500000$, and $-1000 \le y_i \le 1000$. If $t_i = 2$, then it it a query of the second type, $1 \le x_i \le 500000$, and $0 \le y_i < x_i$.
It is guaranteed that there will be at least one query of type $2$.
-----Output-----
For each query of type $2$ print one integer — the answer to it.
-----Example-----
Input
5
1 3 4
2 3 0
2 4 3
1 4 -4
2 1 0
Output
4
4
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
n = 500001
sqrt = int(0.75 * n**0.5)
data = [0]*(n)
ans = [[]]
out = []
for i in range(1, sqrt):
ans.append([0]*i)
j = int(sys.stdin.readline())
qus = sys.stdin.readlines()
for qu in qus:
q = [int(i) for i in qu.split()]
if q[0] == 1:
x = q[1]
y = q[2]
data[x] += y
for i in range(1, sqrt):
ans[i][x%i] += y
else:
if q[1] < sqrt:
out.append(str(ans[q[1]][q[2]]))
else:
out.append(str(sum([data[i] for i in range(q[2], n, q[1])])))
sys.stdout.write('\n'.join(out) + '\n')
``` | vfc_17642 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1207/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 3 4\n2 3 0\n2 4 3\n1 4 -4\n2 1 0\n",
"output": "4\n4\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 3 4\n2 3 0\n2 4 3\n1 500000 1\n2 800 0\n",
"output": "4\n4\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 500000 1\n2 499999 1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1973 | Solve the following coding problem using the programming language python:
This problem is same as the next one, but has smaller constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the $n$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $i$-th day has a ribbon with color $u_i$. Shiro wants to know the largest number $x$, such that if we consider the streak of the first $x$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $x - 1$ will have the same number of occurrences.
For example, consider the following sequence of $u_i$: $[2, 2, 1, 1, 5, 4, 4, 5]$. Then $x = 7$ makes a streak, since if we remove the leftmost $u_i = 5$, each ribbon color will appear exactly twice in the prefix of $x - 1$ days. Note that $x = 8$ doesn't form a streak, since you must remove exactly one day.
Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the total number of days.
The second line contains $n$ integers $u_1, u_2, \ldots, u_n$ ($1 \leq u_i \leq 10$) — the colors of the ribbons the cats wear.
-----Output-----
Print a single integer $x$ — the largest possible streak of days.
-----Examples-----
Input
13
1 1 1 2 2 2 3 3 3 4 4 4 5
Output
13
Input
5
10 2 5 4 1
Output
5
Input
1
10
Output
1
Input
7
3 2 1 1 4 5 1
Output
6
Input
6
1 1 1 2 2 2
Output
5
-----Note-----
In the first example, we can choose the longest streak of $13$ days, since upon removing the last day out of the streak, all of the remaining colors $1$, $2$, $3$, and $4$ will have the same number of occurrences of $3$. Note that the streak can also be $10$ days (by removing the $10$-th day from this streak) but we are interested in the longest streak.
In the fourth example, if we take the streak of the first $6$ days, we can remove the third day from this streak then all of the remaining colors $1$, $2$, $3$, $4$ and $5$ will occur exactly once.
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())
u = [int(u) for u in input().split()]
NMAX = 100005
suma = [0 for _ in range(NMAX)]
total = [0 for _ in range(NMAX)]
diferentes = 0
sol = 0
maximo = 1
for i, v in enumerate(u):
if total[v] == 0:
diferentes += 1
else:
suma[total[v]] -= 1
total[v] += 1
suma[total[v]] += 1
maximo = max(maximo, total[v])
#print(i, v, ":", diferentes)
#print(suma)
#print(total)
#print(maximo, ":", suma[maximo], suma[maximo+1], diferentes-1)
#print(maximo, ":", suma[maximo-1], suma[maximo], diferentes-1)
if diferentes <= 1:
sol = i
if suma[maximo-1] == diferentes-1 and suma[maximo] == 1:
sol = i
if suma[maximo] == diferentes-1 and suma[1] == 1:
sol = i
if suma[1] == diferentes:
sol = i
#print("SOL", sol)
print(sol+1)
``` | vfc_17646 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1163/B1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "13\n1 1 1 2 2 2 3 3 3 4 4 4 5\n",
"output": "13",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1974 | Solve the following coding problem using the programming language python:
There are $n$ robbers at coordinates $(a_1, b_1)$, $(a_2, b_2)$, ..., $(a_n, b_n)$ and $m$ searchlight at coordinates $(c_1, d_1)$, $(c_2, d_2)$, ..., $(c_m, d_m)$.
In one move you can move each robber to the right (increase $a_i$ of each robber by one) or move each robber up (increase $b_i$ of each robber by one). Note that you should either increase all $a_i$ or all $b_i$, you can't increase $a_i$ for some points and $b_i$ for some other points.
Searchlight $j$ can see a robber $i$ if $a_i \leq c_j$ and $b_i \leq d_j$.
A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair $i,j$ such that searchlight $j$ can see a robber $i$).
What is the minimum number of moves you need to perform to reach a safe configuration?
-----Input-----
The first line of input contains two integers $n$ and $m$ ($1 \leq n, m \leq 2000$): the number of robbers and the number of searchlight.
Each of the next $n$ lines contains two integers $a_i$, $b_i$ ($0 \leq a_i, b_i \leq 10^6$), coordinates of robbers.
Each of the next $m$ lines contains two integers $c_i$, $d_i$ ($0 \leq c_i, d_i \leq 10^6$), coordinates of searchlights.
-----Output-----
Print one integer: the minimum number of moves you need to perform to reach a safe configuration.
-----Examples-----
Input
1 1
0 0
2 3
Output
3
Input
2 3
1 6
6 1
10 1
1 10
7 7
Output
4
Input
1 2
0 0
0 0
0 0
Output
1
Input
7 3
0 8
3 8
2 7
0 10
5 5
7 0
3 5
6 6
3 11
11 5
Output
6
-----Note-----
In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates $(3, 0)$.
The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates $(2, 3)$ and $3 > 2$.
In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates $(3, 8)$, $(8, 3)$.
It's easy the see that the configuration of the robbers is safe.
It can be proved that you can't reach a safe configuration using no more than $3$ moves.
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 = lambda: sys.stdin.readline().rstrip()
N, M = list(map(int, input().split()))
X = []
for _ in range(N):
a, b = list(map(int, input().split()))
X.append((a, b))
Y = []
for _ in range(M):
c, d = list(map(int, input().split()))
c, d = c, d+1
Y.append((c, d))
Y.sort(key = lambda x: -x[0])
Z = [0] * 1001001
for a, b in X:
for c, d in Y:
if c >= a:
Z[c-a] = max(Z[c-a], d - b)
ans = 1 << 30
ma = 0
for i in range(1001000)[::-1]:
ma = max(ma, Z[i])
ans = min(ans, ma + i)
print(ans)
``` | vfc_17650 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1408/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 1\n0 0\n2 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n1 6\n6 1\n10 1\n1 10\n7 7\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\n0 0\n0 0\n0 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 3\n0 8\n3 8\n2 7\n0 10\n5 5\n7 0\n3 5\n6 6\n3 11\n11 5\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n0 0\n0 0\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1975 | Solve the following coding problem using the programming language python:
Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule: either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before); or the girl in the dancing pair must dance for the first time.
Help Fox Ciel to make a schedule that they can dance as many songs as possible.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of boys and girls in the dancing room.
-----Output-----
In the first line print k — the number of songs during which they can dance. Then in the following k lines, print the indexes of boys and girls dancing during songs chronologically. You can assume that the boys are indexed from 1 to n, and the girls are indexed from 1 to m.
-----Examples-----
Input
2 1
Output
2
1 1
2 1
Input
2 2
Output
3
1 1
1 2
2 2
-----Note-----
In test case 1, there are 2 boys and 1 girl. We can have 2 dances: the 1st boy and 1st girl (during the first song), the 2nd boy and 1st girl (during the second song).
And in test case 2, we have 2 boys with 2 girls, the answer is 3.
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())
print(n + m - 1)
for i in range(1, m + 1):
print(1, i)
for i in range(2, n + 1):
print(i, 1)
``` | vfc_17654 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/322/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 1\n",
"output": "2\n1 1\n2 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n",
"output": "3\n1 1\n1 2\n2 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n",
"output": "1\n1 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n",
"output": "4\n1 1\n1 2\n1 3\n2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4\n",
"output": "7\n1 1\n1 2\n1 3\n1 4\n4 4\n3 4\n2 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 12\n",
"output": "12\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n1 12\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1976 | Solve the following coding problem using the programming language python:
Recently Luba bought a monitor. Monitor is a rectangular matrix of size n × m. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square k × k consisting entirely of broken pixels. She knows that q pixels are already broken, and for each of them she knows the moment when it stopped working. Help Luba to determine when the monitor became broken (or tell that it's still not broken even after all q pixels stopped working).
-----Input-----
The first line contains four integer numbers n, m, k, q (1 ≤ n, m ≤ 500, 1 ≤ k ≤ min(n, m), 0 ≤ q ≤ n·m) — the length and width of the monitor, the size of a rectangle such that the monitor is broken if there is a broken rectangle with this size, and the number of broken pixels.
Each of next q lines contain three integer numbers x_{i}, y_{i}, t_{i} (1 ≤ x_{i} ≤ n, 1 ≤ y_{i} ≤ m, 0 ≤ t_{ ≤ 10}^9) — coordinates of i-th broken pixel (its row and column in matrix) and the moment it stopped working. Each pixel is listed at most once.
We consider that pixel is already broken at moment t_{i}.
-----Output-----
Print one number — the minimum moment the monitor became broken, or "-1" if it's still not broken after these q pixels stopped working.
-----Examples-----
Input
2 3 2 5
2 1 8
2 2 8
1 2 1
1 3 4
2 3 2
Output
8
Input
3 3 2 5
1 2 2
2 2 1
2 3 5
3 2 10
2 1 100
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
from operator import itemgetter
n, m, k, q = list(map(int, input().split()))
query = sorted((list(map(int, line.split()))
for line in sys.stdin), key=itemgetter(2))
times = [q[2] for q in query]
def solve(ti):
imos = [[0]*(m+1) for _ in range(n+1)]
for i in range(ti):
imos[query[i][0]][query[i][1]] += 1
for i in range(n+1):
for j in range(m):
imos[i][j+1] += imos[i][j]
for j in range(m+1):
for i in range(n):
imos[i+1][j] += imos[i][j]
for i in range(k, n+1):
for j in range(k, m+1):
if imos[i][j] - imos[i-k][j] - imos[i][j-k] + imos[i-k][j-k] == k*k:
return True
return False
inf = len(times)+1
ok, ng = inf, 0
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
if mid >= k*k and solve(mid):
ok = mid
else:
ng = mid
print(times[ok-1] if ok != inf else -1)
``` | vfc_17658 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/846/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3 2 5\n2 1 8\n2 2 8\n1 2 1\n1 3 4\n2 3 2\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 2 5\n1 2 2\n2 2 1\n2 3 5\n3 2 10\n2 1 100\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "29 50 5 29\n21 42 1565821\n21 43 53275635\n21 44 2717830\n21 45 9579585\n21 46 20725775\n22 42 2568372\n22 43 9584662\n22 44 31411635\n22 45 5089311\n22 46 4960702\n23 42 11362237\n23 43 42200296\n23 44 18762146\n23 45 8553819\n23 46 4819516\n24 42 10226552\n24 43 21022685\n24 44 32940182\n24 45 39208099\n24 46 3119232\n25 42 8418247\n25 43 4093694\n25 44 9162006\n25 45 328637\n25 46 13121717\n6 21 3147344\n28 26 12445148\n5 7 925220\n25 35 170187\n",
"output": "53275635\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "500 500 1 0\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1977 | Solve the following coding problem using the programming language python:
You are given a matrix of size $n \times n$ filled with lowercase English letters. You can change no more than $k$ letters in this matrix.
Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $2n - 1$.
Find the lexicographically smallest string that can be associated with a path after changing letters in at most $k$ cells of the matrix.
A string $a$ is lexicographically smaller than a string $b$, if the first different letter in $a$ and $b$ is smaller in $a$.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n \le 2000$, $0 \le k \le n^2$) — the size of the matrix and the number of letters you can change.
Each of the next $n$ lines contains a string of $n$ lowercase English letters denoting one row of the matrix.
-----Output-----
Output the lexicographically smallest string that can be associated with some valid path after changing no more than $k$ letters in the matrix.
-----Examples-----
Input
4 2
abcd
bcde
bcad
bcde
Output
aaabcde
Input
5 3
bwwwz
hrhdh
sepsp
sqfaf
ajbvw
Output
aaaepfafw
Input
7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz
Output
aaaaaaadudsnz
-----Note-----
In the first sample test case it is possible to change letters 'b' in cells $(2, 1)$ and $(3, 1)$ to 'a', then the minimum path contains cells $(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)$. The first coordinate corresponds to the row and the second coordinate corresponds to the column.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from array import array
inf = (1 << 30)
def main():
(n,k) = [int(x) for x in input().split(' ')]
Matrix = []
for i in range(n):
Matrix.append(array('b',[ord(x) for x in input()]))
dp = [array('l', [inf for j in range(n)]) for i in range(n)]
direct = [[ord('d') for j in range(n)] for i in range(n)]
opt = ""
for s in range (2 * n - 1):
opchar = chr(ord('z') + 1)
positions = []
for i in range(0, s+1):
j = s - i;
if j < n and i < n:
if(i > 0 and j > 0):
if(dp[i-1][j] < dp[i][j-1]):
dp[i][j] = dp[i-1][j]
direct[i][j] = 'l'
else:
dp[i][j] = dp[i][j-1]
direct[i][j] = 'd'
elif i > 0:
dp[i][j] = dp[i-1][j]
direct[i][j] = 'l'
elif j > 0:
dp[i][j] = dp[i][j-1]
direct[i][j] = 'd'
else:
dp[i][j] = 0
direct[i][j] = 'e'
if(dp[i][j] < k and Matrix[i][j] is not ord('a')):
dp[i][j]+=1
Matrix[i][j] = ord('a')
if(Matrix[i][j] < ord(opchar) and dp[i][j] <= k):
opchar = chr(Matrix[i][j])
for i in range(0, s+1):
j = s - i;
if j < n and i < n:
if(Matrix[i][j] is not ord(opchar)):
dp[i][j] = inf
ans = ""
a,b = (n-1,n-1)
while(direct[a][b] is not 'e'):
ans += chr(Matrix[a][b])
if(direct[a][b] is 'l'):
a-=1
else:
b-=1
ans += chr(Matrix[0][0])
print(ans[::-1])
main()
``` | vfc_17662 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1031/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2\nabcd\nbcde\nbcad\nbcde\n",
"output": "aaabcde\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3\nbwwwz\nhrhdh\nsepsp\nsqfaf\najbvw\n",
"output": "aaaepfafw\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 6\nypnxnnp\npnxonpm\nnxanpou\nxnnpmud\nnhtdudu\nnpmuduh\npmutsnz\n",
"output": "aaaaaaadudsnz\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 0\ng\n",
"output": "g\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1978 | Solve the following coding problem using the programming language python:
The main characters have been omitted to be short.
You are given a directed unweighted graph without loops with $n$ vertexes and a path in it (that path is not necessary simple) given by a sequence $p_1, p_2, \ldots, p_m$ of $m$ vertexes; for each $1 \leq i < m$ there is an arc from $p_i$ to $p_{i+1}$.
Define the sequence $v_1, v_2, \ldots, v_k$ of $k$ vertexes as good, if $v$ is a subsequence of $p$, $v_1 = p_1$, $v_k = p_m$, and $p$ is one of the shortest paths passing through the vertexes $v_1$, $\ldots$, $v_k$ in that order.
A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $p$ is good but your task is to find the shortest good subsequence.
If there are multiple shortest good subsequences, output any of them.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 100$) — the number of vertexes in a graph.
The next $n$ lines define the graph by an adjacency matrix: the $j$-th character in the $i$-st line is equal to $1$ if there is an arc from vertex $i$ to the vertex $j$ else it is equal to $0$. It is guaranteed that the graph doesn't contain loops.
The next line contains a single integer $m$ ($2 \le m \le 10^6$) — the number of vertexes in the path.
The next line contains $m$ integers $p_1, p_2, \ldots, p_m$ ($1 \le p_i \le n$) — the sequence of vertexes in the path. It is guaranteed that for any $1 \leq i < m$ there is an arc from $p_i$ to $p_{i+1}$.
-----Output-----
In the first line output a single integer $k$ ($2 \leq k \leq m$) — the length of the shortest good subsequence. In the second line output $k$ integers $v_1$, $\ldots$, $v_k$ ($1 \leq v_i \leq n$) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.
-----Examples-----
Input
4
0110
0010
0001
1000
4
1 2 3 4
Output
3
1 2 4
Input
4
0110
0010
1001
1000
20
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
Output
11
1 2 4 2 4 2 4 2 4 2 4
Input
3
011
101
110
7
1 2 3 1 3 2 1
Output
7
1 2 3 1 3 2 1
Input
4
0110
0001
0001
1000
3
1 2 4
Output
2
1 4
-----Note-----
Below you can see the graph from the first example:
[Image]
The given path is passing through vertexes $1$, $2$, $3$, $4$. The sequence $1-2-4$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $1$, $2$ and $4$ in that order is $1-2-3-4$. Note that subsequences $1-4$ and $1-3-4$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $1-3-4$.
In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.
In the fourth example, the paths $1-2-4$ and $1-3-4$ are the shortest paths passing through the vertexes $1$ and $4$.
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())
INF = 10 ** 18
g = [[INF for i in range(n)] for _ in range(n)]
for i in range(n):
s = input().rstrip()
for j in range(n):
if s[j] == '1':
g[i][j] = 1
g[i][i] = 0
for k in range(n):
for i in range(n):
for j in range(n):
g[i][j] = min(g[i][j], g[i][k] + g[k][j])
m = int(input())
p = [int(i) - 1 for i in input().split()]
ptr = 1
ans = [p[0]]
while ptr + 1 < len(p):
s = ans[-1]
if g[s][p[ptr]] + 1 != g[s][p[ptr + 1]]:
ans.append(p[ptr])
ptr += 1
ans.append(p[-1])
print(len(ans))
for i in ans:
print(i + 1, end=" ")
``` | vfc_17666 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1204/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n0110\n0010\n0001\n1000\n4\n1 2 3 4\n",
"output": "3\n1 2 4 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4\n",
"output": "11\n1 2 4 2 4 2 4 2 4 2 4 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n011\n101\n110\n7\n1 2 3 1 3 2 1\n",
"output": "7\n1 2 3 1 3 2 1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n0110\n0001\n0001\n1000\n3\n1 2 4\n",
"output": "2\n1 4 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n01\n00\n2\n1 2\n",
"output": "2\n1 2 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1980 | Solve the following coding problem using the programming language python:
Vasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit.
Vasya has $n$ problems to choose from. They are numbered from $1$ to $n$. The difficulty of the $i$-th problem is $d_i$. Moreover, the problems are given in the increasing order by their difficulties. The difficulties of all tasks are pairwise distinct. In order to add the $i$-th problem to the contest you need to pay $c_i$ burles to its author. For each problem in the contest Vasya gets $a$ burles.
In order to create a contest he needs to choose a consecutive subsegment of tasks.
So the total earnings for the contest are calculated as follows: if Vasya takes problem $i$ to the contest, he needs to pay $c_i$ to its author; for each problem in the contest Vasya gets $a$ burles; let $gap(l, r) = \max\limits_{l \le i < r} (d_{i + 1} - d_i)^2$. If Vasya takes all the tasks with indices from $l$ to $r$ to the contest, he also needs to pay $gap(l, r)$. If $l = r$ then $gap(l, r) = 0$.
Calculate the maximum profit that Vasya can earn by taking a consecutive segment of tasks.
-----Input-----
The first line contains two integers $n$ and $a$ ($1 \le n \le 3 \cdot 10^5$, $1 \le a \le 10^9$) — the number of proposed tasks and the profit for a single problem, respectively.
Each of the next $n$ lines contains two integers $d_i$ and $c_i$ ($1 \le d_i, c_i \le 10^9, d_i < d_{i+1}$).
-----Output-----
Print one integer — maximum amount of burles Vasya can earn.
-----Examples-----
Input
5 10
1 15
5 3
6 11
7 2
11 22
Output
13
Input
3 5
1 8
2 19
3 11
Output
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
it = iter(sys.stdin.readlines())
input = it.__next__
n, k = list(map(int, input().split()))
d, c = [0] * n, [0] * n
for i in range(n):
a, b = list(map(int, input().split()))
d[i], c[i] = a, k - b
p, r, pre, suf, sm, mx = list(range(n)), [0] * n, c[:], c[:], c[:], c[:]
def find(x):
if x != p[x]:
p[x] = find(p[x])
return p[x]
def union(x, y, w):
x, y = find(x), find(y)
z = y if r[y] > r[x] else x
r[x] += r[x] == r[y]
mx[z] = max(mx[x], mx[y], suf[x] + pre[y])
pre[z] = max(pre[x], sm[x] + pre[y])
suf[z] = max(suf[x] + sm[y], suf[y])
sm[z] = sm[x] + sm[y]
p[x] = p[y] = z
return mx[z] - w ** 2
ans = max(0, max(c))
for w, i in sorted((d[i + 1] - d[i], i) for i in range(n - 1)):
ans = max(ans, union(i, i + 1, w))
print(ans)
``` | vfc_17674 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1107/G",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 10\n1 15\n5 3\n6 11\n7 2\n11 22\n",
"output": "13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 5\n1 8\n2 19\n3 11\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 8\n1 16\n23 27\n26 2\n32 21\n38 50\n51 53\n62 79\n77 97\n94 18\n100 5\n",
"output": "6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1982 | Solve the following coding problem using the programming language python:
You are given two integers $n$ and $k$. Your task is to find if $n$ can be represented as a sum of $k$ distinct positive odd (not divisible by $2$) integers or not.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 10^5$) — the number of test cases.
The next $t$ lines describe test cases. The only line of the test case contains two integers $n$ and $k$ ($1 \le n, k \le 10^7$).
-----Output-----
For each test case, print the answer — "YES" (without quotes) if $n$ can be represented as a sum of $k$ distinct positive odd (not divisible by $2$) integers and "NO" otherwise.
-----Example-----
Input
6
3 1
4 2
10 3
10 2
16 4
16 5
Output
YES
YES
NO
YES
YES
NO
-----Note-----
In the first test case, you can represent $3$ as $3$.
In the second test case, the only way to represent $4$ is $1+3$.
In the third test case, you cannot represent $10$ as the sum of three distinct positive odd integers.
In the fourth test case, you can represent $10$ as $3+7$, for example.
In the fifth test case, you can represent $16$ as $1+3+5+7$.
In the sixth test case, you cannot represent $16$ as the sum of five distinct positive odd integers.
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):
n, k = map(int, input().split())
n -= k**2
if n<0:
print("NO")
elif n%2 == 0:
print("YES")
else:
print("NO")
``` | vfc_17682 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1327/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5\n",
"output": "YES\nYES\nNO\nYES\nYES\nNO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1983 | Solve the following coding problem using the programming language python:
Ehab has an array $a$ of length $n$. He has just enough free time to make a new array consisting of $n$ copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.
-----Input-----
The first line contains an integer $t$ — the number of test cases you need to solve. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($1 \le n \le 10^5$) — the number of elements in the array $a$.
The second line contains $n$ space-separated integers $a_1$, $a_2$, $\ldots$, $a_{n}$ ($1 \le a_i \le 10^9$) — the elements of the array $a$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each testcase, output the length of the longest increasing subsequence of $a$ if you concatenate it to itself $n$ times.
-----Example-----
Input
2
3
3 2 1
6
3 1 4 1 5 9
Output
3
5
-----Note-----
In the first sample, the new array is $[3,2,\textbf{1},3,\textbf{2},1,\textbf{3},2,1]$. The longest increasing subsequence is marked in bold.
In the second sample, the longest increasing subsequence will be $[1,3,4,5,9]$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#list(map(int,input().split()))
t=int(input())
for _ in range(t):
n=int(input())
it=list(map(int,input().split()))
print(len(set(it)))
``` | vfc_17686 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1325/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n3\n3 2 1\n6\n3 1 4 1 5 9\n",
"output": "3\n5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n7\n6 6 8 8 6 6 6\n1\n2\n5\n4 5 9 8 7\n7\n1 2 7 1 6 10 2\n",
"output": "2\n1\n5\n5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n5\n5 5 5 5 5\n3\n1 2 5\n",
"output": "1\n3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1984 | Solve the following coding problem using the programming language python:
During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same.
[Image]
When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A:
You can transmit the whole level A. Then you need to transmit n·m bytes via the network. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit d_{A}, B·w bytes, where d_{A}, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate d_{A}, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other.
Your task is to find a way to transfer all the k levels and minimize the traffic.
-----Input-----
The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters.
-----Output-----
In the first line print the required minimum number of transferred bytes.
Then print k pairs of integers x_1, y_1, x_2, y_2, ..., x_{k}, y_{k}, describing the way to transfer levels. Pair x_{i}, y_{i} means that level x_{i} needs to be transferred by way y_{i}. If y_{i} equals 0, that means that the level must be transferred using the first way, otherwise y_{i} must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels y_{i} and x_{i} to transfer level x_{i}. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input.
If there are multiple optimal solutions, you can print any of them.
-----Examples-----
Input
2 3 3 2
A.A
...
A.a
..C
X.Y
...
Output
14
1 0
2 1
3 1
Input
1 1 4 1
A
.
B
.
Output
3
1 0
2 0
4 2
3 0
Input
1 3 5 2
ABA
BBB
BBA
BAB
ABB
Output
11
1 0
3 1
2 3
4 2
5 1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def put():
return list(map(int, input().split()))
def diff(x,y):
ans = 0
for i in range(n*m):
if s[x][i]!= s[y][i]:
ans+=1
return ans
def find(i):
if i==p[i]:
return i
p[i] = find(p[i])
return p[i]
def union(i,j):
if rank[i]>rank[j]:
i,j = j,i
elif rank[i]==rank[j]:
rank[j]+=1
p[i]= j
def dfs(i,p):
if i!=0:
print(i,p)
for j in tree[i]:
if j!=p:
dfs(j,i)
n,m,k,w = put()
s = ['']*k
for i in range(k):
for j in range(n):
s[i]+=input()
edge = []
k+=1
rank = [0]*(k)
p = list(range(k))
cost = 0
tree = [[] for i in range(k)]
for i in range(k):
for j in range(i+1,k):
if i==0:
z=n*m
else:
z = diff(i-1,j-1)*w
edge.append((z,i,j))
edge.sort()
for z,i,j in edge:
u = find(i)
v = find(j)
if u!=v:
union(u,v)
cost+= z
tree[i].append(j)
tree[j].append(i)
print(cost)
dfs(0,-1)
``` | vfc_17690 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/436/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3 3 2\nA.A\n...\nA.a\n..C\nX.Y\n...\n",
"output": "14\n1 0\n2 1\n3 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 4 1\nA\n.\nB\n.\n",
"output": "3\n1 0\n2 0\n4 2\n3 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 3 5 2\nABA\nBBB\nBBA\nBAB\nABB\n",
"output": "11\n1 0\n3 1\n2 3\n4 2\n5 1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1985 | Solve the following coding problem using the programming language python:
Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave a_{i} points.
Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n ≤ k) values b_1, b_2, ..., b_{n} (it is guaranteed that all values b_{j} are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.
Your task is to determine the number of options for the score the participant could have before the judges rated the participant.
-----Input-----
The first line contains two integers k and n (1 ≤ n ≤ k ≤ 2 000) — the number of jury members and the number of scores Polycarp remembers.
The second line contains k integers a_1, a_2, ..., a_{k} ( - 2 000 ≤ a_{i} ≤ 2 000) — jury's marks in chronological order.
The third line contains n distinct integers b_1, b_2, ..., b_{n} ( - 4 000 000 ≤ b_{j} ≤ 4 000 000) — the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.
-----Output-----
Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes).
-----Examples-----
Input
4 1
-5 5 0 20
10
Output
3
Input
2 2
-2000 -2000
3998000 4000000
Output
1
-----Note-----
The answer for the first example is 3 because initially the participant could have - 10, 10 or 15 points.
In the second example there is only one correct initial score equaling to 4 002 000.
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
k, n = map(int, stdin.readline().split())
a = list(map(int, stdin.readline().split()))
b = list(map(int, stdin.readline().split()))
res = set()
for i in range(k):
# putting b[0] on place i
our = set()
curr = b[0]
for j in range(i, -1, -1):
our.add(curr)
curr -= a[j]
first = curr
good = True
curr = b[0]
for j in range(i + 1, k):
curr += a[j]
our.add(curr)
for elem in b:
if elem not in our:
good = False
break
if good:
res.add(first)
print(len(res))
main()
``` | vfc_17694 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/831/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 1\n-5 5 0 20\n10\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n-2000 -2000\n3998000 4000000\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n-577\n1273042\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n614 -1943\n3874445\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1\n1416 -1483 1844\n3261895\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1986 | Solve the following coding problem using the programming language python:
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.
The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers f_{i} and t_{i}. Value t_{i} shows the time the Rabbits need to lunch in the i-th restaurant. If time t_{i} exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal f_{i} - (t_{i} - k). Otherwise, the Rabbits get exactly f_{i} units of joy.
Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
-----Input-----
The first line contains two space-separated integers — n (1 ≤ n ≤ 10^4) and k (1 ≤ k ≤ 10^9) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — f_{i} (1 ≤ f_{i} ≤ 10^9) and t_{i} (1 ≤ t_{i} ≤ 10^9) — the characteristics of the i-th restaurant.
-----Output-----
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
-----Examples-----
Input
2 5
3 3
4 5
Output
4
Input
4 6
5 8
3 6
2 3
2 2
Output
3
Input
1 5
1 7
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
(n, k) = [int(x) for x in sys.stdin.readline().strip().split()]
ans = -999999999999999999999999999999999999999999
for i in range(0, n):
(f, t) = [int(x) for x in sys.stdin.readline().strip().split()]
ans = max(ans, f-max(0,t-k))
print(ans)
``` | vfc_17698 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/276/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 5\n3 3\n4 5\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 6\n5 8\n3 6\n2 3\n2 2\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 5\n1 7\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 9\n10 13\n4 18\n13 3\n10 6\n",
"output": "13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1 1000000000\n",
"output": "-999999998\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1000000000 1000000000\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1987 | Solve the following coding problem using the programming language python:
Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once.
Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c_1 + c_2·(x - 1)^2 (in particular, if the group consists of one person, then the price is c_1).
All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group.
-----Input-----
The first line contains three integers n, c_1 and c_2 (1 ≤ n ≤ 200 000, 1 ≤ c_1, c_2 ≤ 10^7) — the number of visitors and parameters for determining the ticket prices for a group.
The second line contains the string of length n, which consists of zeros and ones. If the i-th symbol of the string is zero, then the i-th visitor is a pupil, otherwise the i-th person is an adult. It is guaranteed that there is at least one adult. It is possible that there are no pupils.
-----Output-----
Print the minimum price of visiting the most extreme attraction for all pupils and their parents. Each of them should roll on the attraction exactly once.
-----Examples-----
Input
3 4 1
011
Output
8
Input
4 7 2
1101
Output
18
-----Note-----
In the first test one group of three people should go to the attraction. Then they have to pay 4 + 1 * (3 - 1)^2 = 8.
In the second test it is better to go to the attraction in two groups. The first group should consist of two adults (for example, the first and the second person), the second should consist of one pupil and one adult (the third and the fourth person). Then each group will have a size of two and for each the price of ticket is 7 + 2 * (2 - 1)^2 = 9. Thus, the total price for two groups is 18.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t = input()
t = t.split()
n = int(t[0])
c1 = int(t[1])
c2 = int(t[2])
t = input()
d = 0
for i in t:
if(i=="1"):
d = d+1
min = 10**1488
for i in range(1, d+1):
t = c1*i + i*c2*(((n//i)-1)**2) + c2*(n%i)*(2*(n//i)-1)
if t<min:
min = t
print(min)
``` | vfc_17702 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/774/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4 1\n011\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 7 2\n1101\n",
"output": "18\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2 2\n1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3 10\n01\n",
"output": "13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 10 3\n11100\n",
"output": "35\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 2 2\n1111101111\n",
"output": "20\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1988 | Solve the following coding problem using the programming language python:
Vasya has a string $s$ of length $n$. He decides to make the following modification to the string: Pick an integer $k$, ($1 \leq k \leq n$). For $i$ from $1$ to $n-k+1$, reverse the substring $s[i:i+k-1]$ of $s$. For example, if string $s$ is qwer and $k = 2$, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length $2$) weqr (after reversing the second substring of length $2$) werq (after reversing the last substring of length $2$) Hence, the resulting string after modifying $s$ with $k = 2$ is werq.
Vasya wants to choose a $k$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $k$. Among all such $k$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.
A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds: $a$ is a prefix of $b$, but $a \ne b$; in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 5000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 5000$) — the length of the string $s$.
The second line of each test case contains the string $s$ of $n$ lowercase latin letters.
It is guaranteed that the sum of $n$ over all test cases does not exceed $5000$.
-----Output-----
For each testcase output two lines:
In the first line output the lexicographically smallest string $s'$ achievable after the above-mentioned modification.
In the second line output the appropriate value of $k$ ($1 \leq k \leq n$) that you chose for performing the modification. If there are multiple values of $k$ that give the lexicographically smallest string, output the smallest value of $k$ among them.
-----Example-----
Input
6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
Output
abab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
-----Note-----
In the first testcase of the first sample, the string modification results for the sample abab are as follows : for $k = 1$ : abab for $k = 2$ : baba for $k = 3$ : abab for $k = 4$ : baba
The lexicographically smallest string achievable through modification is abab for $k = 1$ and $3$. Smallest value of $k$ needed to achieve is hence $1$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
s = input().rstrip()
words = []
for i in range(n):
if (n - i) % 2 == 0:
words.append((s[i:] + s[:i], i+1))
else:
words.append((s[i:] + s[:i][::-1], i+1))
words.sort()
print(words[0][0])
print(words[0][1])
``` | vfc_17706 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1316/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n4\nabab\n6\nqwerty\n5\naaaaa\n6\nalaska\n9\nlfpbavjsm\n1\np\n",
"output": "abab\n1\nertyqw\n3\naaaaa\n1\naksala\n6\navjsmbpfl\n5\np\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n440\ntcjbjlbtjfmvzdqutuwzvmgqrqtrvxwrdacxcowbmbwvwssihttgdsjntiawqavwspzmybakxmwpbcgaffpyhvjrulqsorkcuozvtdbkkmasxtemrrbhqnmkpgewwphdvcyhxmatrfjkesacujihmtyqtqcjfqhpsjhgzimegvkjylapylqprykvkjavlmipewlzqsfefjzecadsqmfutgnegngmwchqttcyklocfcyuhghvtygdbsxaoxkvtgdcnsqddzzakhgrribwxkuakxkjneasowsadprpcusmbevudorsmfdjynazzyflfystiksncdgnyvelnwhcpbpdcsavmzvcwmelcruhjqktlzymndlcfshsmyfqfqejlenesnzxjqnzmwvjkwhoorczwqsglslsgrtoqcekryyghxfmzixbyjgecnfk\n",
"output": "acujihmtyqtqcjfqhpsjhgzimegvkjylapylqprykvkjavlmipewlzqsfefjzecadsqmfutgnegngmwchqttcyklocfcyuhghvtygdbsxaoxkvtgdcnsqddzzakhgrribwxkuakxkjneasowsadprpcusmbevudorsmfdjynazzyflfystiksncdgnyvelnwhcpbpdcsavmzvcwmelcruhjqktlzymndlcfshsmyfqfqejlenesnzxjqnzmwvjkwhoorczwqsglslsgrtoqcekryyghxfmzixbyjgecnfktcjbjlbtjfmvzdqutuwzvmgqrqtrvxwrdacxcowbmbwvwssihttgdsjntiawqavwspzmybakxmwpbcgaffpyhvjrulqsorkcuozvtdbkkmasxtemrrbhqnmkpgewwphdvcyhxmatrfjkes\n143\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n9\njyiqoebcn\n",
"output": "bcneoqiyj\n7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n9\nahqgpxbiw\n",
"output": "ahqgpxbiw\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n7\nydyamrb\n",
"output": "amrbydy\n4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\nk\n",
"output": "k\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1989 | Solve the following coding problem using the programming language python:
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.
There is a sequence a that consists of n integers a_1, a_2, ..., a_{n}. Let's denote f(l, r, x) the number of indices k such that: l ≤ k ≤ r and a_{k} = x. His task is to calculate the number of pairs of indicies i, j (1 ≤ i < j ≤ n) such that f(1, i, a_{i}) > f(j, n, a_{j}).
Help Pashmak with the test.
-----Input-----
The first line of the input contains an integer n (1 ≤ n ≤ 10^6). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print a single integer — the answer to the problem.
-----Examples-----
Input
7
1 2 1 1 2 2 1
Output
8
Input
3
1 1 1
Output
1
Input
5
1 2 3 4 5
Output
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
INF = 10 ** 10
def merge(l, r):
res = l + r
i = j = k = 0
while i < len(l) and j < len(r):
if l[i] < r[j]:
res[k] = l[i]
k += 1
i += 1
else:
res[k] = r[j]
k += 1
j += 1
while i < len(l):
res[k] = l[i]
k += 1
i += 1
while j < len(r):
res[k] = r[j]
k += 1
j += 1
return res
def solve(fl, fr, l, r):
if l == r:
return 0
mid = (l + r) // 2
res = solve(fl, fr, l, mid) + solve(fl, fr, mid + 1, r)
i, j = l, mid + 1
while i <= mid:
while j <= r and fr[j] < fl[i]:
j += 1
res += j - mid - 1
i += 1
fl[l: r + 1] = merge(fl[l: mid + 1], fl[mid + 1: r + 1])
fr[l: r + 1] = merge(fr[l: mid + 1], fr[mid + 1: r + 1])
return res
def __starting_point():
n = int(input())
a = list(map(int, input().split()))
fl, cnt = [], {}
for x in a:
cnt[x] = cnt.get(x, 0) + 1
fl.append(cnt[x])
fr, cnt = [], {}
for x in a[::-1]:
cnt[x] = cnt.get(x, 0) + 1
fr.append(cnt[x])
fr = fr[::-1]
# print(fl, fr)
print(solve(fl, fr, 0, n - 1))
# print(fl, fr)
__starting_point()
``` | vfc_17710 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/459/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\n1 2 1 1 2 2 1\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 1 1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1990 | Solve the following coding problem using the programming language python:
The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text.
Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters). Thus, it points to an index character. The user can move the cursor left or right one position. If the cursor is already at the first (leftmost) position, then it does not move left.
Initially, the cursor is in the first (leftmost) character.
Also, the user can write a letter or brackets (either (, or )) to the position that the cursor is currently pointing at. A new character always overwrites the old value at that position.
Your editor must check, whether the current line is the correct text. Text is correct if the brackets in them form the correct bracket sequence.
Formally, correct text (CT) must satisfy the following rules: any line without brackets is CT (the line can contain whitespaces); If the first character of the string — is (, the last — is ), and all the rest form a CT, then the whole line is a CT; two consecutively written CT is also CT.
Examples of correct texts: hello(codeforces), round, ((i)(write))edi(tor)s, ( me). Examples of incorrect texts: hello)oops(, round), ((me).
The user uses special commands to work with your editor. Each command has its symbol, which must be written to execute this command.
The correspondence of commands and characters is as follows: L — move the cursor one character to the left (remains in place if it already points to the first character); R — move the cursor one character to the right; any lowercase Latin letter or bracket (( or )) — write the entered character to the position where the cursor is now.
For a complete understanding, take a look at the first example and its illustrations in the note below.
You are given a string containing the characters that the user entered. For the brackets coloring module's work, after each command you need to:
check if the current text in the editor is a correct text; if it is, print the least number of colors that required, to color all brackets.
If two pairs of brackets are nested (the first in the second or vice versa), then these pairs of brackets should be painted in different colors. If two pairs of brackets are not nested, then they can be painted in different or the same colors. For example, for the bracket sequence ()(())()() the least number of colors is $2$, and for the bracket sequence (()(()())())(()) — is $3$.
Write a program that prints the minimal number of colors after processing each command.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 10^6$) — the number of commands.
The second line contains $s$ — a sequence of commands. The string $s$ consists of $n$ characters. It is guaranteed that all characters in a string are valid commands.
-----Output-----
In a single line print $n$ integers, where the $i$-th number is:
$-1$ if the line received after processing the first $i$ commands is not valid text, the minimal number of colors in the case of the correct text.
-----Examples-----
Input
11
(RaRbR)L)L(
Output
-1 -1 -1 -1 -1 -1 1 1 -1 -1 2
Input
11
(R)R(R)Ra)c
Output
-1 -1 1 1 -1 -1 1 1 1 -1 1
-----Note-----
In the first example, the text in the editor will take the following form:
(
^ (
^ (a
^ (a
^ (ab
^ (ab
^ (ab)
^ (ab)
^ (a))
^ (a))
^ (())
^
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# reproduction of solution № 66039386 by @windhunterSB
import sys
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (s.rstrip() for s in sys.stdin)
n = int(next(reader))
operations = next(reader)
# inf.close()
left_sum = [0] * (n + 2) # for s[:i+1]
right_sum = [0] * (n + 2) # for s[i:][::-1]
left_min = [0] * (n + 2) # min - validation of bracket sequence
right_min = [0] * (n + 2)
left_max = [0] * (n + 2) # max - depth of bracket sequence
right_max = [0] * (n + 2)
text = [0] * (n + 2) # entered text, letters marked as 0
op_map = {'(': 1,
')': -1}
ans = []
i = 1 # cursor loc i >= 1
for op in operations:
if op == 'L':
i = max(1, i - 1)
elif op == 'R':
i += 1
else:
text[i] = op_map.get(op, 0)
left_sum[i] = left_sum[i - 1] + text[i]
left_min[i] = min(left_min[i - 1], left_sum[i])
left_max[i] = max(left_max[i - 1], left_sum[i])
right_sum[i] = right_sum[i + 1] - text[i] # -text[i] cause of symmetry
right_min[i] = min(right_min[i + 1], right_sum[i])
right_max[i] = max(right_max[i + 1], right_sum[i])
correct = left_min[i] >= 0 and right_min[i + 1] >= 0 and left_sum[i] == right_sum[i + 1]
status = max(left_max[i], right_max[i + 1]) if correct else -1
ans.append(status)
print(*ans)
``` | vfc_17714 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1263/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "11\n(RaRbR)L)L(\n",
"output": "-1 -1 -1 -1 -1 -1 1 1 -1 -1 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11\n(R)R(R)Ra)c\n",
"output": "-1 -1 1 1 -1 -1 1 1 1 -1 1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\na\n",
"output": "0 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n(R)\n",
"output": "-1 -1 1 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1991 | Solve the following coding problem using the programming language python:
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he scores $1$ point, in the second game he scores $2$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up!
Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $[1,2,3]$ can yield $[3,1,2]$ but it cannot yield $[3,2,1]$ since the $2$ is in the same position.
Given a permutation of $n$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $10^{18}$.
An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows.
The first line of each test case contains integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the length of the given permutation.
The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ ($1 \leq a_{i} \leq n$) — the initial permutation.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.
-----Example-----
Input
2
5
1 2 3 4 5
7
3 2 4 5 1 6 7
Output
0
2
-----Note-----
In the first permutation, it is already sorted so no exchanges are needed.
It can be shown that you need at least $2$ exchanges to sort the second permutation.
$[3, 2, 4, 5, 1, 6, 7]$
Perform special exchange on range ($1, 5$)
$[4, 1, 2, 3, 5, 6, 7]$
Perform special exchange on range ($1, 4$)
$[1, 2, 3, 4, 5, 6, 7]$
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 *
def r1(t):
return t(input())
def r2(t):
return [t(i) for i in input().split()]
for _ in range(r1(int)):
n = r1(int)
a = r2(int)
g = True
for i in range(n):
if a[i] != i + 1:
g = False
break
if g:
print(0)
continue
g = True
c = 0
p = False
for i in range(n):
if a[i] != i + 1:
if p == False:
c += 1
p = True
else:
p = False
print(min(c, 2))
``` | vfc_17718 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1372/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n5\n1 2 3 4 5\n7\n3 2 4 5 1 6 7\n",
"output": "0\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n6\n1 5 3 4 2 6\n6\n5 1 3 4 2 6\n6\n1 5 3 4 6 2\n6\n5 1 3 4 6 2\n",
"output": "2\n2\n2\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3\n1 2 3\n4\n3 1 2 4\n7\n6 4 1 7 3 5 2\n",
"output": "0\n1\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1993 | Solve the following coding problem using the programming language python:
You are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.
Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.
For each impassable cell (x, y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x, y). You should do it for each impassable cell independently.
The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces.
To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
-----Input-----
The first line contains two integers n, m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the field.
Each of the next n lines contains m symbols: "." for empty cells, "*" for impassable cells.
-----Output-----
Print the answer as a matrix as described above. See the examples to precise the format of the output.
-----Examples-----
Input
3 3
*.*
.*.
*.*
Output
3.3
.5.
3.3
Input
4 5
**..*
..***
.*.*.
*.*.*
Output
46..3
..732
.6.4.
5.4.3
-----Note-----
In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Author : Arif Ahmad
Date :
Algo :
Difficulty :
"""
from sys import stdin, stdout
from collections import deque
g = None # contains the actual graph
h = None # h[x][y] represents the component in which cell (x,y) belongs
r = None
c = None
visited = None
total = None
comp = None
dx = [-1, 0, 0, 1]
dy = [0, -1, 1, 0]
def bfs(x, y):
nonlocal total
q = deque([(x, y)])
total += 1
visited[x][y] = True
h[x][y] = comp
while q:
x, y = q.pop()
#print('comp:', comp, 'cell:', x, y)
for k in range(4):
#print('loop:', k)
nx = x + dx[k]
ny = y + dy[k]
#print(visited)
#print('new cell:', nx, ny, 'check:', nx>=0 , nx<r , ny>=0 , ny<c , visited[nx][ny]==False , g[nx][ny]=='.')
if nx>=0 and nx<r and ny>=0 and ny<c and visited[nx][ny]==False and g[nx][ny]=='.':
q.appendleft((nx, ny))
total += 1
visited[nx][ny] = True
h[nx][ny] = comp
def main():
nonlocal g, h, r, c, visited, comp, total
r, c = [int(_) for _ in stdin.readline().split()]
g = []
for i in range(r):
line = stdin.readline()
g.append(list(line))
component = []
h = [[-1 for i in range(c)] for j in range(r)]
visited = [[False for i in range(c)] for j in range(r)]
#print(visited)
for i in range(r):
for j in range(c):
if visited[i][j] == False and g[i][j] == '.':
comp = len(component)
total = 0
#print('calling bfs', i, j)
bfs(i, j)
component.append(total)
for x in range(r):
for y in range(c):
if g[x][y] == '*':
ans = 0
idx = set()
for k in range(4):
nx = x + dx[k]
ny = y + dy[k]
if nx>=0 and nx<r and ny>=0 and ny<c and g[nx][ny]=='.':
idx.add(h[nx][ny])
for item in idx:
#print(component[item])
ans += component[item]
ans += 1
ans %= 10
g[x][y] = str(ans)
#print(component)
for i in range(r):
stdout.write(''.join(g[i]))
def __starting_point():
main()
__starting_point()
``` | vfc_17726 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/616/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3\n*.*\n.*.\n*.*\n",
"output": "3.3\n.5.\n3.3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 5\n**..*\n..***\n.*.*.\n*.*.*\n",
"output": "46..3\n..732\n.6.4.\n5.4.3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n*\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n.\n",
"output": ".\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1994 | Solve the following coding problem using the programming language python:
You have a string s = s_1s_2...s_{|}s|, where |s| is the length of string s, and s_{i} its i-th character.
Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string s_{i}s_{i} + 1...s_{j}. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|].
Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring.
-----Input-----
The single line contains a sequence of characters s_1s_2...s_{|}s| (1 ≤ |s| ≤ 10^5) — string s. The string only consists of uppercase English letters.
-----Output-----
In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers l_{i} c_{i}. Numbers l_{i} c_{i} mean that the prefix of the length l_{i} matches the suffix of length l_{i} and occurs in string s as a substring c_{i} times. Print pairs l_{i} c_{i} in the order of increasing l_{i}.
-----Examples-----
Input
ABACABA
Output
3
1 4
3 2
7 1
Input
AAA
Output
3
1 3
2 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
s = input()
n = len(s)
p = [0] * n
k = 0
for i in range(1, n):
while k != 0 and s[k] != s[i]:
k = p[k - 1]
if s[k] == s[i]:
k += 1
p[i] = k
a = []
k = n
while k != 0:
a += [k]
k = p[k - 1]
c = [0] * (n + 1)
for i in range(n):
c[p[i]] += 1
for i in range(n - 1, 1, -1):
c[p[i - 1]] += c[i]
print(len(a))
for t in reversed(a):
print(t, c[t] + 1)
``` | vfc_17730 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/432/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "ABACABA\n",
"output": "3\n1 4\n3 2\n7 1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1995 | Solve the following coding problem using the programming language python:
You are given a string s and should process m queries. Each query is described by two 1-based indices l_{i}, r_{i} and integer k_{i}. It means that you should cyclically shift the substring s[l_{i}... r_{i}] k_{i} times. The queries should be processed one after another in the order they are given.
One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.
For example, if the string s is abacaba and the query is l_1 = 3, r_1 = 6, k_1 = 1 then the answer is abbacaa. If after that we would process the query l_2 = 1, r_2 = 4, k_2 = 2 then we would get the string baabcaa.
-----Input-----
The first line of the input contains the string s (1 ≤ |s| ≤ 10 000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters.
Second line contains a single integer m (1 ≤ m ≤ 300) — the number of queries.
The i-th of the next m lines contains three integers l_{i}, r_{i} and k_{i} (1 ≤ l_{i} ≤ r_{i} ≤ |s|, 1 ≤ k_{i} ≤ 1 000 000) — the description of the i-th query.
-----Output-----
Print the resulting string s after processing all m queries.
-----Examples-----
Input
abacaba
2
3 6 1
1 4 2
Output
baabcaa
-----Note-----
The sample is described in problem statement.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s=input()
def shift(x,k):
x=x[-k:]+x[:-k]
return x
for i in range(int(input())):
l,r,k=tuple(map(int,input().split()))
l-=1
k%=(r-l)
s=s[:l]+shift(s[l:r],k)+s[r:]
print(s)
``` | vfc_17734 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/598/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "abacaba\n2\n3 6 1\n1 4 2\n",
"output": "baabcaa\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "u\n1\n1 1 1\n",
"output": "u\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "p\n5\n1 1 5\n1 1 9\n1 1 10\n1 1 10\n1 1 4\n",
"output": "p\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1996 | Solve the following coding problem using the programming language python:
Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.
Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of actions Valentin did.
The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types: Valentin pronounced some word and didn't get an electric shock. This action is described by the string ". w" (without quotes), in which "." is a dot (ASCII-code 46), and w is the word that Valentin said. Valentin pronounced some word and got an electric shock. This action is described by the string "! w" (without quotes), in which "!" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said. Valentin made a guess about the selected letter. This action is described by the string "? s" (without quotes), in which "?" is a question mark (ASCII-code 63), and s is the guess — a lowercase English letter.
All words consist only of lowercase English letters. The total length of all words does not exceed 10^5.
It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after pronouncing some word, then it contains the selected letter; and also if Valentin didn't get an electric shock after pronouncing some word, then it does not contain the selected letter.
-----Output-----
Output a single integer — the number of electric shocks that Valentin could have avoided if he had told the selected letter just after it became uniquely determined.
-----Examples-----
Input
5
! abc
. ad
. b
! cd
? c
Output
1
Input
8
! hello
! codeforces
? c
. o
? d
? h
. l
? e
Output
2
Input
7
! ababahalamaha
? a
? b
? a
? b
? a
? h
Output
0
-----Note-----
In the first test case after the first action it becomes clear that the selected letter is one of the following: a, b, c. After the second action we can note that the selected letter is not a. Valentin tells word "b" and doesn't get a shock. After that it is clear that the selected letter is c, but Valentin pronounces the word cd and gets an excessive electric shock.
In the second test case after the first two electric shocks we understand that the selected letter is e or o. Valentin tries some words consisting of these letters and after the second word it's clear that the selected letter is e, but Valentin makes 3 more actions before he makes a correct hypothesis.
In the third example the selected letter can be uniquely determined only when Valentin guesses it, so he didn't get excessive electric shocks.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n=int(input())
c=set('qwertyuiopasdfghjklzxcvbnm')
ch=False
k=0
for i in range(n-1):
s=input()
if ch:
if s[0]!='.':
k+=1
else:
if s[0]=='.':
c.difference_update(set(s[2:]))
elif s[0]=='!':
c.intersection_update(set(s[2:]))
else:
if s[2] in c:
c.remove(s[2])
if len(c)==1:
ch=True
input()
print(k)
``` | vfc_17738 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/904/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n! abc\n. ad\n. b\n! cd\n? c\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n! hello\n! codeforces\n? c\n. o\n? d\n? h\n. l\n? e\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1998 | Solve the following coding problem using the programming language python:
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.
Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").
Galya has already made k shots, all of them were misses.
Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.
It is guaranteed that there is at least one valid ships placement.
-----Input-----
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·10^5, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made.
The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
-----Output-----
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.
In the second line print the cells Galya should shoot at.
Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left.
If there are multiple answers, you can print any of them.
-----Examples-----
Input
5 1 2 1
00100
Output
2
4 2
Input
13 3 2 3
1000000010001
Output
2
7 11
-----Note-----
There is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def sum_zeroth(arr):
res = 0
for elem in arr:
res += elem[0]
return res
n, a, b, k = list(map(int, input().split()))
data = input()
dist = []
pp = 0
last = 0
for i in range(n):
if data[i] == '1':
dist.append((last, i))
pp += (i - last) // b
last = i + 1
dist.append((last, n))
pp += (n - last) // b
pos = []
minp = pp - a + 1
fnd = False
for elem in dist:
cur = elem[0] - 1
while (cur + b) < elem[1]:
cur += b
pos.append(cur + 1)
if len(pos) == minp:
fnd = True
break
if fnd:
break
print(minp)
print(' '.join(map(str, pos)))
``` | vfc_17746 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/729/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 1 2 1\n00100\n",
"output": "2\n2 5 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "13 3 2 3\n1000000010001\n",
"output": "2\n3 5 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1 0\n0\n",
"output": "1\n1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2 1 0\n00\n",
"output": "1\n1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 4 1 0\n00000\n",
"output": "2\n1 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 2 2 0\n0000000000\n",
"output": "4\n2 4 6 8 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1999 | Solve the following coding problem using the programming language python:
You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value $x$ that occurs in the array $2$ or more times. Take the first two occurrences of $x$ in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, $2 \cdot x$).
Determine how the array will look after described operations are performed.
For example, consider the given array looks like $[3, 4, 1, 2, 2, 1, 1]$. It will be changed in the following way: $[3, 4, 1, 2, 2, 1, 1]~\rightarrow~[3, 4, 2, 2, 2, 1]~\rightarrow~[3, 4, 4, 2, 1]~\rightarrow~[3, 8, 2, 1]$.
If the given array is look like $[1, 1, 3, 1, 1]$ it will be changed in the following way: $[1, 1, 3, 1, 1]~\rightarrow~[2, 3, 1, 1]~\rightarrow~[2, 3, 2]~\rightarrow~[3, 4]$.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 150\,000$) — the number of elements in the array.
The second line contains a sequence from $n$ elements $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{9}$) — the elements of the array.
-----Output-----
In the first line print an integer $k$ — the number of elements in the array after all the performed operations. In the second line print $k$ integers — the elements of the array after all the performed operations.
-----Examples-----
Input
7
3 4 1 2 2 1 1
Output
4
3 8 2 1
Input
5
1 1 3 1 1
Output
2
3 4
Input
5
10 40 20 50 30
Output
5
10 40 20 50 30
-----Note-----
The first two examples were considered in the statement.
In the third example all integers in the given array are distinct, so it will 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())
xs = [int(x) for x in input().split()]
pos = {}
for i, x in enumerate(xs):
while x in pos:
del pos[x]
x *= 2
pos[x] = i
ks = sorted(list(pos.keys()), key=lambda k: pos[k])
print(len(ks))
print(" ".join(map(str, ks)))
``` | vfc_17750 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/962/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\n3 4 1 2 2 1 1\n",
"output": "4\n3 8 2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 1 3 1 1\n",
"output": "2\n3 4 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n10 40 20 50 30\n",
"output": "5\n10 40 20 50 30 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2000 | Solve the following coding problem using the programming language python:
You are given n integers a_1, a_2, ..., a_{n}. Find the number of pairs of indexes i, j (i < j) that a_{i} + a_{j} is a power of 2 (i. e. some integer x exists so that a_{i} + a_{j} = 2^{x}).
-----Input-----
The first line contains the single positive integer n (1 ≤ n ≤ 10^5) — the number of integers.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print the number of pairs of indexes i, j (i < j) that a_{i} + a_{j} is a power of 2.
-----Examples-----
Input
4
7 3 2 1
Output
2
Input
3
1 1 1
Output
3
-----Note-----
In the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).
In the second example all pairs of indexes (i, j) (where i < j) include in answer.
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()]
def isp2(x):
return (x >= 1) and ((x & (x - 1)) == 0)
p2 = [2 ** i for i in range(33)]
d = {}
for i in a:
if i in d:
d[i] += 1
else:
d[i] = 1
k = 0
for i in d:
for p in p2:
j = p - i
if j > i:
break;
if j in d:
if i == j:
k += d[i] * (d[i] - 1) // 2
else:
k += d[i] * d[j]
print(k)
``` | vfc_17754 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/702/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n7 3 2 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 1 1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000000\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n2827343 1373647 96204862 723505 796619138 71550121 799843967 5561265 402690754 446173607\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n6 6 7 3 9 14 15 7 2 2\n",
"output": "9\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2001 | Solve the following coding problem using the programming language python:
JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into $n$ parts, places them on a row and numbers them from $1$ through $n$. For each part $i$, he defines the deliciousness of the part as $x_i \in \{0, 1\}$. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the $i$-th part then his enjoyment of the Banh-mi will increase by $x_i$ and the deliciousness of all the remaining parts will also increase by $x_i$. The initial enjoyment of JATC is equal to $0$.
For example, suppose the deliciousness of $3$ parts are $[0, 1, 0]$. If JATC eats the second part then his enjoyment will become $1$ and the deliciousness of remaining parts will become $[1, \_, 1]$. Next, if he eats the first part then his enjoyment will become $2$ and the remaining parts will become $[\_, \_, 2]$. After eating the last part, JATC's enjoyment will become $4$.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you $q$ queries, each of them consisting of two integers $l_i$ and $r_i$. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range $[l_i, r_i]$ in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo $10^9+7$.
-----Input-----
The first line contains two integers $n$ and $q$ ($1 \le n, q \le 100\,000$).
The second line contains a string of $n$ characters, each character is either '0' or '1'. The $i$-th character defines the deliciousness of the $i$-th part.
Each of the following $q$ lines contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le n$) — the segment of the corresponding query.
-----Output-----
Print $q$ lines, where $i$-th of them contains a single integer — the answer to the $i$-th query modulo $10^9 + 7$.
-----Examples-----
Input
4 2
1011
1 4
3 4
Output
14
3
Input
3 2
111
1 2
3 3
Output
3
1
-----Note-----
In the first example: For query $1$: One of the best ways for JATC to eats those parts is in this order: $1$, $4$, $3$, $2$. For query $2$: Both $3$, $4$ and $4$, $3$ ordering give the same answer.
In the second example, any order of eating parts leads to the same answer.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def add(a,b):
return (a+b)%1000000007
def mul(a,b):
return (a*b)%1000000007
def sub(a,b):
return (a-b+1000000007)%1000000007
def qpow(a, b):
r = 1
k = a
for i in range(17):
if b & (1<<i):
r = mul(r, k)
k = mul(k, k)
return r
n, q = mints()
a = list(minp())
c = [0]*(n+1)
for i in range(n):
c[i+1] = c[i] + int(a[i])
for i in range(q):
l, r = mints()
k = (r-l+1)
o = c[r]-c[l-1]
z = sub(qpow(2,o),1)
print(mul(z,qpow(2,k-o)))
``` | vfc_17758 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1062/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2\n1011\n1 4\n3 4\n",
"output": "14\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n111\n1 2\n3 3\n",
"output": "3\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 2004 | Solve the following coding problem using the programming language python:
Slava plays his favorite game "Peace Lightning". Now he is flying a bomber on a very specific map.
Formally, map is a checkered field of size 1 × n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged.
If a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell n can only move to the cell n - 1, a tank in the cell 1 can only move to the cell 2). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves.
Help Slava to destroy all tanks using as few bombs as possible.
-----Input-----
The first line contains a single integer n (2 ≤ n ≤ 100 000) — the size of the map.
-----Output-----
In the first line print m — the minimum number of bombs Slava needs to destroy all tanks.
In the second line print m integers k_1, k_2, ..., k_{m}. The number k_{i} means that the i-th bomb should be dropped at the cell k_{i}.
If there are multiple answers, you can print any of them.
-----Examples-----
Input
2
Output
3
2 1 2
Input
3
Output
4
2 1 3 2
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s=int(input())
i=2
print(s//2+s-s//2+s//2)
while(i<=s):
print(i, end= ' ')
i+=2
i=1
while(i<=s):
print(i, end= ' ')
i+=2
i=2
while(i<=s):
print(i, end= ' ')
i+=2
``` | vfc_17770 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/877/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n",
"output": "3\n2 1 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "4\n2 1 3 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "6\n2 4 1 3 2 4 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n",
"output": "9\n2 4 6 1 3 5 2 4 6 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n",
"output": "15\n2 4 6 8 10 1 3 5 7 9 2 4 6 8 10 ",
"type": "stdin_stdout"
}
]
} |
Subsets and Splits