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 | 1775 | Solve the following coding problem using the programming language python:
An army of n droids is lined up in one row. Each droid is described by m integers a_1, a_2, ..., a_{m}, where a_{i} is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it).
A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?
-----Input-----
The first line contains three integers n, m, k (1 ≤ n ≤ 10^5, 1 ≤ m ≤ 5, 0 ≤ k ≤ 10^9) — the number of droids, the number of detail types and the number of available shots, respectively.
Next n lines follow describing the droids. Each line contains m integers a_1, a_2, ..., a_{m} (0 ≤ a_{i} ≤ 10^8), where a_{i} is the number of details of the i-th type for the respective robot.
-----Output-----
Print m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length.
If there are multiple optimal solutions, print any of them.
It is not necessary to make exactly k shots, the number of shots can be less.
-----Examples-----
Input
5 2 4
4 0
1 2
2 1
0 2
1 3
Output
2 2
Input
3 2 4
1 2
1 3
2 2
Output
1 3
-----Note-----
In the first test the second, third and fourth droids will be destroyed.
In the second test the first and second droids will be destroyed.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,m,k = map(int, input().split())
mCnt = 0
ans = [0]*m
start = 0
end = 0
Q = [[] for i in range(m)]
for i in range(n):
A = list(map(int, input().split()))
z = 0
for j in range(m) :
while Q[j] and Q[j][-1][0] < A[j] :
Q[j].pop()
Q[j].append([A[j],i])
z += Q[j][0][0]
if z <= k :
end = i+1
if mCnt < end - start :
mCnt = end - start
for j in range(m) :
ans[j] = Q[j][0][0]
else :
while True :
z = 0
for j in range(m) :
if Q[j] and Q[j][0][1] == start :
Q[j].pop(0)
if Q[j] : z += Q[j][0][0]
start += 1
if z<= k : break
end += 1
for i in ans :
print(i, end = " ")
``` | vfc_16854 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/514/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 2 4\n4 0\n1 2\n2 1\n0 2\n1 3\n",
"output": "2 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 4\n1 2\n1 3\n2 2\n",
"output": "1 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 0\n0\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 0\n1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n0\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 5 33\n2 10 2 3 2\n10 6 4 5 0\n3 1 7 3 2\n4 4 2 1 5\n",
"output": "10 6 7 5 5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1776 | Solve the following coding problem using the programming language python:
Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression.
An Ahmes arithmetic expression can be defined as: "d" is an Ahmes arithmetic expression, where d is a one-digit positive integer; "(E_1 op E_2)" is an Ahmes arithmetic expression, where E_1 and E_2 are valid Ahmes arithmetic expressions (without spaces) and op is either plus ( + ) or minus ( - ). For example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions.
On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task:
Given the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators.
-----Input-----
The first line contains a string E (1 ≤ |E| ≤ 10^4) — a valid Ahmes arithmetic expression. All operators are erased and replaced with '?'.
The second line contains two space-separated integers P and M (0 ≤ min(P, M) ≤ 100) — the number of plus and minus operators, respectively.
It is guaranteed that P + M = the number of erased operators.
-----Output-----
Print one line containing the answer to the problem.
-----Examples-----
Input
(1?1)
1 0
Output
2
Input
(2?(1?2))
1 1
Output
1
Input
((1?(5?7))?((6?2)?7))
3 2
Output
18
Input
((1?(5?7))?((6?2)?7))
2 3
Output
16
-----Note----- The first sample will be (1 + 1) = 2. The second sample will be (2 + (1 - 2)) = 1. The third sample will be ((1 - (5 - 7)) + ((6 + 2) + 7)) = 18. The fourth sample will be ((1 + (5 + 7)) - ((6 - 2) - 7)) = 16.
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 inf
class Node:
def __init__(self, parent = None, leftExp = None, rightExp = None, signQ = 0):
self.parent, self.leftExp, self.rightExp, self.signQ = parent, leftExp, rightExp, signQ
def __str__(self):
return "Node"
memo = {}
def Memoize(node, p, maxValue, minValue):
if not node in memo:
memo.update({node : {p : [maxValue, minValue]} })
else:
memo[node].update({p : [maxValue, minValue]})
def ExpMaxValue(root: Node, p):
m = root.signQ - p
"""if root.signQ == 1:
if p == 1:
return [root.leftExp.value + root.rightExp.value, root.leftExp.value + root.rightExp.value]
else:
return [root.leftExp.value - root.rightExp.value, root.leftExp.value - root.rightExp.value]"""
if root.signQ == 0:
return [root.value, root.value]
if root in memo:
if p in memo[root]:
return memo[root][p]
if m == 0:
value = ExpMaxValue(root.leftExp, root.leftExp.signQ)[0] + ExpMaxValue(root.rightExp, root.rightExp.signQ)[0]
Memoize(root, p, value, value)
return [value, value]
if p == 0:
value = ExpMaxValue(root.leftExp, 0)[0] - ExpMaxValue(root.rightExp, 0)[0]
Memoize(root, p, value, value)
return [value, value]
maxValue = -inf
minValue = inf
if m >= p:
for pQMid in range(2):
pQLeftMin = min(p - pQMid, root.leftExp.signQ)
for pQLeft in range(pQLeftMin + 1):
if root.leftExp.signQ - pQLeft + (1 - pQMid) > m:
continue
resLeft = ExpMaxValue(root.leftExp, pQLeft)
resRight = ExpMaxValue(root.rightExp, p - pQMid - pQLeft)
if pQMid == 1:
maxValue = max(resLeft[0] + resRight[0], maxValue)
minValue = min(resLeft[1] + resRight[1], minValue)
else:
maxValue = max(resLeft[0] - resRight[1], maxValue)
minValue = min(resLeft[1] - resRight[0], minValue)
else:
for mQMid in range(2):
mQLeftMin = min(m - mQMid, root.leftExp.signQ)
for mQLeft in range(mQLeftMin + 1):
pQLeft = root.leftExp.signQ - mQLeft
if pQLeft + (1 - mQMid) > p:
continue
resLeft = ExpMaxValue(root.leftExp, pQLeft)
resRight = ExpMaxValue(root.rightExp, p - (1 - mQMid) - pQLeft)
if mQMid == 0:
maxValue = max(resLeft[0] + resRight[0], maxValue)
minValue = min(resLeft[1] + resRight[1], minValue)
else:
maxValue = max(resLeft[0] - resRight[1], maxValue)
minValue = min(resLeft[1] - resRight[0], minValue)
Memoize(root, p, int(maxValue), int(minValue))
return [int(maxValue), int(minValue)]
def PrintNodes(root: Node):
if root.signQ != 0:
leftExp = root.leftExp if root.leftExp.signQ != 0 else root.leftExp.value
rightExp = root.rightExp if root.rightExp.signQ != 0 else root.rightExp.value
check = root.signQ == root.leftExp.signQ + root.rightExp.signQ + 1
print(root.signQ, root.parent, leftExp, rightExp, check)
PrintNodes(root.leftExp)
PrintNodes(root.rightExp)
def main():
exp = str(input())
if len(exp) == 1:
print(exp)
return
#root = Node(None, None, None)
#root.parent = root
cNode = Node()
isRight = False
for i in range(1, len(exp) - 1):
if exp[i] == '(':
if not isRight:
cNode.leftExp = Node(cNode)
cNode = cNode.leftExp
else:
cNode.rightExp = Node(cNode)
cNode = cNode.rightExp
isRight = False
elif exp[i] == '?':
isRight = True
cNode.signQ += 1
elif exp[i] == ')':
if cNode.parent != None:
cNode.parent.signQ += cNode.signQ
cNode = cNode.parent
isRight = False
else:
if not isRight:
cNode.leftExp = Node(cNode)
cNode.leftExp.value = int(exp[i])
else:
cNode.rightExp = Node(cNode)
cNode.rightExp.value = int(exp[i])
#PrintNodes(cNode)
ss = str(input()).split()
p, m = int(ss[0]), int(ss[1])
print(ExpMaxValue(cNode, p)[0])
main()
``` | vfc_16858 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/935/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "(1?1)\n1 0\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "(2?(1?2))\n1 1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1777 | Solve the following coding problem using the programming language python:
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
-----Input-----
The first line contains one integer $n$ ($1 \leq n \leq 10^5$) — the number of bracket sequences.
Each of the following $n$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most $5 \cdot 10^5$.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
-----Output-----
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
-----Examples-----
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
-----Note-----
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
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())
ls = [input() for _ in range(n)]
balance = [[0, 0] for _ in range(n)]
for i in range(n):
for j in range(len(ls[i])):
balance[i][0] = balance[i][0] + (1 if ls[i][j] == '(' else -1)
balance[i][1] = min(balance[i][1], balance[i][0])
balance2 = []
for i in range(n):
if balance[i][0] < 0:
if balance[i][1] >= balance[i][0]:
balance2.append(balance[i][0])
if balance[i][0] >= 0:
if balance[i][1] >= 0:
balance2.append(balance[i][0])
balance2.sort()
answer = 0
i, j = 0, len(balance2) - 1
while i < j:
if balance2[i] + balance2[j] == 0:
answer += 1
i += 1
j -= 1
elif balance2[i] + balance2[j] < 0:
i += 1
elif balance2[i] + balance2[j] > 0:
j -= 1
print(answer)
``` | vfc_16862 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1097/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\n)())\n)\n((\n((\n(\n)\n)\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n(\n((\n(((\n(())\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n(())\n()\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1778 | Solve the following coding problem using the programming language python:
Two players A and B have a list of $n$ integers each. They both want to maximize the subtraction between their score and their opponent's score.
In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).
Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $\{1, 2, 2, 3\}$ in a list and you decided to choose $2$ for the next turn, only a single instance of $2$ will be deleted (and added to the score, if necessary).
The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.
Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.
-----Input-----
The first line of input contains an integer $n$ ($1 \le n \le 100\,000$) — the sizes of the list.
The second line contains $n$ integers $a_i$ ($1 \le a_i \le 10^6$), describing the list of the player A, who starts the game.
The third line contains $n$ integers $b_i$ ($1 \le b_i \le 10^6$), describing the list of the player B.
-----Output-----
Output the difference between A's score and B's score ($A-B$) if both of them are playing optimally.
-----Examples-----
Input
2
1 4
5 1
Output
0
Input
3
100 100 100
100 100 100
Output
0
Input
2
2 1
5 6
Output
-3
-----Note-----
In the first example, the game could have gone as follows: A removes $5$ from B's list. B removes $4$ from A's list. A takes his $1$. B takes his $1$.
Hence, A's score is $1$, B's score is $1$ and difference is $0$.
There is also another optimal way of playing: A removes $5$ from B's list. B removes $4$ from A's list. A removes $1$ from B's list. B removes $1$ from A's list.
The difference in the scores is still $0$.
In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $0$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n=int(input())
a=[*map(int,input().split())]
b=[*map(int,input().split())]
print(sum(sorted(a+b)[::-2])-sum(b))
``` | vfc_16866 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1038/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 4\n5 1\n",
"output": "0",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1779 | Solve the following coding problem using the programming language python:
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.
You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order.
You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.
Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.
-----Input-----
The first line contains a string of length 26 consisting of distinct lowercase English letters. This is the first layout.
The second line contains a string of length 26 consisting of distinct lowercase English letters. This is the second layout.
The third line contains a non-empty string s consisting of lowercase and uppercase English letters and digits. This is the text typed in the first layout. The length of s does not exceed 1000.
-----Output-----
Print the text if the same keys were pressed in the second layout.
-----Examples-----
Input
qwertyuiopasdfghjklzxcvbnm
veamhjsgqocnrbfxdtwkylupzi
TwccpQZAvb2017
Output
HelloVKCup2017
Input
mnbvcxzlkjhgfdsapoiuytrewq
asdfghjklqwertyuiopzxcvbnm
7abaCABAABAcaba7
Output
7uduGUDUUDUgudu7
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s1 = input()
s2 = input()
s = input()
r=''
for i in s:
if i.isalpha():
#print (s1.index(i.lower()))
if i.isupper():
r+= (s2[(s1.index(i.lower()))].upper())
else:
r+=(s2[(s1.index(i.lower()))])
else:
r+=(i)
print (r)
``` | vfc_16870 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/831/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "qwertyuiopasdfghjklzxcvbnm\nveamhjsgqocnrbfxdtwkylupzi\nTwccpQZAvb2017\n",
"output": "HelloVKCup2017\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "mnbvcxzlkjhgfdsapoiuytrewq\nasdfghjklqwertyuiopzxcvbnm\n7abaCABAABAcaba7\n",
"output": "7uduGUDUUDUgudu7\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1780 | Solve the following coding problem using the programming language python:
Eugeny has array a = a_1, a_2, ..., a_{n}, consisting of n integers. Each integer a_{i} equals to -1, or to 1. Also, he has m queries: Query number i is given as a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum a_{l}_{i} + a_{l}_{i} + 1 + ... + a_{r}_{i} = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
-----Input-----
The first line contains integers n and m (1 ≤ n, m ≤ 2·10^5). The second line contains n integers a_1, a_2, ..., a_{n} (a_{i} = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n).
-----Output-----
Print m integers — the responses to Eugene's queries in the order they occur in the input.
-----Examples-----
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int, input().split())
t = input()
a, b = t.count('1'), t.count('-')
t = ['0'] * m
c = 2 * min(a - b, b)
for i in range(m):
l, r = map(int, input().split())
r -= l
if r & 1 and r < c: t[i] = '1'
print('\n'.join(t))
``` | vfc_16874 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/302/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3\n1 -1\n1 1\n1 2\n2 2\n",
"output": "0\n1\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n",
"output": "0\n1\n0\n1\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n1 1 1\n2 2\n1 1\n1 1\n",
"output": "0\n0\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4\n-1 -1 -1 -1\n1 3\n1 2\n1 2\n1 1\n",
"output": "0\n0\n0\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n-1 -1 -1 -1 -1\n1 1\n1 1\n3 4\n1 1\n1 4\n",
"output": "0\n0\n0\n0\n0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1781 | Solve the following coding problem using the programming language python:
В самолёте есть n рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа.
Известно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, которые часто летают) и обычные.
Перед вами стоит задача рассадить ещё k обычных пассажиров так, чтобы суммарное число соседей у статусных пассажиров было минимально возможным. Два пассажира считаются соседями, если они сидят в одном ряду и между ними нет других мест и прохода между рядами. Если пассажир является соседним пассажиром для двух статусных пассажиров, то его следует учитывать в сумме соседей дважды.
-----Входные данные-----
В первой строке следуют два целых числа n и k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10·n) — количество рядов мест в самолёте и количество пассажиров, которых нужно рассадить.
Далее следует описание рядов мест самолёта по одному ряду в строке. Если очередной символ равен '-', то это проход между рядами. Если очередной символ равен '.', то это свободное место. Если очередной символ равен 'S', то на текущем месте будет сидеть статусный пассажир. Если очередной символ равен 'P', то на текущем месте будет сидеть обычный пассажир.
Гарантируется, что количество свободных мест не меньше k. Гарантируется, что все ряды удовлетворяют описанному в условии формату.
-----Выходные данные-----
В первую строку выведите минимальное суммарное число соседей у статусных пассажиров.
Далее выведите план рассадки пассажиров, который минимизирует суммарное количество соседей у статусных пассажиров, в том же формате, что и во входных данных. Если в свободное место нужно посадить одного из k пассажиров, выведите строчную букву 'x' вместо символа '.'.
-----Примеры-----
Входные данные
1 2
SP.-SS.S-S.S
Выходные данные
5
SPx-SSxS-S.S
Входные данные
4 9
PP.-PPPS-S.S
PSP-PPSP-.S.
.S.-S..P-SS.
P.S-P.PP-PSP
Выходные данные
15
PPx-PPPS-S.S
PSP-PPSP-xSx
xSx-SxxP-SSx
P.S-PxPP-PSP
-----Примечание-----
В первом примере нужно посадить ещё двух обычных пассажиров. Для минимизации соседей у статусных пассажиров, нужно посадить первого из них на третье слева место, а второго на любое из оставшихся двух мест, так как независимо от выбора места он станет соседом двух статусных пассажиров.
Изначально, у статусного пассажира, который сидит на самом левом месте уже есть сосед. Также на четвёртом и пятом местах слева сидят статусные пассажиры, являющиеся соседями друг для друга (что добавляет к сумме 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 = list(map(int, input().split()))
plain = list()
for i in range(n):
plain.append(list(input()))
fr = {
"0": list(),
"1": list(),
"2": list(),
}
for i in range(n):
for j in range(12):
if plain[i][j] != ".":
continue
st = 0
if j > 0 and plain[i][j - 1] == "S":
st += 1
if j < 11 and plain[i][j + 1] == "S":
st += 1
fr[str(st)].append((i, j))
for i in range(k):
if len(fr["0"]):
x, y = fr["0"].pop()
elif len(fr["1"]):
x, y = fr["1"].pop()
else:
x, y = fr["2"].pop()
plain[x][y] = "x"
result = 0
for i in range(n):
for j in range(12):
if plain[i][j] != "S":
continue
if j > 0 and plain[i][j - 1] in ("S", "x", "P"):
result += 1
if j < 11 and plain[i][j + 1] in ("S", "x", "P"):
result += 1
print(result)
for i in range(n):
print("".join(plain[i]))
``` | vfc_16878 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/929/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 2\nSP.-SS.S-S.S\n",
"output": "5\nSPx-SSxS-S.S\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 9\nPP.-PPPS-S.S\nPSP-PPSP-.S.\n.S.-S..P-SS.\nP.S-P.PP-PSP\n",
"output": "15\nPPx-PPPS-S.S\nPSP-PPSP-xSx\nxSx-SxxP-SSx\nP.S-PxPP-PSP\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 7\n.S.-SSSP-..S\nS..-.SPP-S.P\n.S.-PPPP-PSP\n",
"output": "13\nxSx-SSSP-xxS\nSxx-xSPP-S.P\n.S.-PPPP-PSP\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1782 | Solve the following coding problem using the programming language python:
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set U_{i} = (u_{i}, 1, u_{i}, 2, ..., u_{i}, |U_{i}|). Here and below we'll presuppose that the set elements are written in the increasing order.
We'll say that the secret is safe if the following conditions are hold: for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets U_{i} and U_{j} is an empty set; the union of sets U_1, U_2, ..., U_{k} is set (1, 2, ..., n); in each set U_{i}, its elements u_{i}, 1, u_{i}, 2, ..., u_{i}, |U_{i}| do not form an arithmetic progression (in particular, |U_{i}| ≥ 3 should hold).
Let us remind you that the elements of set (u_1, u_2, ..., u_{s}) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills u_{i} + d = u_{i} + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.
Your task is to find any partition of the set of words into subsets U_1, U_2, ..., U_{k} so that the secret is safe. Otherwise indicate that there's no such partition.
-----Input-----
The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 10^6) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.
-----Output-----
If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.
If there are multiple solutions, print any of them.
-----Examples-----
Input
11 3
Output
3 1 2 1 1 2 3 2 2 3 1
Input
5 2
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 re
import itertools
from collections import Counter, deque
class Task:
n, k = 0, 0
answer = []
def getData(self):
self.n, self.k = [int(x) for x in input().split(' ')]
#inFile = open('input.txt', 'r')
#inFile.readline().rstrip()
#self.childs = inFile.readline().rstrip()
def solve(self):
n, k = self.n, self.k
if n < 3 * k:
self.answer = '-1'
return
keeper = 1
while keeper < k:
self.answer += [keeper, keeper, keeper + 1]
self.answer += [keeper, keeper + 1, keeper + 1]
keeper += 2
if keeper > k:
self.answer += [k] * (n - len(self.answer))
return
else:
self.answer += [keeper] * (n - len(self.answer))
self.answer[-1] = 1
self.answer[3] = keeper
def printAnswer(self):
print(re.sub(r'[\[\],]', '', str(self.answer)))
#print(self.answer[:6])
#outFile = open('output.txt', 'w')
#outFile.write(self.answer)
task = Task()
task.getData()
task.solve()
task.printAnswer()
``` | vfc_16882 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/271/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "11 3\n",
"output": "3 1 2 1 1 2 3 2 2 3 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1783 | Solve the following coding problem using the programming language python:
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!
When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a_1, a_2, ..., a_{n}, where a_{i} is the sleep time on the i-th day.
The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is $\frac{(3 + 4) +(4 + 7)}{2} = 9$.
You should write a program which will calculate average sleep times of Polycarp over all weeks.
-----Input-----
The first line contains two integer numbers n and k (1 ≤ k ≤ n ≤ 2·10^5).
The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5).
-----Output-----
Output average sleeping time over all weeks.
The answer is considered to be correct if its absolute or relative error does not exceed 10^{ - 6}. In particular, it is enough to output real number with at least 6 digits after the decimal point.
-----Examples-----
Input
3 2
3 4 7
Output
9.0000000000
Input
1 1
10
Output
10.0000000000
Input
8 2
1 2 4 100000 123 456 789 1
Output
28964.2857142857
-----Note-----
In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
line=input().split()
n=int(line[0])
k=int(line[1])
nums=input().split()
for i in range(n):
nums[i]=int(nums[i])
firstsum = 0
for i in range(k):
firstsum+=nums[i]
totsum=firstsum
for i in range(n-k):
firstsum-=nums[i]
firstsum+=nums[k+i]
totsum+=firstsum
print(totsum/(n-k+1))
``` | vfc_16886 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/808/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n3 4 7\n",
"output": "9.0000000000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1784 | Solve the following coding problem using the programming language python:
There are n piles of pebbles on the table, the i-th pile contains a_{i} pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.
In other words, let's say that b_{i}, c is the number of pebbles of color c in the i-th pile. Then for any 1 ≤ c ≤ k, 1 ≤ i, j ≤ n the following condition must be satisfied |b_{i}, c - b_{j}, c| ≤ 1. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then b_{i}, c is considered to be zero.
-----Input-----
The first line of the input contains positive integers n and k (1 ≤ n, k ≤ 100), separated by a space — the number of piles and the number of colors respectively.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100) denoting number of pebbles in each of the piles.
-----Output-----
If there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) .
Otherwise in the first line output "YES" (without quotes). Then n lines should follow, the i-th of them should contain a_{i} space-separated integers. j-th (1 ≤ j ≤ a_{i}) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.
-----Examples-----
Input
4 4
1 2 3 4
Output
YES
1
1 4
1 2 4
1 2 3 4
Input
5 2
3 2 4 1 3
Output
NO
Input
5 4
3 2 4 3 5
Output
YES
1 2 3
1 3
1 2 3 4
1 3 4
1 1 2 3 4
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())
arr = [int(i) for i in input().split()]
res = [[] for i in range(n)]
c = 0
while True:
z = 0
for i in arr:
if i > 0:
z += 1
if z == 0:
break
if z == n:
for i in range(n):
arr[i] -= 1
res[i].append(1)
else:
c += 1
if c > k:
break
for i, j in enumerate(arr):
if j > 0:
arr[i] -= 1
res[i].append(c)
if c > k:
print('NO')
else:
print('YES')
for i in res:
for j in i:
print(j, end = ' ')
print()
``` | vfc_16890 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/509/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 4\n1 2 3 4\n",
"output": "YES\n1 \n1 1 \n1 1 2 \n1 1 2 3 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1785 | Solve the following coding problem using the programming language python:
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.
Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t): $\rho(s, t) = \sum_{i = 0}^{n - 1} \sum_{j = 0}^{n - 1} h(\operatorname{shift}(s, i), \operatorname{shift}(t, j))$ where $\operatorname{shift}(s, i)$ is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") = h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") + h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") + h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") = 1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6
Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: $\rho(s, t) = \operatorname{max}_{u :|u|=|s|} \rho(s, u)$.
Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 10^9 + 7.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 10^5).
The second line of the input contains a single string of length n, consisting of characters "ACGT".
-----Output-----
Print a single number — the answer modulo 10^9 + 7.
-----Examples-----
Input
1
C
Output
1
Input
2
AG
Output
4
Input
3
TTT
Output
1
-----Note-----
Please note that if for two distinct strings t_1 and t_2 values ρ(s, t_1) и ρ(s, t_2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.
In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0.
In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4.
In the third sample, ρ("TTT", "TTT") = 27
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
n = int(input())
l = [0] * 85
for c in input():
l[ord(c)] += 1
a, c, g, t = sorted(l[_] for _ in (65, 67, 71, 84))
if g < t:
print(1)
elif c < g:
print(pow(2, n, 1000000007))
elif a < c:
print(pow(3, n, 1000000007))
else:
print(pow(4, n, 1000000007))
def __starting_point():
main()
__starting_point()
``` | vfc_16894 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/520/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\nC\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\nAG\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nTTT\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\nGACT\n",
"output": "256\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1786 | Solve the following coding problem using the programming language python:
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
-----Input-----
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
-----Output-----
After each cut print on a single line the area of the maximum available glass fragment in mm^2.
-----Examples-----
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
-----Note-----
Picture for the first sample test: [Image] Picture for the second sample test: $\square$
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
w, h, n = list(map(int, input().split()))
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i in range(n):
s = input()
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
whmax = [wmax, hmax]
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = whmax[flag]
res[i] = u * whmax[not flag]
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
whmax[flag] = v
print('\n'.join(map(str, res)))
def __starting_point():
main()
__starting_point()
``` | vfc_16898 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/527/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3 4\nH 2\nV 2\nV 3\nV 1\n",
"output": "8\n4\n4\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 6 5\nH 4\nV 3\nV 5\nH 2\nV 1\n",
"output": "28\n16\n12\n6\n4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1787 | Solve the following coding problem using the programming language python:
The Fair Nut found a string $s$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $p_1, p_2, \ldots, p_k$, such that: For each $i$ ($1 \leq i \leq k$), $s_{p_i} =$ 'a'. For each $i$ ($1 \leq i < k$), there is such $j$ that $p_i < j < p_{i + 1}$ and $s_j =$ 'b'.
The Nut is upset because he doesn't know how to find the number. Help him.
This number should be calculated modulo $10^9 + 7$.
-----Input-----
The first line contains the string $s$ ($1 \leq |s| \leq 10^5$) consisting of lowercase Latin letters.
-----Output-----
In a single line print the answer to the problem — the number of such sequences $p_1, p_2, \ldots, p_k$ modulo $10^9 + 7$.
-----Examples-----
Input
abbaa
Output
5
Input
baaaa
Output
4
Input
agaa
Output
3
-----Note-----
In the first example, there are $5$ possible sequences. $[1]$, $[4]$, $[5]$, $[1, 4]$, $[1, 5]$.
In the second example, there are $4$ possible sequences. $[2]$, $[3]$, $[4]$, $[5]$.
In the third example, there are $3$ possible sequences. $[1]$, $[3]$, $[4]$.
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)
a=[]
curr=0
for i in range(n):
if s[i]=="a":
curr+=1
elif s[i]=="b":
a.append(curr)
curr=0
if curr>0:
a.append(curr)
prod=1
for i in range(len(a)):
prod*=(a[i]+1)
prod=prod%1000000007
print(prod-1)
``` | vfc_16902 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1084/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "abbaa\n",
"output": "5",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "baaaa\n",
"output": "4",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "agaa\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aaaaabb\n",
"output": "5",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1790 | Solve the following coding problem using the programming language python:
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.
During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 100$) — the number of stops Arkady saw.
The next $n$ lines describe the stops. Each of them starts with a single integer $r$ ($1 \le r \le 100$) — the number of tram lines that stop there. $r$ distinct integers follow, each one between $1$ and $100$, inclusive, — the line numbers. They can be in arbitrary order.
It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
-----Output-----
Print all tram lines that Arkady could be in, in arbitrary order.
-----Examples-----
Input
3
3 1 4 6
2 1 4
5 10 5 6 4 1
Output
1 4
Input
5
1 1
10 10 9 8 7 100 5 4 3 99 1
5 1 2 3 4 5
5 4 1 3 2 5
4 10 1 5 3
Output
1
-----Note-----
Consider the first example. Arkady woke up three times. The first time he saw a stop with lines $1$, $4$, $6$. The second time he saw a stop with lines $1$, $4$. The third time he saw a stop with lines $10$, $5$, $6$, $4$ and $1$. He can be in a tram of one of two lines: $1$ or $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())
d = {}
for i in range(n):
s = input().split()
for j in range(int(s[0])):
d[s[j+1]] = d.get(s[j+1],0)+1
ans = ""
for x in d:
if d[x] == n:
ans += str(x) + ' '
print(ans.strip())
``` | vfc_16914 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1056/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1\n",
"output": "1 4 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1791 | Solve the following coding problem using the programming language python:
You will receive 5 points for solving this problem.
Manao has invented a new operation on strings that is called folding. Each fold happens between a pair of consecutive letters and places the second part of the string above first part, running in the opposite direction and aligned to the position of the fold. Using this operation, Manao converts the string into a structure that has one more level than there were fold operations performed. See the following examples for clarity.
We will denote the positions of folds with '|' characters. For example, the word "ABRACADABRA" written as "AB|RACA|DAB|RA" indicates that it has been folded three times: first, between the leftmost pair of 'B' and 'R' letters; second, between 'A' and 'D'; and third, between the rightmost pair of 'B' and 'R' letters. Here are several examples of folded strings:
"ABCDEF|GHIJK" | "A|BCDEFGHIJK" | "AB|RACA|DAB|RA" | "X|XXXXX|X|X|XXXXXX"
| | | XXXXXX
KJIHG | KJIHGFEDCB | AR | X
ABCDEF | A | DAB | X
| | ACAR | XXXXX
| | AB | X
One last example for "ABCD|EFGH|IJ|K":
K
IJ
HGFE
ABCD
Manao noticed that each folded string can be viewed as several piles of letters. For instance, in the previous example, there are four piles, which can be read as "AHI", "BGJK", "CF", and "DE" from bottom to top. Manao wonders what is the highest pile of identical letters he can build using fold operations on a given word. Note that the pile should not contain gaps and should start at the bottom level. For example, in the rightmost of the four examples above, none of the piles would be considered valid since each of them has gaps, starts above the bottom level, or both.
-----Input-----
The input will consist of one line containing a single string of n characters with 1 ≤ n ≤ 1000 and no spaces. All characters of the string will be uppercase letters.
This problem doesn't have subproblems. You will get 5 points for the correct submission.
-----Output-----
Print a single integer — the size of the largest pile composed of identical characters that can be seen in a valid result of folding operations on the given string.
-----Examples-----
Input
ABRACADABRA
Output
3
Input
ABBBCBDB
Output
3
Input
AB
Output
1
-----Note-----
Consider the first example. Manao can create a pile of three 'A's using the folding "AB|RACAD|ABRA", which results in the following structure:
ABRA
DACAR
AB
In the second example, Manao can create a pile of three 'B's using the following folding: "AB|BB|CBDB".
CBDB
BB
AB
Another way for Manao to create a pile of three 'B's with "ABBBCBDB" is the following folding: "AB|B|BCBDB".
BCBDB
B
AB
In the third example, there are no folds performed and the string is just written in one line.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t = {}
for i, c in enumerate(input()):
if c not in t: t[c] = (i, 1)
elif (t[c][0] - i) & 1: t[c] = (i, t[c][1] + 1)
print(max(b for a, b in t.values()))
``` | vfc_16918 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/391/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "ABRACADABRA\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ABBBCBDB\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "AB\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ABBCDEFB\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1792 | Solve the following coding problem using the programming language python:
Thanks to the Doctor's help, the rebels managed to steal enough gold to launch a full-scale attack on the Empire! However, Darth Vader is looking for revenge and wants to take back his gold.
The rebels have hidden the gold in various bases throughout the galaxy. Darth Vader and the Empire are looking to send out their spaceships to attack these bases.
The galaxy can be represented as an undirected graph with $n$ planets (nodes) and $m$ wormholes (edges), each connecting two planets.
A total of $s$ empire spaceships and $b$ rebel bases are located at different planets in the galaxy.
Each spaceship is given a location $x$, denoting the index of the planet on which it is located, an attacking strength $a$, and a certain amount of fuel $f$.
Each base is given a location $x$, and a defensive strength $d$.
A spaceship can attack a base if both of these conditions hold: the spaceship's attacking strength is greater or equal than the defensive strength of the base the spaceship's fuel is greater or equal to the shortest distance, computed as the number of wormholes, between the spaceship's planet and the base's planet
Vader is very particular about his attacking formations. He requires that each spaceship is to attack at most one base and that each base is to be attacked by at most one spaceship.
Vader knows that the rebels have hidden $k$ gold in each base, so he will assign the spaceships to attack bases in such a way that maximizes the number of bases attacked.
Therefore, for each base that is attacked, the rebels lose $k$ gold.
However, the rebels have the ability to create any number of dummy bases. With the Doctor's help, these bases would exist beyond space and time, so all spaceship can reach them and attack them. Moreover, a dummy base is designed to seem irresistible: that is, it will always be attacked by some spaceship.
Of course, dummy bases do not contain any gold, but creating such a dummy base costs $h$ gold.
What is the minimum gold the rebels can lose if they create an optimal number of dummy bases?
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \leq n \leq 100$, $0 \leq m \leq 10000$), the number of nodes and the number of edges, respectively.
The next $m$ lines contain two integers $u$ and $v$ ($1 \leq u$, $v \leq n$) denoting an undirected edge between the two nodes.
The next line contains four integers $s$, $b$, $k$ and $h$ ($1 \leq s$, $b \leq 1000$, $0 \leq k$, $h \leq 10^9$), the number of spaceships, the number of bases, the cost of having a base attacked, and the cost of creating a dummy base, respectively.
The next $s$ lines contain three integers $x$, $a$, $f$ ($1 \leq x \leq n$, $0 \leq a$, $f \leq 10^9$), denoting the location, attack, and fuel of the spaceship.
The next $b$ lines contain two integers $x$, $d$ ($1 \leq x \leq n$, $0 \leq d \leq 10^9$), denoting the location and defence of the base.
-----Output-----
Print a single integer, the minimum cost in terms of gold.
-----Example-----
Input
6 7
1 2
2 3
3 4
4 6
6 5
4 4
3 6
4 2 7 3
1 10 2
3 8 2
5 1 0
6 5 4
3 7
5 2
Output
12
-----Note-----
One way to minimize the cost is to build $4$ dummy bases, for a total cost of $4 \times 3 = 12$.
One empire spaceship will be assigned to attack each of these dummy bases, resulting in zero actual bases attacked.
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 matching(node, visited, adj, assigned):
if node == -1:
return True
if visited[node]:
return False
visited[node] = True
for neighbor in adj[node]:
if matching(assigned[neighbor], visited, adj, assigned):
assigned[neighbor] = node
return True
return False
INF = 1000 * 1000
inp = [int(x) for x in sys.stdin.read().split()]
n, m = inp[0], inp[1]
inp_idx = 2
G = [[INF] * n for _ in range(n)]
for _ in range(m):
a, b = inp[inp_idx] - 1, inp[inp_idx + 1] - 1
inp_idx += 2
G[a][b] = G[b][a] = 1
for v in range(n):
G[v][v] = 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])
s, b, k, h = inp[inp_idx], inp[inp_idx + 1], inp[inp_idx + 2], inp[inp_idx + 3]
inp_idx += 4
spaceships = []
for _ in range(s):
x, a, f = inp[inp_idx] - 1, inp[inp_idx + 1], inp[inp_idx + 2]
inp_idx += 3
spaceships.append((x, a, f))
bases = []
for _ in range(b):
x, d = inp[inp_idx] - 1, inp[inp_idx + 1]
inp_idx += 2
bases.append((x, d))
adj = [[] for _ in range(s)]
assigned = [[] for _ in range(b)]
for i in range(s):
space = spaceships[i]
for j in range(b):
base = bases[j]
u, v = space[0], base[0]
fuel = space[2]
if G[u][v] <= fuel and space[1] >= base[1]:
adj[i].append(j)
visited = [False] * s
assigned = [-1] * b
matched = 0
for i in range(s):
visited = [False] * s
if matching(i, visited, adj, assigned):
matched += 1
print(min(matched * k, h * s))
``` | vfc_16922 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1184/B2",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 7\n1 2\n2 3\n3 4\n4 6\n6 5\n4 4\n3 6\n4 2 7 3\n1 10 2\n3 8 2\n5 1 0\n6 5 4\n3 7\n5 2\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1 1\n1 2 498328473 730315543\n1 267535146 337021959\n1 340728578\n1 82073826\n",
"output": "498328473\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1 1\n2 1 709189476 658667824\n1 511405192 843598992\n1 638564514 680433292\n1 584582554\n",
"output": "709189476\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1 1\n2 2 551454259 292052813\n1 755275238 645143315\n1 936400451 457379982\n1 873148501\n1 181471857\n",
"output": "584105626\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1793 | Solve the following coding problem using the programming language python:
You are given a rooted tree on $n$ vertices, its root is the vertex number $1$. The $i$-th vertex contains a number $w_i$. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than $L$ vertices and the sum of integers $w_i$ on each path does not exceed $S$. Each vertex should belong to exactly one path.
A vertical path is a sequence of vertices $v_1, v_2, \ldots, v_k$ where $v_i$ ($i \ge 2$) is the parent of $v_{i - 1}$.
-----Input-----
The first line contains three integers $n$, $L$, $S$ ($1 \le n \le 10^5$, $1 \le L \le 10^5$, $1 \le S \le 10^{18}$) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path.
The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($1 \le w_i \le 10^9$) — the numbers in the vertices of the tree.
The third line contains $n - 1$ integers $p_2, \ldots, p_n$ ($1 \le p_i < i$), where $p_i$ is the parent of the $i$-th vertex in the tree.
-----Output-----
Output one number — the minimum number of vertical paths. If it is impossible to split the tree, output $-1$.
-----Examples-----
Input
3 1 3
1 2 3
1 1
Output
3
Input
3 3 6
1 2 3
1 1
Output
2
Input
1 1 10000
10001
Output
-1
-----Note-----
In the first sample the tree is split into $\{1\},\ \{2\},\ \{3\}$.
In the second sample the tree is split into $\{1,\ 2\},\ \{3\}$ or $\{1,\ 3\},\ \{2\}$.
In the third sample it is impossible to split the tree.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def solve(n, l, s, www, children):
ans = 0
dp = [{} for _ in range(n)]
for v in range(n - 1, -1, -1):
cv = children[v]
if not cv:
dp[v][1] = www[v]
continue
ans += len(cv) - 1
wv = www[v]
if wv > s:
return -1
dv = dp[v]
for c in cv:
for lc, wc in list(dp[c].items()):
if lc == l:
continue
wt = wc + wv
if wt > s:
continue
if lc + 1 not in dv:
dv[lc + 1] = wt
else:
dv[lc + 1] = min(dv[lc + 1], wt)
if not dv:
ans += 1
dv[1] = wv
return ans + 1
n, l, s = list(map(int, input().split()))
www = list(map(int, input().split()))
if n == 1:
print(-1 if www[0] > s else 1)
return
children = [set() for _ in range(n)]
for i, p in enumerate(map(int, input().split())):
children[p - 1].add(i + 1)
print(solve(n, l, s, www, children))
``` | vfc_16926 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1059/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 1 3\n1 2 3\n1 1\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 6\n1 2 3\n1 1\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 10000\n10001\n",
"output": "-1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 3\n1 2 3\n1 1\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 3 100\n1 100 1 1 1 1\n1 1 2 3 3\n",
"output": "4",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1794 | Solve the following coding problem using the programming language python:
Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to a_{i} inclusive. No tickets are sold at the last station.
Let ρ_{i}, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρ_{i}, j among all pairs 1 ≤ i < j ≤ n.
-----Input-----
The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of stations.
The second line contains n - 1 integer a_{i} (i + 1 ≤ a_{i} ≤ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to a_{i} inclusive.
-----Output-----
Print the sum of ρ_{i}, j among all pairs of 1 ≤ i < j ≤ n.
-----Examples-----
Input
4
4 4 4
Output
6
Input
5
2 3 5 5
Output
17
-----Note-----
In the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.
Consider the second sample: ρ_{1, 2} = 1 ρ_{1, 3} = 2 ρ_{1, 4} = 3 ρ_{1, 5} = 3 ρ_{2, 3} = 1 ρ_{2, 4} = 2 ρ_{2, 5} = 2 ρ_{3, 4} = 1 ρ_{3, 5} = 1 ρ_{4, 5} = 1
Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
MAX_N = 100000
def maxi(a, b):
if a[0] > b[0]:
return a
else:
return b
class Segment_Tree:
def init(self, left, right, data, leftbound, rightbound):
self.data = data
self.left = left
self.right = right
self.leftbound = leftbound
self.rightbound = rightbound
return self
def build(self, a, leftbound, rightbound):
#print(leftbound, rightbound, a)
if len(a) == 0:
return self.init(-1, -1, [0, -1], MAX_N + 1, -1)
elif len(a) == 1:
return self.init(-1, -1, a[0], leftbound, rightbound)
else:
middle = (leftbound + rightbound) // 2
self.left = Segment_Tree()
self.right = Segment_Tree()
return self.init(self.left.build(a[:middle - leftbound], leftbound, middle), self.right.build(a[middle - leftbound:], middle, rightbound), maxi(self.left.data, self.right.data), leftbound, rightbound)
def get(self, l, r):
if l <= self.leftbound and r >= self.rightbound:
return self.data
elif l < self.left.rightbound and r > self.right.leftbound:
return maxi(self.left.get(l, r), self.right.get(l, r))
elif l >= self.right.leftbound:
return self.right.get(l, r)
else:
return self.left.get(l, r)
n = int(input())
a = list(map(int, input().split())) + [n]
a = [[a[i] - 1, i] for i in range(n)]
Tree = Segment_Tree()
Tree.build(a, 0, n)
dp = [0] * n
ans = 0
for i in range(n - 2, -1, -1):
m = Tree.get(i + 1, a[i][0] + 1)[1]
dp[i] = dp[m] - (a[i][0] - m) + n - i - 1;
ans += dp[i]
print(ans)
``` | vfc_16930 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/675/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n4 4 4\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n2 3 5 5\n",
"output": "17\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n2 10 8 7 8 8 10 9 10\n",
"output": "63\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1795 | Solve the following coding problem using the programming language python:
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number f_{i}, where 1 ≤ f_{i} ≤ n and f_{i} ≠ i.
We call a love triangle a situation in which plane A likes plane B, plane B likes plane C and plane C likes plane A. Find out if there is any love triangle on Earth.
-----Input-----
The first line contains a single integer n (2 ≤ n ≤ 5000) — the number of planes.
The second line contains n integers f_1, f_2, ..., f_{n} (1 ≤ f_{i} ≤ n, f_{i} ≠ i), meaning that the i-th plane likes the f_{i}-th.
-----Output-----
Output «YES» if there is a love triangle consisting of planes on Earth. Otherwise, output «NO».
You can output any letter in lower case or in upper case.
-----Examples-----
Input
5
2 4 5 1 3
Output
YES
Input
5
5 5 5 5 1
Output
NO
-----Note-----
In first example plane 2 likes plane 4, plane 4 likes plane 1, plane 1 likes plane 2 and that is a love triangle.
In second example there are no love triangles.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list([int(x) - 1 for x in input().split()])
ans = False
for i in range(n):
if a[a[a[i]]] == i:
ans = True
break
print('YES' if ans else 'NO')
``` | vfc_16934 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/939/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n2 4 5 1 3\n",
"output": "YES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1796 | Solve the following coding problem using the programming language python:
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
Operation ++ increases the value of variable x by 1. Operation -- decreases the value of variable x by 1.
A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.
A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.
You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 150) — the number of statements in the programme.
Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.
-----Output-----
Print a single integer — the final value of x.
-----Examples-----
Input
1
++X
Output
1
Input
2
X++
--X
Output
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
str = input()
inpt = ""
n = int(str)
x = 0
for i in range(n):
inpt = input()
#print(inpt[0:2]+" - "+inpt[1:3])
if(inpt[0:2] == "++" or inpt[1:3] == "++"):
x += 1
#print("x = {} plus 1".format(x))
elif(inpt[0:2] == "--" or inpt[1:3] == "--"):
x -= 1
#print("x = {} minus 1".format(x))
print(x)
``` | vfc_16938 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/282/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n++X\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\nX++\n--X\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n++X\n++X\n++X\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1797 | Solve the following coding problem using the programming language python:
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
For each station i there exists exactly one train that goes from this station. Its destination station is p_{i}, possibly p_{i} = i; For each station i there exists exactly one station j such that p_{j} = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of p_{i} for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
-----Input-----
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the current structure of the subway. All these numbers are distinct.
-----Output-----
Print one number — the maximum possible value of convenience.
-----Examples-----
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
-----Note-----
In the first example the mayor can change p_2 to 3 and p_3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p_2 to 4 and p_3 to 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())
p = list(map(int, input().split()))
ls = []
visited = [False for _ in range(n)]
cnt = 0
for i in range(n):
j = i
cnt = 0
while not visited[j]:
visited[j] = True
cnt += 1
j = p[j] - 1
if 0 < cnt:
ls.append(cnt)
ls.sort()
if 1 < len(ls):
ls[-2] += ls[-1]
ls.pop()
print(sum([x**2 for x in ls]))
``` | vfc_16942 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/884/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 1 3\n",
"output": "9\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1798 | Solve the following coding problem using the programming language python:
One day Jeff got hold of an integer sequence a_1, a_2, ..., a_{n} of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold:
x occurs in sequence a. Consider all positions of numbers x in the sequence a (such i, that a_{i} = x). These numbers, sorted in the increasing order, must form an arithmetic progression.
Help Jeff, find all x that meet the problem conditions.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5). The next line contains integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5). The numbers are separated by spaces.
-----Output-----
In the first line print integer t — the number of valid x. On each of the next t lines print two integers x and p_{x}, where x is current suitable value, p_{x} is the common difference between numbers in the progression (if x occurs exactly once in the sequence, p_{x} must equal 0). Print the pairs in the order of increasing x.
-----Examples-----
Input
1
2
Output
1
2 0
Input
8
1 2 1 3 1 2 1 5
Output
4
1 2
2 4
3 0
5 0
-----Note-----
In the first test 2 occurs exactly once in the sequence, ergo p_2 = 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
def Is_arth(L):
D=L[1]-L[0]
p=L[1]
for i in range(2,len(L)):
if(L[i]-p!=D):
return False
p=L[i]
return True
n=int(sys.stdin.readline())
A=list(map(int,sys.stdin.readline().split()))
T=[False]*(10**5+1)
Z=[]
for i in range(10**5+1):
Z.append([])
Taken=[]
for i in range(n):
Z[A[i]]+=[i]
Ans=""
Num=0
for i in range(10**5+1):
L=len(Z[i])
item=i
if(L==0):
continue
if(L==1):
Num+=1
Ans+=str(item)+" 0\n"
elif(L==2):
Num+=1
Ans+=str(item)+" "+str(Z[item][1]-Z[item][0])+"\n"
else:
if(Is_arth(Z[item])):
Num+=1
Ans+=str(item)+" "+str(Z[item][1]-Z[item][0])+"\n"
sys.stdout.write(str(Num)+"\n")
sys.stdout.write(Ans)
``` | vfc_16946 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/352/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n2\n",
"output": "1\n2 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n1 2 1 3 1 2 1 5\n",
"output": "4\n1 2\n2 4\n3 0\n5 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 10 5\n",
"output": "3\n1 0\n5 0\n10 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n9 9 3 5\n",
"output": "3\n3 0\n5 0\n9 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n1 2 2 1 1 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n2 6 3 8 7 2\n",
"output": "5\n2 5\n3 0\n6 0\n7 0\n8 0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1800 | Solve the following coding problem using the programming language python:
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first r_{i} numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence a_{i} of length n and the description of each manager, that is value r_{i} and his favourite order. You are asked to speed up the process and determine how the final report will look like.
-----Input-----
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers a_{i} (|a_{i}| ≤ 10^9) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers t_{i} and r_{i} ($t_{i} \in \{1,2 \}$, 1 ≤ r_{i} ≤ n), meaning that the i-th manager sorts the first r_{i} numbers either in the non-descending (if t_{i} = 1) or non-ascending (if t_{i} = 2) order.
-----Output-----
Print n integers — the final report, which will be passed to Blake by manager number m.
-----Examples-----
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
-----Note-----
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# You lost the game.
n, m = map(int, input().split())
A = list(map(int, input().split()))
M = [list(map(int, input().split())) for _ in range(m)]
j = m-1
x = 2
h = -1
B = [-1 for _ in range(n+1)]
while h < n and j >= 0:
h = M[j][1]
if h >= x:
B[h] = j
x = h+1
j -= 1
O = [0 for _ in range(n)]
for i in range(n-1,x-2,-1):
O[i] = A[i]
del A[i]
n2 = len(A)
R = A[:]
R.sort()
d = 0
f = n2-1
c = 0
for i in range(n2-1,-1,-1):
j = B[i+1]
if j >= 0:
c = M[j][0]
if c == 1:
O[i] = R[f]
f -= 1
else:
O[i] = R[d]
d += 1
for i in range(n):
print(O[i],end=" ")
``` | vfc_16954 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/631/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 1\n1 2 3\n2 2\n",
"output": "2 1 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2\n1 2 4 3\n2 3\n1 2\n",
"output": "2 4 1 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n4 3 2 1\n1 4\n",
"output": "1 2 3 4 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1801 | Solve the following coding problem using the programming language python:
Little Dima has two sequences of points with integer coordinates: sequence (a_1, 1), (a_2, 2), ..., (a_{n}, n) and sequence (b_1, 1), (b_2, 2), ..., (b_{n}, n).
Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in the assembled sequence will not decrease. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence.
Dima considers two assembled sequences (p_1, q_1), (p_2, q_2), ..., (p_{2·}n, q_{2·}n) and (x_1, y_1), (x_2, y_2), ..., (x_{2·}n, y_{2·}n) distinct, if there is such i (1 ≤ i ≤ 2·n), that (p_{i}, q_{i}) ≠ (x_{i}, y_{i}).
As the answer can be rather large, print the remainder from dividing the answer by number m.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). The third line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^9). The numbers in the lines are separated by spaces.
The last line contains integer m (2 ≤ m ≤ 10^9 + 7).
-----Output-----
In the single line print the remainder after dividing the answer to the problem by number m.
-----Examples-----
Input
1
1
2
7
Output
1
Input
2
1 2
2 3
11
Output
2
-----Note-----
In the first sample you can get only one sequence: (1, 1), (2, 1).
In the second sample you can get such sequences : (1, 1), (2, 2), (2, 1), (3, 2); (1, 1), (2, 1), (2, 2), (3, 2). Thus, the answer 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 = int(input())
c, d = {}, {}
for x, y in zip(input().split(), input().split()):
c[x] = c.get(x, 1) + 1
c[y] = c.get(y, 1) + 1
if x == y: d[x] = d.get(x, 0) + 2
s, m = 1, int(input())
for k, v in c.items():
u = d.get(k, 0)
for i in range(v - u, v, 2): s = s * (i * i + i) // 2 % m
for i in range(1, v - u): s = s * i % m
print(s)
``` | vfc_16958 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/272/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n1\n2\n7\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 2\n2 3\n11\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1802 | Solve the following coding problem using the programming language python:
The Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression.
To achieve the goal, the gym teacher ordered a lot of magical buns from the dining room. The magic buns come in two types: when a student eats one magic bun of the first type, his height increases by one, when the student eats one magical bun of the second type, his height decreases by one. The physical education teacher, as expected, cares about the health of his students, so he does not want them to eat a lot of buns. More precisely, he wants the maximum number of buns eaten by some student to be minimum.
Help the teacher, get the maximum number of buns that some pupils will have to eat to achieve the goal of the teacher. Also, get one of the possible ways for achieving the objective, namely, the height of the lowest student in the end and the step of the resulting progression.
-----Input-----
The single line contains integer n (2 ≤ n ≤ 10^3) — the number of students. The second line contains n space-separated integers — the heights of all students. The height of one student is an integer which absolute value doesn't exceed 10^4.
-----Output-----
In the first line print the maximum number of buns eaten by some student to achieve the teacher's aim. In the second line, print two space-separated integers — the height of the lowest student in the end and the step of the progression. Please, pay attention that the step should be non-negative.
If there are multiple possible answers, you can print any of them.
-----Examples-----
Input
5
-3 -4 -2 -3 3
Output
2
-3 1
Input
5
2 -3 -1 -4 3
Output
1
-4 2
-----Note-----
Lets look at the first sample. We can proceed in the following manner:
don't feed the 1-st student, his height will stay equal to -3; give two buns of the first type to the 2-nd student, his height become equal to -2; give two buns of the first type to the 3-rd student, his height become equal to 0; give two buns of the first type to the 4-th student, his height become equal to -1; give two buns of the second type to the 5-th student, his height become equal to 1.
To sum it up, when the students line up in non-decreasing height it will be an arithmetic progression: -3, -2, -1, 0, 1. The height of the lowest student is equal to -3, the step of the progression is equal to 1. The maximum number of buns eaten by one student is equal to 2.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
q = 10001
n, a = int(input()), list(map(int, input().split()))
a.sort()
for i in range(40000 // (n - 1) + 1):
b = [a[j] - j * i for j in range(n)]
u, v = max(b), min(b)
p = (u - v + 1) // 2
if p < q: q, s, d = p, v + p, i
print(q)
print(s, d)
``` | vfc_16962 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/394/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n-3 -4 -2 -3 3\n",
"output": "2\n-3 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n2 -3 -1 -4 3\n",
"output": "1\n-4 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n94 65 -33 -43 60 -24\n",
"output": "25\n-67 34\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n-10000 10000 -10000\n",
"output": "5000\n-15000 10000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n0 0\n",
"output": "0\n0 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n-1 -2 -4 -10 6 6 5\n",
"output": "3\n-9 3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1803 | Solve the following coding problem using the programming language python:
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are a_{i} oskols sitting on the i-th wire. $40$
Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away.
Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.
-----Input-----
The first line of the input contains an integer n, (1 ≤ n ≤ 100). The next line contains a list of space-separated integers a_1, a_2, ..., a_{n}, (0 ≤ a_{i} ≤ 100).
The third line contains an integer m, (0 ≤ m ≤ 100). Each of the next m lines contains two integers x_{i} and y_{i}. The integers mean that for the i-th time Shaass shoot the y_{i}-th (from left) bird on the x_{i}-th wire, (1 ≤ x_{i} ≤ n, 1 ≤ y_{i}). It's guaranteed there will be at least y_{i} birds on the x_{i}-th wire at that moment.
-----Output-----
On the i-th line of the output print the number of birds on the i-th wire.
-----Examples-----
Input
5
10 10 10 10 10
5
2 5
3 13
2 12
1 13
4 6
Output
0
12
5
0
16
Input
3
2 4 1
1
2 2
Output
3
0
3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
rd = lambda: list(map(int, input().split()))
n, = rd()
a = [0] + rd() + [0]
for i in range(rd()[0]):
x, y = rd()
a[x-1] += y-1
a[x+1] += a[x]-y
a[x ] = 0
print('\n'.join(map(str, a[1:1+n])))
``` | vfc_16966 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/294/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6\n",
"output": "0\n12\n5\n0\n16\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 4 1\n1\n2 2\n",
"output": "3\n0\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n58 51 45 27 48\n5\n4 9\n5 15\n4 5\n5 8\n1 43\n",
"output": "0\n66\n57\n7\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n48 53 10 28 91 56 81 2 67 52\n2\n2 40\n6 51\n",
"output": "87\n0\n23\n28\n141\n0\n86\n2\n67\n52\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n72 45\n6\n1 69\n2 41\n1 19\n2 7\n1 5\n2 1\n",
"output": "0\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n95 54 36 39 98 30 19 24 14 12\n3\n9 5\n8 15\n7 5\n",
"output": "95\n54\n36\n39\n98\n34\n0\n28\n13\n21\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1804 | Solve the following coding problem using the programming language python:
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
-----Input-----
The first line contains two integers N и M — size of the city (1 ≤ N, M ≤ 10^9). In the next line there is a single integer C (1 ≤ C ≤ 10^5) — the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 ≤ x ≤ N, 1 ≤ y ≤ M). The next line contains an integer H — the number of restaurants (1 ≤ H ≤ 10^5). Following H lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing.
-----Output-----
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
-----Examples-----
Input
10 10
2
1 1
3 3
2
1 10
4 4
Output
6
2
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
n, m = list(map(int, input().split()))
minx = miny = n + m
maxx = maxy = - minx
dist = n + m + 1
c = int(input())
for _ in range(c):
x, y = list(map(int, input().split()))
minx = min(minx, x - y)
miny = min(miny, x + y)
maxx = max(maxx, x - y)
maxy = max(maxy, x + y)
h = int(input())
for i in range(h):
a, b = list(map(int, input().split()))
x = a - b
y = a + b
maxxy = max(
max(abs(minx - x), abs(maxx - x)),
max(abs(miny - y), abs(maxy - y))
)
if maxxy < dist:
dist = maxxy
res = i + 1
print(dist)
print(res)
``` | vfc_16970 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/491/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 10\n2\n1 1\n3 3\n2\n1 10\n4 4\n",
"output": "6\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 100\n10\n53 20\n97 6\n12 74\n48 92\n97 13\n47 96\n75 32\n69 21\n95 75\n1 54\n10\n36 97\n41 1\n1 87\n39 23\n27 44\n73 97\n1 1\n6 26\n48 3\n5 69\n",
"output": "108\n4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 100\n10\n86 72\n25 73\n29 84\n34 33\n29 20\n84 83\n41 80\n22 22\n16 89\n77 49\n1\n4 23\n",
"output": "140\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 100\n1\n66 77\n10\n70 11\n76 69\n79 39\n90 3\n38 87\n61 81\n98 66\n63 68\n62 93\n53 36\n",
"output": "9\n6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000000 1000000000\n1\n1 1\n1\n1000000000 1000000000\n",
"output": "1999999998\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1805 | Solve the following coding problem using the programming language python:
Let's denote correct match equation (we will denote it as CME) an equation $a + b = c$ there all integers $a$, $b$ and $c$ are greater than zero.
For example, equations $2 + 2 = 4$ (||+||=||||) and $1 + 2 = 3$ (|+||=|||) are CME but equations $1 + 2 = 4$ (|+||=||||), $2 + 2 = 3$ (||+||=|||), and $0 + 1 = 1$ (+|=|) are not.
Now, you have $n$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if $n = 2$, you can buy two matches and assemble |+|=||, and if $n = 5$ you can buy one match and assemble ||+|=|||. [Image]
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer $q$ independent queries.
-----Input-----
The first line contains one integer $q$ ($1 \le q \le 100$) — the number of queries.
The only line of each query contains one integer $n$ ($2 \le n \le 10^9$) — the number of matches.
-----Output-----
For each test case print one integer in single line — the minimum number of matches which you have to buy for assembling CME.
-----Example-----
Input
4
2
5
8
11
Output
2
1
0
1
-----Note-----
The first and second queries are explained in the statement.
In the third query, you can assemble $1 + 3 = 4$ (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble $2 + 4 = 6$ (||+||||=||||||).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t = int(input())
for i in range(t):
a = int(input())
if a >= 4:
print(a % 2)
else:
print(4 - a)
``` | vfc_16974 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1223/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n2\n5\n8\n11\n",
"output": "2\n1\n0\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n101\n60\n16\n78\n37\n22\n24\n63\n65\n57\n31\n46\n62\n50\n40\n79\n93\n97\n41\n64\n52\n30\n48\n95\n44\n9\n33\n15\n4\n59\n69\n56\n67\n73\n87\n17\n71\n23\n55\n18\n43\n80\n94\n58\n26\n90\n6\n96\n27\n10\n45\n75\n72\n82\n11\n3\n5\n85\n2\n14\n53\n36\n39\n99\n89\n20\n81\n61\n12\n29\n8\n70\n42\n66\n91\n77\n49\n35\n92\n84\n38\n21\n76\n74\n86\n32\n100\n28\n51\n13\n7\n34\n68\n47\n19\n83\n54\n88\n25\n98\n",
"output": "1\n0\n0\n0\n1\n0\n0\n1\n1\n1\n1\n0\n0\n0\n0\n1\n1\n1\n1\n0\n0\n0\n0\n1\n0\n1\n1\n1\n0\n1\n1\n0\n1\n1\n1\n1\n1\n1\n1\n0\n1\n0\n0\n0\n0\n0\n0\n0\n1\n0\n1\n1\n0\n0\n1\n1\n1\n1\n2\n0\n1\n0\n1\n1\n1\n0\n1\n1\n0\n1\n0\n0\n0\n0\n1\n1\n1\n1\n0\n0\n0\n1\n0\n0\n0\n0\n0\n0\n1\n1\n1\n0\n0\n1\n1\n1\n0\n0\n1\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n127\n145\n190\n164\n131\n168\n123\n132\n138\n140\n167\n195\n121\n143\n182\n136\n148\n189\n171\n105\n196\n169\n170\n135\n102\n162\n139\n126\n146\n165\n197\n181\n130\n103\n107\n125\n118\n180\n157\n179\n106\n128\n198\n110\n104\n137\n184\n116\n141\n199\n187\n133\n186\n115\n129\n114\n147\n166\n172\n120\n160\n163\n191\n193\n152\n112\n174\n173\n108\n176\n101\n159\n122\n150\n175\n111\n134\n119\n154\n156\n124\n153\n188\n194\n161\n151\n109\n192\n185\n144\n177\n158\n113\n117\n178\n149\n142\n200\n183\n155\n",
"output": "1\n1\n0\n0\n1\n0\n1\n0\n0\n0\n1\n1\n1\n1\n0\n0\n0\n1\n1\n1\n0\n1\n0\n1\n0\n0\n1\n0\n0\n1\n1\n1\n0\n1\n1\n1\n0\n0\n1\n1\n0\n0\n0\n0\n0\n1\n0\n0\n1\n1\n1\n1\n0\n1\n1\n0\n1\n0\n0\n0\n0\n1\n1\n1\n0\n0\n0\n1\n0\n0\n1\n1\n0\n0\n1\n1\n0\n1\n0\n0\n0\n1\n0\n0\n1\n1\n1\n0\n1\n0\n1\n0\n1\n1\n0\n1\n0\n0\n1\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1807 | Solve the following coding problem using the programming language python:
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display). [Image]
Max starts to type all the values from a to b. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator.
For example if a = 1 and b = 3 then at first the calculator will print 2 segments, then — 5 segments and at last it will print 5 segments. So the total number of printed segments is 12.
-----Input-----
The only line contains two integers a, b (1 ≤ a ≤ b ≤ 10^6) — the first and the last number typed by Max.
-----Output-----
Print the only integer a — the total number of printed segments.
-----Examples-----
Input
1 3
Output
12
Input
10 15
Output
39
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
v = {
"1" : 2,
"2" : 5,
"3" : 5,
"4" : 4,
"5" : 5,
"6" : 6,
"7" : 3,
"8" : 7,
"9" : 6,
"0" : 6
}
a, b = map(int, input().split())
answer = 0
for i in range(a, b + 1):
s = str(i)
for e in s:
answer += v[e]
print(answer)
def __starting_point():
main()
__starting_point()
``` | vfc_16982 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/620/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 3\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 15\n",
"output": "39\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 100\n",
"output": "928\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 10000\n",
"output": "188446\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "213 221442\n",
"output": "5645356\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1000000\n",
"output": "28733372\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1808 | Solve the following coding problem using the programming language python:
Luba has to do n chores today. i-th chore takes a_{i} units of time to complete. It is guaranteed that for every $i \in [ 2 . . n ]$ the condition a_{i} ≥ a_{i} - 1 is met, so the sequence is sorted.
Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of a_{i} ($x < \operatorname{min}_{i = 1}^{n} a_{i}$).
Luba is very responsible, so she has to do all n chores, and now she wants to know the minimum time she needs to do everything. Luba cannot do two chores simultaneously.
-----Input-----
The first line contains three integers n, k, x (1 ≤ k ≤ n ≤ 100, 1 ≤ x ≤ 99) — the number of chores Luba has to do, the number of chores she can do in x units of time, and the number x itself.
The second line contains n integer numbers a_{i} (2 ≤ a_{i} ≤ 100) — the time Luba has to spend to do i-th chore.
It is guaranteed that $x < \operatorname{min}_{i = 1}^{n} a_{i}$, and for each $i \in [ 2 . . n ]$ a_{i} ≥ a_{i} - 1.
-----Output-----
Print one number — minimum time Luba needs to do all n chores.
-----Examples-----
Input
4 2 2
3 6 7 10
Output
13
Input
5 2 1
100 100 100 100 100
Output
302
-----Note-----
In the first example the best option would be to do the third and the fourth chore, spending x = 2 time on each instead of a_3 and a_4, respectively. Then the answer is 3 + 6 + 2 + 2 = 13.
In the second example Luba can choose any two chores to spend x time on them instead of a_{i}. So the answer is 100·3 + 2·1 = 302.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
R=lambda:list(map(int,input().split()))
n,k,x=R()
a=list(reversed(R()))
print(sum(x if i < k else a[i] for i in range(n)))
``` | vfc_16986 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/873/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2 2\n3 6 7 10\n",
"output": "13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2 1\n100 100 100 100 100\n",
"output": "302\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n100\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 1 99\n100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100\n",
"output": "9999\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 100 1\n100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100\n",
"output": "100\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 50 50\n51 51 52 53 55 55 55 55 56 56 56 57 57 58 58 59 59 59 60 60 61 61 62 62 63 64 64 64 64 65 65 65 65 66 66 66 67 68 68 68 69 69 70 70 70 70 71 71 71 71 71 71 72 72 76 76 76 76 77 79 79 81 81 81 81 82 82 82 82 83 84 85 86 87 87 88 88 88 89 89 89 90 90 90 91 91 91 92 92 93 95 95 96 96 96 97 97 98 99 100\n",
"output": "5618\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1809 | Solve the following coding problem using the programming language python:
New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is w_{i}.
As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below. He lifts all the books above book x. He pushes book x out of the stack. He puts down the lifted books without changing their order. After reading book x, he puts book x on the top of the stack.
[Image]
He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer b_{j} (1 ≤ b_{j} ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.
After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?
-----Input-----
The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books.
The second line contains n space-separated integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 100) — the weight of each book.
The third line contains m space separated integers b_1, b_2, ..., b_{m} (1 ≤ b_{j} ≤ n) — the order of books that he would read. Note that he can read the same book more than once.
-----Output-----
Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.
-----Examples-----
Input
3 5
1 2 3
1 3 2 3 1
Output
12
-----Note-----
Here's a picture depicting the example. Each vertical column presents the stacked books. [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
line = input().split()
n = int(line[0])
m = int(line[1])
W = [int(w) for w in input().split()]
B = [int(b) for b in input().split()]
ans = 0
lst = [0 for i in range(n)]
for i in range(m):
arr = list(lst)
for j in range(i):
if B[i - j - 1] == B[i]:
break
arr[B[i - j - 1] - 1] = 1
for i in range(n):
if arr[i] == 1:
ans += W[i]
print(ans)
``` | vfc_16990 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/500/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5\n1 2 3\n1 3 2 3 1\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n10 20 30\n1 2 3\n",
"output": "40\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n10 12\n2 1\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n61 59 97 16 2 94 57 48 91 93\n2 8 6 5 3 1 3 4 9 10\n",
"output": "2137\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50 50\n75 71 23 37 28 23 69 75 5 62 3 11 96 100 13 50 57 51 8 90 4 6 84 27 11 89 95 81 10 62 48 52 69 87 97 95 30 74 21 42 36 64 31 80 81 50 56 53 33 99\n26 30 5 33 35 29 6 15 36 17 32 16 14 1 29 34 22 40 12 42 38 48 39 50 13 47 18 43 10 8 49 45 11 31 21 37 46 28 20 41 2 7 9 24 27 23 3 44 15 14\n",
"output": "63929\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1810 | Solve the following coding problem using the programming language python:
IT City company developing computer games invented a new way to reward its employees. 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 divisible by all numbers 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 divisible by all numbers from 2 to 10.
-----Examples-----
Input
3000
Output
1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = 2*2*2*3*3*5*7
m = int(input())
print(m//n)
``` | vfc_16994 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/J",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3000\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2520\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2519\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2521\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "0",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1811 | Solve the following coding problem using the programming language python:
Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1.
Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.
Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i + 1, i + 2, ..., i + k.
Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?
-----Input-----
The first line contains two integers n and k (2 ≤ n ≤ 3·10^5, 1 ≤ k ≤ 3·10^5). The next line contains n characters — the description of the road: the i-th character equals ".", if the i-th sector contains no rocks. Otherwise, it equals "#".
It is guaranteed that the first and the last characters equal ".".
-----Output-----
Print "YES" (without the quotes) if Ksusha can reach the end of the road, otherwise print "NO" (without the quotes).
-----Examples-----
Input
2 1
..
Output
YES
Input
5 2
.#.#.
Output
YES
Input
7 3
.#.###.
Output
NO
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = map(int, input().split())
j = 0
for i in input():
if i == '.':
j = 0
else:
j += 1
if j >= k:
print("NO")
break
else:
print("YES")
``` | vfc_16998 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/299/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 1\n..\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n.#.#.\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 3\n.#.###.\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1812 | Solve the following coding problem using the programming language python:
You are given n positive integers a_1, a_2, ..., a_{n}.
For every a_{i} you need to find a positive integer k_{i} such that the decimal notation of 2^{k}_{i} contains the decimal notation of a_{i} as a substring among its last min(100, length(2^{k}_{i})) digits. Here length(m) is the length of the decimal notation of m.
Note that you don't have to minimize k_{i}. The decimal notations in this problem do not contain leading zeros.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 2 000) — the number of integers a_{i}.
Each of the next n lines contains a positive integer a_{i} (1 ≤ a_{i} < 10^11).
-----Output-----
Print n lines. The i-th of them should contain a positive integer k_{i} such that the last min(100, length(2^{k}_{i})) digits of 2^{k}_{i} contain the decimal notation of a_{i} as a substring. Integers k_{i} must satisfy 1 ≤ k_{i} ≤ 10^50.
It can be shown that the answer always exists under the given constraints. If there are multiple answers, print any of them.
-----Examples-----
Input
2
8
2
Output
3
1
Input
2
3
4857
Output
5
20
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def dlog(x, n):
bigMod = 5 ** n
ans = [None, 0, 1, 3, 2][x % 5]
val = 2 ** ans % bigMod
mod, phi = 5, 4
phiVal = 2 ** phi % bigMod
for i in range(2, n + 1):
nextMod = mod * 5
while val % nextMod != x % nextMod:
val = val * phiVal % bigMod
ans += phi
phi *= 5
phiVal = (phiVal *
phiVal % bigMod *
phiVal % bigMod *
phiVal % bigMod *
phiVal % bigMod)
mod = nextMod
return ans
def main():
inp = input()
n = len(inp)
a = int(inp)
for m in range(n + 1):
l = a * 10 ** m
x, mod = l, 2 ** (n + m)
if x % mod != 0:
x += mod - x % mod
if x % 5 == 0:
x += mod
if x < l + 10 ** m:
assert x % mod == 0 and x % 5 != 0
x = x // mod
mod = 5 ** (n + m)
print(n + m + dlog(x % mod, n + m))
return
assert False
def __starting_point():
cnt = int(input())
for i in range(cnt):
main()
__starting_point()
``` | vfc_17002 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/913/G",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n8\n2\n",
"output": "3\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n3\n4857\n",
"output": "5\n20\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1813 | Solve the following coding problem using the programming language python:
Alexandra has a paper strip with n numbers on it. Let's call them a_{i} from left to right.
Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:
Each piece should contain at least l numbers.
The difference between the maximal and the minimal number on the piece should be at most s.
Please help Alexandra to find the minimal number of pieces meeting the condition above.
-----Input-----
The first line contains three space-separated integers n, s, l (1 ≤ n ≤ 10^5, 0 ≤ s ≤ 10^9, 1 ≤ l ≤ 10^5).
The second line contains n integers a_{i} separated by spaces ( - 10^9 ≤ a_{i} ≤ 10^9).
-----Output-----
Output the minimal number of strip pieces.
If there are no ways to split the strip, output -1.
-----Examples-----
Input
7 2 2
1 3 1 2 4 1 2
Output
3
Input
7 2 2
1 100 1 100 1 100 1
Output
-1
-----Note-----
For the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2].
For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def split(a,n,s,l):
pieces = []
i = 1
tmpmin = a[0]
tmpmax = a[0]
tmppc = [a[0]]
while i<n:
if abs(a[i]-tmpmin)<=s and abs(a[i]-tmpmax)<=s:
tmppc.append(a[i])
if a[i]<tmpmin: tmpmin=a[i]
elif a[i]>tmpmax: tmpmax = a[i]
else:
pieces.append(tmppc)
tmppc = [a[i]]
tmpmin = a[i]
tmpmax = a[i]
i += 1
pieces.append(tmppc)
fail = False
for j in range(len(pieces)):
if len(pieces[j])<l:
if j>0:
prevpc = pieces[j-1]
minj = min(pieces[j])
maxj = max(pieces[j])
while len(pieces[j])<l:
tmp = prevpc.pop()
if abs(tmp-minj)<=s and abs(tmp-maxj)<=s:
pieces[j].insert(0,tmp)
if tmp<minj: minj=tmp
elif tmp>maxj: maxj=tmp
else:
return -1
if len(prevpc)<l:
return -1
else:
return -1
return len(pieces)
n,s,l = [int(s) for s in input().split()]
a = [int(s) for s in input().split()]
res = split(a,n,s,l)
if res<0:
a.reverse()
res = split(a,n,s,l)
print(res)
``` | vfc_17006 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/488/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 2 2\n1 3 1 2 4 1 2\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1814 | Solve the following coding problem using the programming language python:
In the year of $30XX$ participants of some world programming championship live in a single large hotel. The hotel has $n$ floors. Each floor has $m$ sections with a single corridor connecting all of them. The sections are enumerated from $1$ to $m$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $n$ and width $m$. We can denote sections with pairs of integers $(i, j)$, where $i$ is the floor, and $j$ is the section number on the floor.
The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $(1, x)$, $(2, x)$, $\ldots$, $(n, x)$ for some $x$ between $1$ and $m$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $v$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.
You are to process $q$ queries. Each query is a question "what is the minimum time needed to go from a room in section $(x_1, y_1)$ to a room in section $(x_2, y_2)$?"
-----Input-----
The first line contains five integers $n, m, c_l, c_e, v$ ($2 \leq n, m \leq 10^8$, $0 \leq c_l, c_e \leq 10^5$, $1 \leq c_l + c_e \leq m - 1$, $1 \leq v \leq n - 1$) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively.
The second line contains $c_l$ integers $l_1, \ldots, l_{c_l}$ in increasing order ($1 \leq l_i \leq m$), denoting the positions of the stairs. If $c_l = 0$, the second line is empty.
The third line contains $c_e$ integers $e_1, \ldots, e_{c_e}$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $l_i$ and $e_i$ are distinct.
The fourth line contains a single integer $q$ ($1 \leq q \leq 10^5$) — the number of queries.
The next $q$ lines describe queries. Each of these lines contains four integers $x_1, y_1, x_2, y_2$ ($1 \leq x_1, x_2 \leq n$, $1 \leq y_1, y_2 \leq m$) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. $y_1$ and $y_2$ are not among $l_i$ and $e_i$.
-----Output-----
Print $q$ integers, one per line — the answers for the queries.
-----Example-----
Input
5 6 1 1 3
2
5
3
1 1 5 6
1 3 5 4
3 3 5 3
Output
7
5
4
-----Note-----
In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.
In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def takeClosest(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
"""
if len(myList) == 0:
return 9e10
pos = bisect_left(myList, myNumber)
if pos == 0:
return myList[0]
if pos == len(myList):
return myList[-1]
before = myList[pos - 1]
after = myList[pos]
if after - myNumber < myNumber - before:
return after
else:
return before
from bisect import bisect_left
from math import ceil
n, m, n_stairs, n_elevators, v = map(int, input().split(" "))
if n_stairs > 0:
stairs = list(map(int, input().split(" ")))
else:
stairs = []
input()
if n_elevators > 0:
elevators = list(map(int, input().split(" ")))
else:
elevators = []
input()
queries = int(input())
res = []
for i in range(queries):
x1, y1, x2, y2 = map(int, input().split(" "))
next_elevator = takeClosest(elevators, (y1 + y2) / 2)
next_stairs = takeClosest(stairs, (y1 + y2) / 2)
time_elevator = abs(x1 - x2) / v
time_stairs = abs(x1 - x2)
mi = min(y1, y2)
ma = max(y1, y2)
if next_elevator < mi:
time_elevator += (mi - next_elevator) * 2
elif next_elevator > ma:
time_elevator += (next_elevator - ma) * 2
if next_stairs < mi:
time_stairs += (mi - next_stairs) * 2
elif next_stairs > ma:
time_stairs += (next_stairs - ma) * 2
dis = abs(y1 - y2)
if time_elevator < time_stairs:
dis += time_elevator
else:
dis += time_stairs
if x1 == x2:
res.append(abs(y1 - y2))
else:
res.append(ceil(dis))
print(*res, sep="\n")
# Made By Mostafa_Khaled
``` | vfc_17010 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/925/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3\n",
"output": "7\n5\n4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2 0 1 1\n\n1\n1\n1 2 2 2\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4 1 0 1\n4\n\n5\n1 1 2 2\n1 3 2 2\n3 3 4 3\n3 2 2 2\n1 2 2 3\n",
"output": "6\n4\n3\n5\n4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10 1 8 4\n10\n2 3 4 5 6 7 8 9\n10\n1 1 3 1\n2 1 7 1\n1 1 9 1\n7 1 4 1\n10 1 7 1\n2 1 7 1\n3 1 2 1\n5 1 2 1\n10 1 5 1\n6 1 9 1\n",
"output": "3\n4\n4\n3\n3\n4\n3\n3\n4\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 5 1 0 1\n2\n\n1\n1 4 1 5\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 10 1 1 1\n1\n10\n1\n1 5 1 8\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1815 | Solve the following coding problem using the programming language python:
This problem is same as the previous one, but has larger 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^5$) — 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 100 20 200 1
Output
5
Input
1
100000
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
counts = {}
rcount = {}
input()
m = 0
for i, x in enumerate(map(int, input().split())):
if x in counts:
rcount[counts[x]].remove(x)
if not rcount[counts[x]]:
del rcount[counts[x]]
counts[x] += 1
if counts[x] not in rcount: rcount[counts[x]] = set()
rcount[counts[x]].add(x)
else:
counts[x] = 1
if 1 not in rcount: rcount[1] = set()
rcount[1].add(x)
keys = list(rcount)
if len(keys) == 2 and max(keys) - min(keys) == 1 and len(rcount[max(keys)]) == 1 or len(keys) == 2 and min(keys) == 1 and len(rcount[1]) == 1 or len(keys) == 1 and (len(rcount[keys[0]]) == 1 or keys[0] == 1):
m = max(m, i)
print(m + 1)
``` | vfc_17014 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1163/B2",
"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"
},
{
"fn_name": null,
"input": "5\n10 100 20 200 1\n",
"output": "5",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n100000\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n3 2 1 1 4 5 1\n",
"output": "6",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1816 | Solve the following coding problem using the programming language python:
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the f_{i}-th fragment of the file (1 ≤ f_{i} ≤ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
-----Input-----
The first line contains a positive integer n (1 ≤ n ≤ 2·10^5) — the number of fragments.
The second line contains n different integers f_{i} (1 ≤ f_{i} ≤ n) — the number of the fragment written in the i-th sector.
-----Output-----
Print the only integer — the number of time units needed to read the file.
-----Examples-----
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
-----Note-----
In the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
k=0
d = [0] * 200005
x = int(input())
p = list(map(int, input().split(' ')))
for i in range(len(p)):
d[p[i]] = i
for i in range(1, x):
k += abs(d[i+1] - d[i])
print(k)
``` | vfc_17018 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/612/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 1 2\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 3 5 4 2\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1817 | Solve the following coding problem using the programming language python:
Two players play a game.
Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.
The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.
You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 1000$) — the number of numbers on the board.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^6$).
-----Output-----
Print one number that will be left on the board.
-----Examples-----
Input
3
2 1 3
Output
2
Input
3
2 2 2
Output
2
-----Note-----
In the first sample, the first player erases $3$ and the second erases $1$. $2$ is left on the board.
In the second sample, $2$ is left on the board regardless of the actions of the players.
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())
num = list(map(int, input().split()))
for i in range(n - 1):
if i % 2 == 0:
num.pop(num.index(max(num)))
else:
num.pop(num.index(min(num)))
print(*num)
``` | vfc_17022 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/984/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 1 3\n",
"output": "2",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1818 | Solve the following coding problem using the programming language python:
Dima got into number sequences. Now he's got sequence a_1, a_2, ..., a_{n}, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence: f(0) = 0; f(2·x) = f(x); f(2·x + 1) = f(x) + 1.
Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤ n) are there, such that f(a_{i}) = f(a_{j}). Help him, count the number of such pairs.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5). The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
The numbers in the lines are separated by single spaces.
-----Output-----
In a single line print the answer to the problem.
Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
3
1 2 4
Output
3
Input
3
5 3 1
Output
1
-----Note-----
In the first sample any pair (i, j) will do, so the answer is 3.
In the second sample only pair (1, 2) will do.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
3
mem = [-1] * 100000
def f(x):
if x == 0:
return 0
if x < 100000 and mem[x] != -1:
return mem[x]
if x % 2 == 0:
res = f(x // 2)
else:
res = f((x - 1) // 2) + 1
if x < 100000:
mem[x] = res
return res
n = int(input())
a = list(map(int, input().split()))
cnt = {}
for v in a:
k = f(v)
cnt[k] = cnt.get(k, 0) + 1
print(sum([v * (v - 1) // 2 for v in list(cnt.values())]))
``` | vfc_17026 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/272/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 4\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n5 3 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n469264357 996569493\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n396640239 62005863 473635171 329666981 510631133 207643327\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n851991424 32517099 310793856 776130403 342626527 58796623 49544509 517126753\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1819 | Solve the following coding problem using the programming language python:
You have a list of numbers from $1$ to $n$ written from left to right on the blackboard.
You perform an algorithm consisting of several steps (steps are $1$-indexed). On the $i$-th step you wipe the $i$-th number (considering only remaining numbers). You wipe the whole number (not one digit). $\left. \begin{array}{r}{1234567 \ldots} \\{234567 \ldots} \\{24567 \ldots} \end{array} \right.$
When there are less than $i$ numbers remaining, you stop your algorithm.
Now you wonder: what is the value of the $x$-th remaining number after the algorithm is stopped?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 100$) — the number of queries. The next $T$ lines contain queries — one per line. All queries are independent.
Each line contains two space-separated integers $n$ and $x$ ($1 \le x < n \le 10^{9}$) — the length of the list and the position we wonder about. It's guaranteed that after the algorithm ends, the list will still contain at least $x$ numbers.
-----Output-----
Print $T$ integers (one per query) — the values of the $x$-th number after performing the algorithm for the corresponding queries.
-----Example-----
Input
3
3 1
4 2
69 6
Output
2
4
12
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, x] = [int(v) for v in input().split()]
print(2 * x)
``` | vfc_17030 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1194/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 1\n4 2\n69 6\n",
"output": "2\n4\n12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1000000000 1\n1000000000 500000000\n",
"output": "2\n1000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2441139 10\n",
"output": "20\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2441139 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n244139 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2441139 12\n",
"output": "24\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1820 | Solve the following coding problem using the programming language python:
You are given an array $a_1, a_2, \dots , a_n$, which is sorted in non-decreasing order ($a_i \le a_{i + 1})$.
Find three indices $i$, $j$, $k$ such that $1 \le i < j < k \le n$ and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $a_i$, $a_j$ and $a_k$ (for example it is possible to construct a non-degenerate triangle with sides $3$, $4$ and $5$ but impossible with sides $3$, $4$ and $7$). If it is impossible to find such triple, report it.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The first line of each test case contains one integer $n$ ($3 \le n \le 5 \cdot 10^4$) — the length of the array $a$.
The second line of each test case contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le 10^9$; $a_{i - 1} \le a_i$) — the array $a$.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case print the answer to it in one line.
If there is a triple of indices $i$, $j$, $k$ ($i < j < k$) such that it is impossible to construct a non-degenerate triangle having sides equal to $a_i$, $a_j$ and $a_k$, print that three indices in ascending order. If there are multiple answers, print any of them.
Otherwise, print -1.
-----Example-----
Input
3
7
4 6 11 11 15 18 20
4
10 10 10 11
3
1 1 1000000000
Output
2 3 6
-1
1 2 3
-----Note-----
In the first test case it is impossible with sides $6$, $11$ and $18$. Note, that this is not the only correct answer.
In the second test case you always can construct a non-degenerate triangle.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
for _ in range(int(input())):
am = int(input())
arr = list(map(int,input().split()))
if arr[0] + arr[1] > arr[-1]:
print(-1)
else:
print(1,2,am)
``` | vfc_17034 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1398/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n7\n4 6 11 11 15 18 20\n4\n10 10 10 11\n3\n1 1 1000000000\n",
"output": "1 2 7\n-1\n1 2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3\n78788 78788 100000\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3\n78788 78788 157577\n",
"output": "1 2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n10\n1 7 7 7 7 9 9 9 9 9\n",
"output": "1 2 10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n6\n1 1 1 2 2 3\n",
"output": "1 2 6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3\n5623 5624 10000000\n",
"output": "1 2 3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1822 | Solve the following coding problem using the programming language python:
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
-----Input-----
The first line contains two integers n (1 ≤ n ≤ 10^3) and x (1 ≤ x ≤ n) — the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ n) — the number of the beaver followed by the i-th beaver. If a_{i} = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values a_{i} are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1): It is guaranteed that the number of zero elements a_{i} doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2): The number of zero elements a_{i} is arbitrary.
-----Output-----
Print all possible positions of the Smart Beaver in the line in the increasing order.
-----Examples-----
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
-----Note----- [Image] Picture for the fourth test.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, x = list(map(int, input().split()))
link1 = list(map(int, input().split()))
link2 = [0] * (n + 1)
for i, v in enumerate(link1, 1):
if v != 0:
link2[v] = i
table = [False] * n
table[0] = True
for i, v in enumerate(link1, 1):
if v == 0:
len = 0
flag = False
now = i
while now:
len += 1
if now == x:
flag = True
pos = len
now = link2[now]
if not flag:
for j in reversed(list(range(n - len))):
if table[j]:
table[j + len] = True
for i in range(n):
if table[i]:
print(i + pos)
``` | vfc_17042 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/316/B1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 1\n2 0 4 0 6 0\n",
"output": "2\n4\n6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 2\n2 3 0 5 6 0\n",
"output": "2\n5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n0 0 0 0\n",
"output": "1\n2\n3\n4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1823 | Solve the following coding problem using the programming language python:
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.
On the i-th day the festival will show a movie of genre a_{i}. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a_1, a_2, ..., a_{n} at least once.
Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.
As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.
Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.
Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
-----Input-----
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 10^5), where n is the number of movies and k is the number of genres.
The second line of the input contains a sequence of n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ k), where a_{i} is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
-----Output-----
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
-----Examples-----
Input
10 3
1 1 2 3 2 3 3 1 1 3
Output
3
Input
7 3
3 1 3 2 3 1 2
Output
1
-----Note-----
In the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.
In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
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())
t = list(map(int, input().split()))
t = [t[0]] + [t[i] for i in range(1, len(t)) if t[i] != t[i - 1]]
p = [0] * (k + 1)
for i in range(1, len(t) - 1):
if t[i - 1] == t[i + 1]: p[t[i]] += 2
else: p[t[i]] += 1
p[t[0]] += 1
p[t[-1]] += 1
print(p.index(max(p)))
``` | vfc_17046 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/250/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 3\n1 1 2 3 2 3 3 1 1 3\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 3\n3 1 3 2 3 1 2\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n1 2\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 2\n1 2 2 1 1 2 1 1 2 2\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n5 7 8 2 4 10 1 3 9 6\n",
"output": "1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1824 | Solve the following coding problem using the programming language python:
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.
However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.
Can you help B find out exactly what two errors he corrected?
-----Input-----
The first line of the input contains integer n (3 ≤ n ≤ 10^5) — the initial number of compilation errors.
The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the errors the compiler displayed for the first time.
The third line contains n - 1 space-separated integers b_1, b_2, ..., b_{n} - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one.
The fourth line contains n - 2 space-separated integers с_1, с_2, ..., с_{n} - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
-----Output-----
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
-----Examples-----
Input
5
1 5 8 123 7
123 7 5 1
5 1 7
Output
8
123
Input
6
1 4 3 3 5 7
3 7 5 4 3
4 3 7 5
Output
1
3
-----Note-----
In the first test sample B first corrects the error number 8, then the error number 123.
In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
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())
one = sum([int(x) for x in input().strip().split()])
two = sum([int(x) for x in input().strip().split()])
three = sum([int(x) for x in input().strip().split()])
print(one-two)
print(two-three)
``` | vfc_17050 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/519/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 5 8 123 7\n123 7 5 1\n5 1 7\n",
"output": "8\n123\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5\n",
"output": "1\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 2 3\n3 2\n2\n",
"output": "1\n3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1825 | Solve the following coding problem using the programming language python:
Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one.
Ivan knows some information about the string s. Namely, he remembers, that string t_{i} occurs in string s at least k_{i} times or more, he also remembers exactly k_{i} positions where the string t_{i} occurs in string s: these positions are x_{i}, 1, x_{i}, 2, ..., x_{i}, k_{i}. He remembers n such strings t_{i}.
You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings t_{i} and string s consist of small English letters only.
-----Input-----
The first line contains single integer n (1 ≤ n ≤ 10^5) — the number of strings Ivan remembers.
The next n lines contain information about the strings. The i-th of these lines contains non-empty string t_{i}, then positive integer k_{i}, which equal to the number of times the string t_{i} occurs in string s, and then k_{i} distinct positive integers x_{i}, 1, x_{i}, 2, ..., x_{i}, k_{i} in increasing order — positions, in which occurrences of the string t_{i} in the string s start. It is guaranteed that the sum of lengths of strings t_{i} doesn't exceed 10^6, 1 ≤ x_{i}, j ≤ 10^6, 1 ≤ k_{i} ≤ 10^6, and the sum of all k_{i} doesn't exceed 10^6. The strings t_{i} can coincide.
It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists.
-----Output-----
Print lexicographically minimal string that fits all the information Ivan remembers.
-----Examples-----
Input
3
a 4 1 3 5 7
ab 2 1 5
ca 1 4
Output
abacaba
Input
1
a 1 3
Output
aaa
Input
3
ab 1 1
aba 1 3
ab 2 3 5
Output
ababab
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math as mt
import sys,string
input=sys.stdin.readline
print=sys.stdout.write
import random
from collections import deque,defaultdict
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
t=I()
d=defaultdict(str)
ml=0
p=0
for _ in range(t):
s=input().split()
w=s[0]
x=list(map(int,s[1::]))
for i in range(1,len(x)):
r=d[x[i]-1]
if(len(r)<len(w)):
d[x[i]-1]=w
ml=max(ml,len(w)+x[-1]-1)
ans="a"*ml
ans=list(ans)
#print(d)
p=-1
z=sorted(list(d.keys()))
for i in z:
if(i+len(d[i])>p):
if(i>=p):
for j in range(i,i+len(d[i])):
ans[j]=d[i][j-i]
else:
leave=p-i
f=max(i,p)
#print(ans,"@",d[i],p,d[i][leave::])
for j in range(leave,len(d[i])):
ans[f]=d[i][j]
f+=1
#print(ans,"*")
p=i+len(d[i])
for i in ans:
print(i)
``` | vfc_17054 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/828/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\na 4 1 3 5 7\nab 2 1 5\nca 1 4\n",
"output": "abacaba\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\na 1 3\n",
"output": "aaa\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nab 1 1\naba 1 3\nab 2 3 5\n",
"output": "ababab\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\nba 2 16 18\na 1 12\nb 3 4 13 20\nbb 2 6 8\nababbbbbaab 1 3\nabababbbbb 1 1\n",
"output": "abababbbbbaabaababab\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1826 | Solve the following coding problem using the programming language python:
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.
Your problem is to print the minimum possible length of the sequence of moves after the replacements.
-----Input-----
The first line of the input contains one integer n (1 ≤ n ≤ 100) — the length of the sequence. The second line contains the sequence consisting of n characters U and R.
-----Output-----
Print the minimum possible length of the sequence of moves after all replacements are done.
-----Examples-----
Input
5
RUURU
Output
3
Input
17
UUURRRRRUUURURUUU
Output
13
-----Note-----
In the first test the shortened sequence of moves may be DUD (its length is 3).
In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13).
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())
st = input()
ans = n
i = 1
while i < n:
if st[i - 1] != st[i]:
ans -= 1
i += 1
i += 1
print(ans)
``` | vfc_17058 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/954/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\nRUURU\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "17\nUUURRRRRUUURURUUU\n",
"output": "13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\nUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n",
"output": "100\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\nRRURRUUUURURRRURRRRURRRRRRURRUURRRUUURUURURRURUURUURRUURUURRURURUUUUURUUUUUURRUUURRRURRURRRUURRUUUUR\n",
"output": "67\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\nUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUURUUUUUUUUUUUUUUUUUUUUU\n",
"output": "99\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nRUR\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1827 | Solve the following coding problem using the programming language python:
Вася купил стол, у которого n ножек. Каждая ножка состоит из двух частей, которые соединяются друг с другом. Каждая часть может быть произвольной положительной длины, но гарантируется, что из всех 2n частей возможно составить n ножек одинаковой длины. При составлении ножки любые две части могут быть соединены друг с другом. Изначально все ножки стола разобраны, а вам заданы длины 2n частей в произвольном порядке.
Помогите Васе собрать все ножки стола так, чтобы все они были одинаковой длины, разбив заданные 2n части на пары правильным образом. Каждая ножка обязательно должна быть составлена ровно из двух частей, не разрешается использовать как ножку только одну часть.
-----Входные данные-----
В первой строке задано число n (1 ≤ n ≤ 1000) — количество ножек у стола, купленного Васей.
Во второй строке следует последовательность из 2n целых положительных чисел a_1, a_2, ..., a_2n (1 ≤ a_{i} ≤ 100 000) — длины частей ножек стола в произвольном порядке.
-----Выходные данные-----
Выведите n строк по два целых числа в каждой — длины частей ножек, которые надо соединить друг с другом. Гарантируется, что всегда возможно собрать n ножек одинаковой длины. Если ответов несколько, разрешается вывести любой из них.
-----Примеры-----
Входные данные
3
1 3 2 4 5 3
Выходные данные
1 5
2 4
3 3
Входные данные
3
1 1 1 2 2 2
Выходные данные
1 2
2 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
a = int(input())
lt = sorted(list(map(int, input().split())))
for i in range(len(lt)//2):
print(lt[i], lt[-i-1])
``` | vfc_17062 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/648/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 3 2 4 5 3\n",
"output": "1 5\n2 4\n3 3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1828 | Solve the following coding problem using the programming language python:
Maria participates in a bicycle race.
The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.
Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).
Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.
Help Maria get ready for the competition — determine the number of dangerous turns on the track.
-----Input-----
The first line of the input contains an integer n (4 ≤ n ≤ 1000) — the number of straight sections of the track.
The following (n + 1)-th line contains pairs of integers (x_{i}, y_{i}) ( - 10 000 ≤ x_{i}, y_{i} ≤ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (x_{i}, y_{i}) and ends at the point (x_{i} + 1, y_{i} + 1).
It is guaranteed that:
the first straight section is directed to the north; the southernmost (and if there are several, then the most western of among them) point of the track is the first point; the last point coincides with the first one (i.e., the start position); any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point); no pair of points (except for the first and last one) is the same; no two adjacent straight sections are directed in the same direction or in opposite directions.
-----Output-----
Print a single integer — the number of dangerous turns on the track.
-----Examples-----
Input
6
0 0
0 1
1 1
1 2
2 2
2 0
0 0
Output
1
Input
16
1 1
1 5
3 5
3 7
2 7
2 9
6 9
6 7
5 7
5 3
4 3
4 4
3 4
3 2
5 2
5 1
1 1
Output
6
-----Note-----
The first sample corresponds to the picture:
[Image]
The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer is 1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#!/usr/bin/env python3
try:
while True:
n = int(input())
prev_x, prev_y = list(map(int, input().split()))
prev_d = 0
result = 0
for i in range(n):
x, y = list(map(int, input().split()))
if y > prev_y:
d = 0
elif x > prev_x:
d = 1
elif y < prev_y:
d = 2
else:
d = 3
if ((d + 1) & 0x3) == prev_d:
result += 1
prev_x, prev_y = x, y
prev_d = d
print(result)
except EOFError:
pass
``` | vfc_17066 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/659/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n0 0\n0 1\n1 1\n1 2\n2 2\n2 0\n0 0\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1829 | Solve the following coding problem using the programming language python:
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.
You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?
-----Input-----
The first input line contains two integers n and m (1 ≤ n, m ≤ 10^3) — number of words PolandBall and EnemyBall know, respectively.
Then n strings follow, one per line — words familiar to PolandBall.
Then m strings follow, one per line — words familiar to EnemyBall.
Note that one Ball cannot know a word more than once (strings are unique), but some words can be known by both players.
Each word is non-empty and consists of no more than 500 lowercase English alphabet letters.
-----Output-----
In a single line of print the answer — "YES" if PolandBall wins and "NO" otherwise. Both Balls play optimally.
-----Examples-----
Input
5 1
polandball
is
a
cool
character
nope
Output
YES
Input
2 2
kremowka
wadowicka
kremowka
wiedenska
Output
YES
Input
1 2
a
a
b
Output
NO
-----Note-----
In the first example PolandBall knows much more words and wins effortlessly.
In the second example if PolandBall says kremowka first, then EnemyBall cannot use that word anymore. EnemyBall can only say wiedenska. PolandBall says wadowicka and wins.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
n, m = list(map(int, input().split()))
p_words = set()
e_words = set()
for _ in range(n):
p_words.add(input())
for _ in range(m):
e_words.add(input())
common = p_words & e_words
p_words -= common
e_words -= common
we_win = False
p_turn = True
a, b, c = len(p_words), len(e_words), len(common)
while True:
if c > 0:
c -= 1
else:
if p_turn:
if a == 0:
we_win = False
break
else:
a -= 1
else:
if b == 0:
we_win = True
break
else:
b -= 1
p_turn = not p_turn
print("YES" if we_win else "NO")
main()
``` | vfc_17070 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/755/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 1\npolandball\nis\na\ncool\ncharacter\nnope\n",
"output": "YES",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\nkremowka\nwadowicka\nkremowka\nwiedenska\n",
"output": "YES",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\na\na\nb\n",
"output": "NO",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\na\nb\nb\nc\n",
"output": "YES",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1830 | Solve the following coding problem using the programming language python:
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.
You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
-----Input-----
The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ min(100 000, n^2)) — the size of the board and the number of rooks.
Each of the next m lines contains integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ n) — the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
-----Output-----
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
-----Examples-----
Input
3 3
1 1
3 1
2 2
Output
4 2 0
Input
5 2
1 5
5 1
Output
16 9
Input
100000 1
300 400
Output
9999800001
-----Note-----
On the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
[Image]
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())
sum = n ** 2
colx = n
coly = n
usedx = [False] * n
usedy = [False] * n
for i in range(m):
x, y = map(int, input().split())
x -= 1
y -= 1
if not usedx[x]:
sum -= coly
usedx[x] = True
colx -= 1
if not usedy[y]:
sum -= colx
usedy[y] = True
coly -= 1
print(sum, end = ' ')
``` | vfc_17074 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/701/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3\n1 1\n3 1\n2 2\n",
"output": "4 2 0 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n1 5\n5 1\n",
"output": "16 9 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100000 1\n300 400\n",
"output": "9999800001 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 4\n2 8\n1 8\n9 8\n6 9\n",
"output": "81 72 63 48 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "30 30\n3 13\n27 23\n18 24\n18 19\n14 20\n7 10\n27 13\n20 27\n11 1\n21 10\n2 9\n28 12\n29 19\n28 27\n27 29\n30 12\n27 2\n4 5\n8 19\n21 2\n24 27\n14 22\n20 3\n18 3\n23 9\n28 6\n15 12\n2 2\n16 27\n1 14\n",
"output": "841 784 729 702 650 600 600 552 506 484 441 400 380 380 361 342 324 289 272 272 255 240 225 225 210 196 182 182 168 143 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1832 | Solve the following coding problem using the programming language python:
The length of the longest common prefix of two strings $s = s_1 s_2 \ldots s_n$ and $t = t_1 t_2 \ldots t_m$ is defined as the maximum integer $k$ ($0 \le k \le min(n,m)$) such that $s_1 s_2 \ldots s_k$ equals $t_1 t_2 \ldots t_k$.
Koa the Koala initially has $n+1$ strings $s_1, s_2, \dots, s_{n+1}$.
For each $i$ ($1 \le i \le n$) she calculated $a_i$ — the length of the longest common prefix of $s_i$ and $s_{i+1}$.
Several days later Koa found these numbers, but she couldn't remember the strings.
So Koa would like to find some strings $s_1, s_2, \dots, s_{n+1}$ which would have generated numbers $a_1, a_2, \dots, a_n$. Can you help her?
If there are many answers print any. We can show that answer always exists for the given constraints.
-----Input-----
Each test contains multiple test cases. The first line contains $t$ ($1 \le t \le 100$) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 100$) — the number of elements in the list $a$.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 50$) — the elements of $a$.
It is guaranteed that the sum of $n$ over all test cases does not exceed $100$.
-----Output-----
For each test case:
Output $n+1$ lines. In the $i$-th line print string $s_i$ ($1 \le |s_i| \le 200$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $s_i$ and $s_{i+1}$ has to be equal to $a_i$.
If there are many answers print any. We can show that answer always exists for the given constraints.
-----Example-----
Input
4
4
1 2 4 2
2
5 3
3
1 3 1
3
0 0 0
Output
aeren
ari
arousal
around
ari
monogon
monogamy
monthly
kevinvu
kuroni
kurioni
korone
anton
loves
adhoc
problems
-----Note-----
In the $1$-st test case one of the possible answers is $s = [aeren, ari, arousal, around, ari]$.
Lengths of longest common prefixes are: Between $\color{red}{a}eren$ and $\color{red}{a}ri$ $\rightarrow 1$ Between $\color{red}{ar}i$ and $\color{red}{ar}ousal$ $\rightarrow 2$ Between $\color{red}{arou}sal$ and $\color{red}{arou}nd$ $\rightarrow 4$ Between $\color{red}{ar}ound$ and $\color{red}{ar}i$ $\rightarrow 2$
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
rndid = "cuuhkjc"
for _ in range(int(input())):
input()
ls = 'a' * 51
oa = ord('a')
print(ls)
for a in input().split():
a = int(a)
ls = ls[:a] + ls[a:].translate({oa: 'b', oa + 1: 'a'})
print(ls)
``` | vfc_17082 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1384/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0\n",
"output": "aaaa\nabbb\nabaa\nabaa\nabbb\naaaaa\naaaaa\naaabb\naaa\nabb\nabb\naaa\na\nb\na\nb\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n4\n5 3 1 5\n1\n3\n3\n5 5 1\n3\n2 3 0\n1\n5\n",
"output": "aaaaa\naaaaa\naaabb\nabbbb\nabbbb\naaa\naaa\naaaaa\naaaaa\naaaaa\nabbbb\naaa\naab\naab\nbbb\naaaaa\naaaaa\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n9\n2 0 2 3 1 3 1 4 5\n5\n5 4 7 9 7\n5\n8 1 3 3 7\n3\n9 6 1\n3\n6 8 2\n",
"output": "aaaaa\naabbb\nbbbbb\nbbaaa\nbbabb\nbaaaa\nbaabb\nbbbbb\nbbbba\nbbbba\naaaaaaaaa\naaaaabbbb\naaaabbbbb\naaaabbbaa\naaaabbbaa\naaaabbbbb\naaaaaaaa\naaaaaaaa\nabbbbbbb\nabbaaaaa\nabbbbbbb\nabbbbbba\naaaaaaaaa\naaaaaaaaa\naaaaaabbb\nabbbbbbbb\naaaaaaaa\naaaaaabb\naaaaaabb\naabbbbbb\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n4\n3 5 2 4\n9\n5 4 5 6 4 2 0 1 0\n3\n1 1 2\n7\n4 6 0 5 5 5 6\n1\n1\n",
"output": "aaaaa\naaabb\naaabb\naabbb\naabba\naaaaaa\naaaaab\naaaabb\naaaaba\naaaaba\naaaaaa\naabbbb\nbbbbbb\nbaaaaa\naaaaaa\naa\nab\naa\naa\naaaaaa\naaaabb\naaaabb\nbbbbbb\nbbbbba\nbbbbbb\nbbbbba\nbbbbba\na\na\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n2\n1 6\n3\n3 2 7\n1\n6\n3\n5 5 6\n2\n6 0\n",
"output": "aaaaaa\nabbbbb\nabbbbb\naaaaaaa\naaabbbb\naabbbbb\naabbbbb\naaaaaa\naaaaaa\naaaaaa\naaaaab\naaaaaa\naaaaaa\naaaaaa\naaaaaa\nbbbbbb\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1833 | Solve the following coding problem using the programming language python:
You are given an integer array $a_1, a_2, \ldots, a_n$.
The array $b$ is called to be a subsequence of $a$ if it is possible to remove some elements from $a$ to get $b$.
Array $b_1, b_2, \ldots, b_k$ is called to be good if it is not empty and for every $i$ ($1 \le i \le k$) $b_i$ is divisible by $i$.
Find the number of good subsequences in $a$ modulo $10^9 + 7$.
Two subsequences are considered different if index sets of numbers included in them are different. That is, the values of the elements do not matter in the comparison of subsequences. In particular, the array $a$ has exactly $2^n - 1$ different subsequences (excluding an empty subsequence).
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 100\,000$) — the length of the array $a$.
The next line contains integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^6$).
-----Output-----
Print exactly one integer — the number of good subsequences taken modulo $10^9 + 7$.
-----Examples-----
Input
2
1 2
Output
3
Input
5
2 2 1 22 14
Output
13
-----Note-----
In the first example, all three non-empty possible subsequences are good: $\{1\}$, $\{1, 2\}$, $\{2\}$
In the second example, the possible good subsequences are: $\{2\}$, $\{2, 2\}$, $\{2, 22\}$, $\{2, 14\}$, $\{2\}$, $\{2, 22\}$, $\{2, 14\}$, $\{1\}$, $\{1, 22\}$, $\{1, 14\}$, $\{22\}$, $\{22, 14\}$, $\{14\}$.
Note, that some subsequences are listed more than once, since they occur in the original array multiple times.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math
n = int(input())
a = list(map(int, input().split()))
d = {0: 1}
m = 1
ans = 0
for i in a:
#print("i=", i)
divisors = []
for j in range(1, min(m, int(math.sqrt(i))) + 1):
if i % j == 0:
k = int(i / j)
divisors.append(j)
if j != k and k <= m:
divisors.append(k)
#print("divisors=", divisors)
new_d = {0: 1}
for j in divisors:
ans = (ans + d[j - 1]) % 1000000007
#print("j=", j, "ans=", ans)
new_d[j] = d.get(j, 0) + d[j - 1]
if j == m:
m = m + 1
#print("new_d=", new_d)
for j in new_d:
d[j] = new_d[j]
print(ans)
``` | vfc_17086 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1061/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 2\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n2 2 1 22 14\n",
"output": "13",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n519612\n",
"output": "1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1834 | Solve the following coding problem using the programming language python:
A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:
a_{i} ≥ a_{i} - 1 for all even i, a_{i} ≤ a_{i} - 1 for all odd i > 1.
For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.
Can you make the array z-sorted?
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a.
The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the elements of the array a.
-----Output-----
If it's possible to make the array a z-sorted print n space separated integers a_{i} — the elements after z-sort. Otherwise print the only word "Impossible".
-----Examples-----
Input
4
1 2 2 1
Output
1 2 1 2
Input
5
1 3 2 2 5
Output
1 5 2 3 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 = [int(i) for i in input().split()]
a.sort()
b = []
for i in range(n - 1, (n + 1) // 2 - 1, -1):
b.append(a[i])
a = a[:(n + 1) // 2]
c = []
for i in range(len(b)):
c.append(a[i])
c.append(b[i])
if len(a) > len(b):
c.append(a[-1])
print(*c)
``` | vfc_17090 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/652/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1 2 2 1\n",
"output": "1 2 1 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 3 2 2 5\n",
"output": "1 5 2 3 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1 1 1 1 1 1 1 1 1\n",
"output": "1 1 1 1 1 1 1 1 1 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 9 7 6 2 4 7 8 1 3\n",
"output": "1 9 1 8 2 7 3 7 4 6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n82 51 81 14 37 17 78 92 64 15 8 86 89 8 87 77 66 10 15 12 100 25 92 47 21 78 20 63 13 49 41 36 41 79 16 87 87 69 3 76 80 60 100 49 70 59 72 8 38 71 45 97 71 14 76 54 81 4 59 46 39 29 92 3 49 22 53 99 59 52 74 31 92 43 42 23 44 9 82 47 7 40 12 9 3 55 37 85 46 22 84 52 98 41 21 77 63 17 62 91\n",
"output": "3 100 3 100 3 99 4 98 7 97 8 92 8 92 8 92 9 92 9 91 10 89 12 87 12 87 13 87 14 86 14 85 15 84 15 82 16 82 17 81 17 81 20 80 21 79 21 78 22 78 22 77 23 77 25 76 29 76 31 74 36 72 37 71 37 71 38 70 39 69 40 66 41 64 41 63 41 63 42 62 43 60 44 59 45 59 46 59 46 55 47 54 47 53 49 52 49 52 49 51\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1835 | Solve the following coding problem using the programming language python:
A palindrome is a string $t$ which reads the same backward as forward (formally, $t[i] = t[|t| + 1 - i]$ for all $i \in [1, |t|]$). Here $|t|$ denotes the length of a string $t$. For example, the strings 010, 1001 and 0 are palindromes.
You have $n$ binary strings $s_1, s_2, \dots, s_n$ (each $s_i$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.
Formally, in one move you: choose four integer numbers $x, a, y, b$ such that $1 \le x, y \le n$ and $1 \le a \le |s_x|$ and $1 \le b \le |s_y|$ (where $x$ and $y$ are string indices and $a$ and $b$ are positions in strings $s_x$ and $s_y$ respectively), swap (exchange) the characters $s_x[a]$ and $s_y[b]$.
What is the maximum number of strings you can make palindromic simultaneously?
-----Input-----
The first line contains single integer $Q$ ($1 \le Q \le 50$) — the number of test cases.
The first line on each test case contains single integer $n$ ($1 \le n \le 50$) — the number of binary strings you have.
Next $n$ lines contains binary strings $s_1, s_2, \dots, s_n$ — one per line. It's guaranteed that $1 \le |s_i| \le 50$ and all strings constist of zeroes and/or ones.
-----Output-----
Print $Q$ integers — one per test case. The $i$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $i$-th test case.
-----Example-----
Input
4
1
0
3
1110
100110
010101
2
11111
000001
2
001
11100111
Output
1
2
2
2
-----Note-----
In the first test case, $s_1$ is palindrome, so the answer is $1$.
In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $s_1 = \text{0110}$, $s_2 = \text{111111}$ and $s_3 = \text{010000}$.
In the third test case we can make both strings palindromic. For example, $s_1 = \text{11011}$ and $s_2 = \text{100001}$.
In the last test case $s_2$ is palindrome and you can make $s_1$ palindrome, for example, by swapping $s_1[2]$ and $s_1[3]$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
import math
from collections import defaultdict
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : list(map(int, input().split()))
def write(*args, sep="\n"):
for i in args:
sys.stdout.write("{}".format(i) + sep)
INF = float('inf')
MOD = int(1e9 + 7)
for _ in range(int(input())):
n = int(input())
arr = sorted([input() for i in range(n)], key=lambda x:len(x))
zero_cnt, one_cnt = 0, 0
for i in arr:
zero_cnt += i.count('0')
one_cnt += i.count('1')
total = (zero_cnt//2) + (one_cnt//2)
ans = 0
for i in arr:
if total >= len(i)//2:
total -= len(i)//2
ans += 1
print(ans)
``` | vfc_17094 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1251/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111\n",
"output": "1\n2\n2\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n4\n0001000\n00000\n00000\n00000\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n33\n10\n1\n1\n1\n1\n1\n1\n1\n1\n1\n0\n0\n1\n1\n1\n1\n1\n0\n0\n0\n1\n1\n1\n1\n0\n1\n1\n1\n1\n0\n0\n1\n10\n",
"output": "33\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1836 | Solve the following coding problem using the programming language python:
This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions: Only segments already presented on the picture can be painted; The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment; The numbers of points from the beginning of the tail to the end should strictly increase.
Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.
Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.
-----Input-----
First line of the input contains two integers n and m(2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number segments on the picture respectively.
Then follow m lines, each containing two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.
-----Output-----
Print the maximum possible value of the hedgehog's beauty.
-----Examples-----
Input
8 6
4 5
3 5
2 5
1 2
2 8
6 7
Output
9
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
12
-----Note-----
The picture below corresponds to the first sample. Segments that form the hedgehog are painted red. The tail consists of a sequence of points with numbers 1, 2 and 5. The following segments are spines: (2, 5), (3, 5) and (4, 5). Therefore, the beauty of the hedgehog is equal to 3·3 = 9.
[Image]
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()))
p = [0] * n
e = []
for i in range(m):
q, w = list(map(int, input().split()))
p[w - 1] += 1
p[q - 1] += 1
e.append([min(q, w), max(q, w)])
dp = [1] * n
e.sort()
for i in range(m):
dp[e[i][1] - 1] = max(dp[e[i][1] - 1], dp[e[i][0] - 1] + 1)
ans = 0
for i in range(n):
ans = max(ans, dp[i] * p[i])
print(ans)
``` | vfc_17098 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/615/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "8 6\n4 5\n3 5\n2 5\n1 2\n2 8\n6 7\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n",
"output": "12\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1837 | Solve the following coding problem using the programming language python:
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.
A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a_0, a_1, ..., a_{n} - 1 if and only if a_{i} = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.
You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^5). The second line contains n integers a_0, a_1, ..., a_{n} - 1 — the given permutation.
-----Output-----
Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.
-----Examples-----
Input
5
0 1 3 4 2
Output
3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
A = list(map(int, input().split()))
cnt = 0
for i in range(n):
cnt += (A[i] == i)
if cnt == n:
print(n)
else:
ind = False
for i in range(n):
ind |= (A[i] != i and A[A[i]] == i)
if ind:
print(cnt + 2)
else:
print(cnt + 1)
``` | vfc_17102 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/347/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n0 1 3 4 2\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n6 9 4 7 8 2 3 5 0 1\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1838 | Solve the following coding problem using the programming language python:
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
-----Input-----
The first line of input contains three integers n, m and q (2 ≤ n ≤ 10^5, 1 ≤ m, q ≤ 10^5) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a_1, a_2, ..., a_{n} consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 ≤ t ≤ 2) followed by two different words x_{i} and y_{i} which has appeared in the dictionary words. If t = 1, that means x_{i} has a synonymy relation with y_{i}, otherwise x_{i} has an antonymy relation with y_{i}.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
-----Output-----
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
-----Examples-----
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
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
n,m,q=list(map(int,input().split()))
a=input().split()
c={x:([x],[]) for x in a}
for i in range(m):
t,x,y=input().split()
if t=='2':
sign=1
else: sign=0
if c[x][0] is c[y][1-sign]:
print("NO")
continue
print("YES")
if c[x][0] is c[y][sign]:
continue
c1,c2=c[x],c[y]
if len(c1[0])+len(c1[1])<len(c2[0])+len(c2[1]):
c1,c2=c2,c1
s1,a1=c1
if sign==0:
s2,a2=c2
else:
a2,s2=c2
s1+=s2
a1+=a2
cs=s1,a1
for x in s2:
c[x]=cs
ca=a1,s1
for x in a2:
c[x]=ca
for i in range(q):
x,y=input().split()
if c[x][0] is c[y][0]:
print(1)
elif c[x][0] is c[y][1]:
print(2)
else:
print(3)
``` | vfc_17106 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/766/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3 4\nhate love like\n1 love like\n2 love hate\n1 hate like\nlove like\nlove hate\nlike hate\nhate like\n",
"output": "YES\nYES\nNO\n1\n2\n2\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8 6 5\nhi welcome hello ihateyou goaway dog cat rat\n1 hi welcome\n1 ihateyou goaway\n2 hello ihateyou\n2 hi goaway\n2 hi hello\n1 hi hello\ndog cat\ndog hi\nhi hello\nihateyou goaway\nwelcome ihateyou\n",
"output": "YES\nYES\nYES\nYES\nNO\nYES\n3\n3\n1\n1\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 4 5\nhello hi welcome ihateyou goaway\n1 hello hi\n1 hi welcome\n2 ihateyou hi\n2 goaway hi\nwelcome hello\nihateyou welcome\nwelcome goaway\ngoaway ihateyou\nwelcome hi\n",
"output": "YES\nYES\nYES\nYES\n1\n2\n2\n1\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1 1\na b\n1 a b\na b\n",
"output": "YES\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1840 | Solve the following coding problem using the programming language python:
Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he understood, and he's ready to face the evils of the Empire!
The rebels have $s$ spaceships, each with a certain attacking power $a$.
They want to send their spaceships to destroy the empire bases and steal enough gold and supplies in order to keep the rebellion alive.
The empire has $b$ bases, each with a certain defensive power $d$, and a certain amount of gold $g$.
A spaceship can attack all the bases which have a defensive power less than or equal to its attacking power.
If a spaceship attacks a base, it steals all the gold in that base.
The rebels are still undecided which spaceship to send out first, so they asked for the Doctor's help. They would like to know, for each spaceship, the maximum amount of gold it can steal.
-----Input-----
The first line contains integers $s$ and $b$ ($1 \leq s, b \leq 10^5$), the number of spaceships and the number of bases, respectively.
The second line contains $s$ integers $a$ ($0 \leq a \leq 10^9$), the attacking power of each spaceship.
The next $b$ lines contain integers $d, g$ ($0 \leq d \leq 10^9$, $0 \leq g \leq 10^4$), the defensive power and the gold of each base, respectively.
-----Output-----
Print $s$ integers, the maximum amount of gold each spaceship can steal, in the same order as the spaceships are given in the input.
-----Example-----
Input
5 4
1 3 5 2 4
0 1
4 2
2 8
9 4
Output
1 9 11 9 11
-----Note-----
The first spaceship can only attack the first base.
The second spaceship can attack the first and third bases.
The third spaceship can attack the first, second and third bases.
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 sys
from operator import itemgetter
from fractions import gcd
from math import ceil, floor
from copy import deepcopy
from itertools import accumulate
from collections import Counter
import math
from functools import reduce
from bisect import bisect_right
sys.setrecursionlimit(200000)
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
def debug(x): print("debug: ", x, file=sys.stderr)
# template
class BIT:
def __init__(self, x, d=0):
if isinstance(x, int):
self.size = x
self.tree = [d for _ in range(self.size + 1)]
elif isinstance(x, list):
self.size = len(x)
self.tree = [d for _ in range(self.size + 1)]
self.build(x)
else:
raise TypeError
def build(self, arr):
if isinstance(arr, list):
raise TypeError
for num, x in enumerate(arr):
self.add0(num, x)
def sum(self, i):
s = self.tree[0]
while i > 0:
s += self.tree[i]
i -= (i & -i)
return s
def add(self, i, a):
if(i == 0):
return
while (i <= self.size):
self.tree[i] += a
i += (i & -i)
def bisect_left(self, w):
if w <= 0:
return 0
x = 0
r = 1
while (r < self.size):
r <<= 1
k = r
while (k > 0):
if x + k <= self.size and self.tree[x + k] < w:
w -= self.tree[x + k]
x += k
k >>= 1
return x + 1
def query(self, l, r):
return self.sum(r - 1) - self.sum(l - 1)
def sum0(self, i):
return self.sum(i + 1)
def add0(self, i, a):
self.add(i + 1, a)
def query0(self, l, r):
return self.sum(r) - self.sum(l)
def __getitem__(self, item):
_tmp = item.indices(self.size + 1)
return [self.sum(i) - self.sum(i - 1) for i in range(_tmp[0], _tmp[1], _tmp[2])]
def __str__(self):
return str(self[1:self.size + 1])
# END CUT HERE
def main():
s, b = mi()
a = lmi()
d = []
g = []
for i in range(b):
_d, _g = mi()
d.append(_d)
g.append(_g)
tmp = [(d[i], g[i]) for i in range(b)]
tmp.sort(key=lambda x: x[0])
d.sort()
# print(tmp)
# print(d)
bit = BIT(b)
for i in range(b):
bit.add0(i, tmp[i][1])
for i in range(s):
tmp = bisect_right(d, a[i])
# print(tmp)
print(bit.sum(tmp), end=" ")
print()
def __starting_point():
main()
__starting_point()
``` | vfc_17114 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1184/B1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 4\n1 3 5 2 4\n0 1\n4 2\n2 8\n9 4\n",
"output": "1 9 11 9 11\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1842 | Solve the following coding problem using the programming language python:
The Department of economic development of IT City created a model of city development till year 2100.
To prepare report about growth perspectives it is required to get growth estimates from the model.
To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.
The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.
-----Input-----
The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax^2 + bx + c = 0 equation.
-----Output-----
In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10^{ - 6}.
-----Examples-----
Input
1 30 200
Output
-10.000000000000000
-20.000000000000000
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math
a,b,c=map(int,input().split())
D = b ** 2 - 4 * a * c
x1 = (-b + math.sqrt(D)) / (2 * a)
x2 = (-b - math.sqrt(D)) / (2 * a)
ans1=max(x1,x2)
ans=min(x1,x2)
print(ans1)
print(ans)
``` | vfc_17122 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/N",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 30 200\n",
"output": "-10.000000000000000\n-20.000000000000000",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 -1\n",
"output": "0.618033988749895\n-1.618033988749895",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "-1 1 1\n",
"output": "1.618033988749895\n-0.618033988749895",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000 1 -1\n",
"output": "0.031126729201737\n-0.032126729201737",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "-1 1000 1\n",
"output": "1000.000999999000000\n-0.000999999000002",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000 1000 -999\n",
"output": "0.617586685675881\n-1.617586685675881",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1843 | Solve the following coding problem using the programming language python:
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.
For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 2^0, 2^1 and 2^2 respectively.
Calculate the answer for t values of n.
-----Input-----
The first line of the input contains a single integer t (1 ≤ t ≤ 100) — the number of values of n to be processed.
Each of next t lines contains a single integer n (1 ≤ n ≤ 10^9).
-----Output-----
Print the requested sum for each of t integers n given in the input.
-----Examples-----
Input
2
4
1000000000
Output
-4
499999998352516354
-----Note-----
The answer for the first sample is explained in the statement.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from math import floor,log
for _ in range(int(input())):
n=int(input())
p=(n*(n+1))//2
f=floor(log(n,2))
p-=2*(2**(f+1)-1)
print(p)
``` | vfc_17126 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/598/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n4\n1000000000\n",
"output": "-4\n499999998352516354\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n",
"output": "-1\n-3\n0\n-4\n1\n7\n14\n6\n15\n25\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n10\n9\n47\n33\n99\n83\n62\n1\n100\n53\n",
"output": "25\n15\n1002\n435\n4696\n3232\n1827\n-1\n4796\n1305\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n16\n",
"output": "74\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1844 | Solve the following coding problem using the programming language python:
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $n$ integers $a_i$.
It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $1$. Now Janusz wonders, for given sequence, how much elements should the player choose?
-----Input-----
The first line contains an only integer $n$ ($1 \le n \le 300\,000$) — the number of integers in the sequence.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 300\,000$).
-----Output-----
If there is no subset of the given sequence with gcd equal to $1$, output -1.
Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $1$.
-----Examples-----
Input
3
10 6 15
Output
3
Input
3
2 4 6
Output
-1
Input
7
30 60 21 42 70 15 30
Output
3
-----Note-----
In the first example, selecting a subset of all numbers gives a gcd of $1$ and for all smaller subsets the gcd is greater than $1$.
In the second example, for all subsets of numbers the gcd is at least $2$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from sys import *
maxn = 3 * 10 ** 5 + 5
fre = [0 for i in range(maxn)]
isprime = [1 for i in range(maxn)]
prime = []
divi = [0 for i in range(maxn)]
fact = [1] * 10
def nCr(n, r):
if n < r:
return 0
if n == r:
return 1
pro = 1
for i in range(r):
pro *= (n - i)
pro //= fact[r]
return pro
n = int(stdin.readline())
arr = list(map(int, stdin.readline().split()))
for i in arr:
if i is 1:
print(1)
return
fre[i] += 1
divi[1] = n
for i in range(2, maxn):
if isprime[i] is 1:
prime.append(i)
for j in range(1, maxn):
if i * j >= maxn:
break
isprime[i * j] = 0
divi[i] += fre[i * j]
for i in range(1, 10):
fact[i] = fact[i - 1] * i
mobius = [0 for i in range(maxn)]
for i in range(1, maxn):
mobius[i] = 1
for p in prime:
if p * p >= maxn:
break
x = p * p
for j in range(x, maxn, x):
mobius[j] = 0
for p in prime:
for j in range(p, maxn, p):
mobius[j] *= -1
for r in range(2, 10):
coprime = 0
for d in range(1, maxn):
ncr = nCr(divi[d], r)
coprime += mobius[d] * ncr
if coprime > 0:
print(r)
return
print(-1)
``` | vfc_17130 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1043/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n10 6 15\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 4 6\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n30 60 21 42 70 15 30\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n91630 147840 12600 52206 270270 48510 16170 33495 25080 60060\n",
"output": "5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1845 | Solve the following coding problem using the programming language python:
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $n$ machines, and the power of the $i$-th machine is $a_i$.
This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer $x$, then choose one machine and reduce the power of its machine by $x$ times, and at the same time increase the power of one another machine by $x$ times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices $i$ and $j$, and one integer $x$ such that $x$ is a divisor of $a_i$, and change powers as following: $a_i = \frac{a_i}{x}$, $a_j = a_j \cdot x$
Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 5 \cdot 10^4$) — the number of machines.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 100$) — the powers of the machines.
-----Output-----
Print one integer — minimum total power.
-----Examples-----
Input
5
1 2 3 4 5
Output
14
Input
4
4 2 4 4
Output
14
Input
5
2 4 2 3 7
Output
18
-----Note-----
In the first example, the farmer can reduce the power of the $4$-th machine by $2$ times, and increase the power of the $1$-st machine by $2$ times, then the powers will be: $[2, 2, 3, 2, 5]$.
In the second example, the farmer can reduce the power of the $3$-rd machine by $2$ times, and increase the power of the $2$-nd machine by $2$ times. At the same time, the farmer can leave is be as it is and the total power won't change.
In the third example, it is optimal to leave it be as it is.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import copy
import fractions
import itertools
import numbers
import string
import sys
###
def to_basex(num, x):
while num > 0:
yield num % x
num //= x
def from_basex(it, x):
ret = 0
p = 1
for d in it:
ret += d*p
p *= x
return ret
###
def core():
n = int(input())
a = [int(x) for x in input().split()]
m = min(a)
s = sum(a)
ans = s
for ai in a:
for d in range(1, ai+1):
if ai % d == 0:
cand = s - ai - m + ai//d + m*d
ans = min(ans, cand)
print(ans)
core()
``` | vfc_17134 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1113/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 3 4 5\n",
"output": "14\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n4 2 4 4\n",
"output": "14\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1846 | Solve the following coding problem using the programming language python:
Scientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet.
Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a thermometer on the balcony every morning and recorded the temperature. He had been measuring the temperature for the last n days. Thus, he got a sequence of numbers t_1, t_2, ..., t_{n}, where the i-th number is the temperature on the i-th day.
Vasya analyzed the temperature statistics in other cities, and came to the conclusion that the city has no environmental problems, if first the temperature outside is negative for some non-zero number of days, and then the temperature is positive for some non-zero number of days. More formally, there must be a positive integer k (1 ≤ k ≤ n - 1) such that t_1 < 0, t_2 < 0, ..., t_{k} < 0 and t_{k} + 1 > 0, t_{k} + 2 > 0, ..., t_{n} > 0. In particular, the temperature should never be zero. If this condition is not met, Vasya decides that his city has environmental problems, and gets upset.
You do not want to upset Vasya. Therefore, you want to select multiple values of temperature and modify them to satisfy Vasya's condition. You need to know what the least number of temperature values needs to be changed for that.
-----Input-----
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of days for which Vasya has been measuring the temperature.
The second line contains a sequence of n integers t_1, t_2, ..., t_{n} (|t_{i}| ≤ 10^9) — the sequence of temperature values. Numbers t_{i} are separated by single spaces.
-----Output-----
Print a single integer — the answer to the given task.
-----Examples-----
Input
4
-1 1 -2 1
Output
1
Input
5
0 -1 1 2 -5
Output
2
-----Note-----
Note to the first sample: there are two ways to change exactly one number so that the sequence met Vasya's condition. You can either replace the first number 1 by any negative number or replace the number -2 by any positive number.
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('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
n=int(sys.stdin.readline());
a=[int(x) for x in sys.stdin.readline().split()]
front=[0]*(len(a)+2)
for i in range(n):
front[i+1]=front[i]+ (1 if (a[i]>=0) else 0 )
back=[0]*(len(a)+2)
for i in range(n-1,-1,-1):
back[i+1]=back[i+2]+ (1 if (a[i]<=0) else 0)
ans=len(a)+1
for i in range(1,n):
ans=min(ans,front[i]+back[i+1])
print("%d"%ans)
``` | vfc_17138 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/234/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n-1 1 -2 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n0 -1 1 2 -5\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n0 0 0 0 0 0\n",
"output": "6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1847 | Solve the following coding problem using the programming language python:
The black king is standing on a chess field consisting of 10^9 rows and 10^9 columns. We will consider the rows of the field numbered with integers from 1 to 10^9 from top to bottom. The columns are similarly numbered with integers from 1 to 10^9 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).
You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers r_{i}, a_{i}, b_{i} (a_{i} ≤ b_{i}), denoting that cells in columns from number a_{i} to number b_{i} inclusive in the r_{i}-th row are allowed.
Your task is to find the minimum number of moves the king needs to get from square (x_0, y_0) to square (x_1, y_1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.
Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.
-----Input-----
The first line contains four space-separated integers x_0, y_0, x_1, y_1 (1 ≤ x_0, y_0, x_1, y_1 ≤ 10^9), denoting the initial and the final positions of the king.
The second line contains a single integer n (1 ≤ n ≤ 10^5), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers r_{i}, a_{i}, b_{i} (1 ≤ r_{i}, a_{i}, b_{i} ≤ 10^9, a_{i} ≤ b_{i}), denoting that cells in columns from number a_{i} to number b_{i} inclusive in the r_{i}-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily.
It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 10^5.
-----Output-----
If there is no path between the initial and final position along allowed cells, print -1.
Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.
-----Examples-----
Input
5 7 6 11
3
5 3 8
6 7 11
5 2 5
Output
4
Input
3 4 3 10
3
3 1 4
4 5 9
3 10 10
Output
6
Input
1 1 2 10
2
1 1 3
2 6 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
import sys
from collections import deque
def solve():
xadj, yadj = [0, 0, - 1, 1, -1, -1, 1, 1], [1, -1, 0, 0, -1, 1, -1, 1]
x0, y0, x1, y1, = rv()
n, = rv()
good = set()
visited = dict()
for seg in range(n):
r, a, b, = rv()
for c in range(a, b + 1): good.add((r, c))
points = deque()
points.append((x0, y0, 0))
visited[(x0, y0)] = 0
while len(points) > 0:
cur = points.popleft()
for i in range(8):
pos = (cur[0] + xadj[i], cur[1] + yadj[i])
if pos in good and pos not in visited:
points.append((pos[0], pos[1], cur[2] + 1))
visited[pos] = cur[2] + 1
print(visited[(x1, y1)] if (x1, y1) in visited else - 1)
def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
``` | vfc_17142 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/242/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 7 6 11\n3\n5 3 8\n6 7 11\n5 2 5\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 4 3 10\n3\n3 1 4\n4 5 9\n3 10 10\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 2 10\n2\n1 1 3\n2 6 10\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 8 7 8\n9\n10 6 6\n10 6 6\n7 7 8\n9 5 6\n8 9 9\n9 5 5\n9 8 8\n8 5 6\n9 10 10\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 15 7 15\n9\n6 15 15\n7 14 14\n6 15 15\n9 14 14\n7 14 16\n6 15 15\n6 15 15\n7 14 14\n8 15 15\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1848 | Solve the following coding problem using the programming language python:
There are n pictures delivered for the new exhibition. The i-th painting has beauty a_{i}. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.
We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1 ≤ i ≤ n - 1), such that a_{i} + 1 > a_{i}.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of painting.
The second line contains the sequence a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000), where a_{i} means the beauty of the i-th painting.
-----Output-----
Print one integer — the maximum possible number of neighbouring pairs, such that a_{i} + 1 > a_{i}, after the optimal rearrangement.
-----Examples-----
Input
5
20 30 10 50 40
Output
4
Input
4
200 100 100 200
Output
2
-----Note-----
In the first sample, the optimal order is: 10, 20, 30, 40, 50.
In the second sample, the optimal order is: 100, 200, 100, 200.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from collections import defaultdict
n = int(input())
A = [int(x) for x in input().split()]
D = defaultdict(int)
for a in A: D[a] += 1
S = set(D.keys())
ans = len(S) - 1
while S:
for k in D:
D[k] -= 1
if D[k] <= 0 and k in S:
S.remove(k)
ans += len(S) - 1
print(ans + 1)
``` | vfc_17146 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/651/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n20 30 10 50 40\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n200 100 100 200\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n2 2 2 2 2 2 2 2 2 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n444 333\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1849 | Solve the following coding problem using the programming language python:
You wrote down all integers from $0$ to $10^n - 1$, padding them with leading zeroes so their lengths are exactly $n$. For example, if $n = 3$ then you wrote out 000, 001, ..., 998, 999.
A block in an integer $x$ is a consecutive segment of equal digits that cannot be extended to the left or to the right.
For example, in the integer $00027734000$ there are three blocks of length $1$, one block of length $2$ and two blocks of length $3$.
For all integers $i$ from $1$ to $n$ count the number of blocks of length $i$ among the written down integers.
Since these integers may be too large, print them modulo $998244353$.
-----Input-----
The only line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$).
-----Output-----
In the only line print $n$ integers. The $i$-th integer is equal to the number of blocks of length $i$.
Since these integers may be too large, print them modulo $998244353$.
-----Examples-----
Input
1
Output
10
Input
2
Output
180 10
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
out = []
MOD = 998244353
for i in range(1, n + 1):
if i == n:
out.append(10)
else:
nex = 2 * 9 * pow(10, n - i - 1, MOD) * 10
if i < n - 1:
nex += (n - 1 - i) * 9 * 9 * pow(10, n - i - 2, MOD) * 10
out.append(nex % MOD)
print(' '.join(map(str,out)))
#print(sum((i + 1) * out[i] for i in range(n)))
#print(n * pow(10, n, MOD))
``` | vfc_17150 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1327/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "180 10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "2610 180 10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "34200 2610 180 10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1850 | Solve the following coding problem using the programming language python:
Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race.
Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race.
-----Input-----
The first line contains two integer numbers $N$ ($1 \leq N \leq 200000$) representing number of F1 astronauts, and current position of astronaut $D$ ($1 \leq D \leq N$) you want to calculate best ranking for (no other competitor will have the same number of points before the race).
The second line contains $N$ integer numbers $S_k$ ($0 \leq S_k \leq 10^8$, $k=1...N$), separated by a single space, representing current ranking of astronauts. Points are sorted in non-increasing order.
The third line contains $N$ integer numbers $P_k$ ($0 \leq P_k \leq 10^8$, $k=1...N$), separated by a single space, representing point awards for the next race. Points are sorted in non-increasing order, so winner of the race gets the maximum number of points.
-----Output-----
Output contains one integer number — the best possible ranking for astronaut after the race. If multiple astronauts have the same score after the race, they all share the best ranking.
-----Example-----
Input
4 3
50 30 20 10
15 10 7 3
Output
2
-----Note-----
If the third ranked astronaut wins the race, he will have 35 points. He cannot take the leading position, but he can overtake the second position if the second ranked astronaut finishes the race at the last position.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,p=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
r=a[p-1]+b[0]
cou=0
for i in range(p-1):
if a[i]+b[-1]<=r:
cou+=1;del b[-1]
print(p-cou)
``` | vfc_17154 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1046/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n50 30 20 10\n15 10 7 3\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4\n29 25 13 10\n20 9 3 0\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1851 | Solve the following coding problem using the programming language python:
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $i$-th page contains some mystery that will be explained on page $a_i$ ($a_i \ge i$).
Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page $i$ such that Ivan already has read it, but hasn't read page $a_i$). After that, he closes the book and continues to read it on the following day from the next page.
How many days will it take to read the whole book?
-----Input-----
The first line contains single integer $n$ ($1 \le n \le 10^4$) — the number of pages in the book.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($i \le a_i \le n$), where $a_i$ is the number of page which contains the explanation of the mystery on page $i$.
-----Output-----
Print one integer — the number of days it will take to read the whole book.
-----Example-----
Input
9
1 3 3 6 7 6 8 8 9
Output
4
-----Note-----
Explanation of the example test:
During the first day Ivan will read only the first page. During the second day Ivan will read pages number $2$ and $3$. During the third day — pages $4$-$8$. During the fourth (and the last) day Ivan will read remaining page number $9$.
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()))
maxi = 0
ans = 0
for i in range(n):
a[i] -= 1
maxi = max(maxi, a[i])
if maxi == i:
ans += 1
print(ans)
``` | vfc_17158 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1140/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "9\n1 3 3 6 7 6 8 8 9\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 3 4 5 5 6 7 8 9 10\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n4 9 4 10 6 8 9 8 9 10\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n",
"output": "15\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1853 | Solve the following coding problem using the programming language python:
Vasya had an array of $n$ integers, each element of the array was from $1$ to $n$. He chose $m$ pairs of different positions and wrote them down to a sheet of paper. Then Vasya compared the elements at these positions, and wrote down the results of the comparisons to another sheet of paper. For each pair he wrote either "greater", "less", or "equal".
After several years, he has found the first sheet of paper, but he couldn't find the second one. Also he doesn't remember the array he had. In particular, he doesn't remember if the array had equal elements. He has told this sad story to his informatics teacher Dr Helen.
She told him that it could be the case that even if Vasya finds his second sheet, he would still not be able to find out whether the array had two equal elements.
Now Vasya wants to find two arrays of integers, each of length $n$. All elements of the first array must be distinct, and there must be two equal elements in the second array. For each pair of positions Vasya wrote at the first sheet of paper, the result of the comparison must be the same for the corresponding elements of the first array, and the corresponding elements of the second array.
Help Vasya find two such arrays of length $n$, or find out that there are no such arrays for his sets of pairs.
-----Input-----
The first line of input contains two integers $n$, $m$ — the number of elements in the array and number of comparisons made by Vasya ($1 \le n \le 100\,000$, $0 \le m \le 100\,000$).
Each of the following $m$ lines contains two integers $a_i$, $b_i$ — the positions of the $i$-th comparison ($1 \le a_i, b_i \le n$; $a_i \ne b_i$). It's guaranteed that any unordered pair is given in the input at most once.
-----Output-----
The first line of output must contain "YES" if there exist two arrays, such that the results of comparisons would be the same, and all numbers in the first one are distinct, and the second one contains two equal numbers. Otherwise it must contain "NO".
If the arrays exist, the second line must contain the array of distinct integers, the third line must contain the array, that contains at least one pair of equal elements. Elements of the arrays must be integers from $1$ to $n$.
-----Examples-----
Input
1 0
Output
NO
Input
3 1
1 2
Output
YES
1 3 2
1 3 1
Input
4 3
1 2
1 3
2 4
Output
YES
1 3 4 2
1 3 4 1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m= list(map(int, input().split()))
s=set()
for i in range(m):
x,y=list(map(int, input().split()))
s.add((x,y))
if m*2 == n*(n-1) or n<2 or n==2 and m==1:
print('NO')
return
x, y = 0,0
for i in range(1,n+1):
for j in range(i+1,n+1):
if (i, j) not in s and (j, i) not in s:
x=i
y=j
break
x-=1
y-=1
print('YES')
l = list(range(1,n+1))
if x == 1:
y,x=x,y
if y == 0:
x, y=y,x
l[x], l[0] = 1, l[x]
l[y], l[1] = 2, l[y]
print(*l)
l[y]=1
print(*l)
``` | vfc_17166 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1090/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 0\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1\n1 2\n",
"output": "YES\n1 3 2 \n1 3 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3\n1 2\n1 3\n2 4\n",
"output": "YES\n1 3 4 2 \n1 3 4 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 0\n",
"output": "YES\n1 2 \n1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n2 1\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1854 | Solve the following coding problem using the programming language python:
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of $n$ integers $a_1, a_2, \dots, a_n$ construct a connected undirected graph of $n$ vertices such that: the graph contains no self-loops and no multiple edges; the degree $d_i$ of the $i$-th vertex doesn't exceed $a_i$ (i.e. $d_i \le a_i$); the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
-----Input-----
The first line contains a single integer $n$ ($3 \le n \le 500$) — the number of vertices in the graph.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n - 1$) — the upper limits to vertex degrees.
-----Output-----
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer $m$ — the number of edges in the resulting graph.
The $i$-th of the next $m$ lines should contain two integers $v_i, u_i$ ($1 \le v_i, u_i \le n$, $v_i \neq u_i$) — the description of the $i$-th edge. The graph should contain no multiple edges — for each pair $(x, y)$ you output, you should output no more pairs $(x, y)$ or $(y, x)$.
-----Examples-----
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
-----Note-----
Here are the graphs for the first two example cases. Both have diameter of $2$. [Image] $d_1 = 1 \le a_1 = 2$
$d_2 = 2 \le a_2 = 2$
$d_3 = 1 \le a_3 = 2$ [Image] $d_1 = 1 \le a_1 = 1$
$d_2 = 4 \le a_2 = 4$
$d_3 = 1 \le a_3 = 1$
$d_4 = 1 \le a_4 = 1$
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n=int(input())
l=[int(c) for c in input().split()]
ll=[]
res=[]
head=0
dia=0
for i in range(1,n):
if l[i]==1:
l[i]=0
ll.append(i)
else:
res.append((head+1,i+1))
l[head]-=1
dia+=1
head=i
l[head]-=1
if l[head]>0 and len(ll)>0:
res.append((ll[0]+1,head+1))
l[head]-=1
del(ll[0])
dia+=1
if l[0]>0 and len(ll)>0:
res.append((ll[0]+1,1))
l[0]-=1
del(ll[0])
dia+=1
for i in ll:
for j in range(n):
if l[j]>0:
res.append((j+1,i+1))
l[j]-=1
break
if len(res)<n-1:
print("NO")
else:
print("YES "+str(dia))
print(n-1)
for p in res:
print(p[0],end =" ")
print(p[1])
``` | vfc_17170 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1082/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 2 2\n",
"output": "YES 2\n2\n1 2\n2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 4 1 1 1\n",
"output": "YES 2\n4\n5 2\n2 4\n2 3\n2 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 1 1\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 1 2\n",
"output": "YES 2\n2\n2 3\n3 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2 1 2 1\n",
"output": "YES 3\n3\n4 1\n1 3\n3 2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1855 | Solve the following coding problem using the programming language python:
You are given a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$ and an integer $k$, such that $1 \leq k \leq n$. A permutation means that every number from $1$ to $n$ is contained in $p$ exactly once.
Let's consider all partitions of this permutation into $k$ disjoint segments. Formally, a partition is a set of segments $\{[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\}$, such that:
$1 \leq l_i \leq r_i \leq n$ for all $1 \leq i \leq k$; For all $1 \leq j \leq n$ there exists exactly one segment $[l_i, r_i]$, such that $l_i \leq j \leq r_i$.
Two partitions are different if there exists a segment that lies in one partition but not the other.
Let's calculate the partition value, defined as $\sum\limits_{i=1}^{k} {\max\limits_{l_i \leq j \leq r_i} {p_j}}$, for all possible partitions of the permutation into $k$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $998\,244\,353$.
-----Input-----
The first line contains two integers, $n$ and $k$ ($1 \leq k \leq n \leq 200\,000$) — the size of the given permutation and the number of segments in a partition.
The second line contains $n$ different integers $p_1, p_2, \ldots, p_n$ ($1 \leq p_i \leq n$) — the given permutation.
-----Output-----
Print two integers — the maximum possible partition value over all partitions of the permutation into $k$ disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo $998\,244\,353$.
Please note that you should only find the second value modulo $998\,244\,353$.
-----Examples-----
Input
3 2
2 1 3
Output
5 2
Input
5 5
2 1 5 3 4
Output
15 1
Input
7 3
2 7 3 1 5 4 6
Output
18 6
-----Note-----
In the first test, for $k = 2$, there exists only two valid partitions: $\{[1, 1], [2, 3]\}$ and $\{[1, 2], [3, 3]\}$. For each partition, the partition value is equal to $2 + 3 = 5$. So, the maximum possible value is $5$ and the number of partitions is $2$.
In the third test, for $k = 3$, the partitions with the maximum possible partition value are $\{[1, 2], [3, 5], [6, 7]\}$, $\{[1, 3], [4, 5], [6, 7]\}$, $\{[1, 4], [5, 5], [6, 7]\}$, $\{[1, 2], [3, 6], [7, 7]\}$, $\{[1, 3], [4, 6], [7, 7]\}$, $\{[1, 4], [5, 6], [7, 7]\}$. For all of them, the partition value is equal to $7 + 5 + 6 = 18$.
The partition $\{[1, 2], [3, 4], [5, 7]\}$, however, has the partition value $7 + 3 + 6 = 16$. This is not the maximum possible value, so we don't count it.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,k=map(int,input().split())
L=list(map(int,input().split()))
ind=[]
for i in range(n):
if L[i]>n-k:ind.append(i)
m=1
for i in range(len(ind)-1):
m*=(ind[i+1]-ind[i])
m%=998244353
print(((n*(n+1)//2)-((n-k)*((n-k)+1))//2),m)
``` | vfc_17174 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1326/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n2 1 3\n",
"output": "5 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n2 1 5 3 4\n",
"output": "15 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 3\n2 7 3 1 5 4 6\n",
"output": "18 6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1\n",
"output": "1 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n1 2\n",
"output": "2 1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1856 | Solve the following coding problem using the programming language python:
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $n$ passwords — strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $a$ and $b$ as follows: two passwords $a$ and $b$ are equivalent if there is a letter, that exists in both $a$ and $b$; two passwords $a$ and $b$ are equivalent if there is a password $c$ from the list, which is equivalent to both $a$ and $b$.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
-----Input-----
The first line contain integer $n$ ($1 \le n \le 2 \cdot 10^5$) — number of passwords in the list. Next $n$ lines contains passwords from the list – non-empty strings $s_i$, with length at most $50$ letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed $10^6$ letters. All of them consist only of lowercase Latin letters.
-----Output-----
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
-----Examples-----
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
-----Note-----
In the second example hacker need to use any of the passwords to access the system.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
input = sys.stdin.readline
n = int(input())
def MakeSet(x):
x.parent = x
x.rank = 0
def Union(x, y):
xRoot = Find(x)
yRoot = Find(y)
if xRoot.rank > yRoot.rank:
yRoot.parent = xRoot
elif xRoot.rank < yRoot.rank:
xRoot.parent = yRoot
elif xRoot != yRoot:
yRoot.parent = xRoot
xRoot.rank = xRoot.rank + 1
def Find(x):
if x.parent == x:
return x
else:
x.parent = Find(x.parent)
return x.parent
class Node:
def __init__ (self, label):
self.label = label
def __str__(self):
return self.label
used = [0] * 26
nodes = [Node(ch) for ch in range(26)]
[MakeSet(node) for node in nodes]
for _ in range(n):
s = input().strip()
prev = -1
for c in s:
val = ord(c) - 97
used[val] = 1
if prev != -1:
Union(nodes[prev], nodes[val])
prev = val
outs = [0] * 26
for node in nodes:
outs[Find(node).label] += 1
count = 0
for val in outs:
if val != 0:
count += 1
print(count + sum(used) - 26)
``` | vfc_17178 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1263/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\na\nb\nab\nd\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nab\nbc\nabc\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\ncodeforces\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\nyyyyyyyyyyyyyyyyyyyyyyyyyyy\nxxxxxx\nzz\nzzzzzzzzzzz\nzzzzzzzzzz\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\nff\nsssssssssssssssssssssss\nwwwwwww\nxxxxxxxx\n",
"output": "5",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\nuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu\nxdxxdxxddxdxdxxdddxdddxxxddx\npyfpffffyyfppyfffpypp\nzzzzzzzzzzzzzzzzzzzzzzzz\nzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\n",
"output": "4",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1857 | Solve the following coding problem using the programming language python:
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n^2 intersections.
The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Obviously this requirement is satisfied by the following scheme: each bench is placed on a cross of paths and each path contains not more than one bench.
Help the park administration count the number of ways to place the benches.
-----Input-----
The only line of the input contains one integer n (5 ≤ n ≤ 100) — the number of east to west paths and north to south paths.
-----Output-----
Output one integer — the number of ways to place the benches.
-----Examples-----
Input
5
Output
120
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((n*(n-1)*(n-2)*(n-3)*(n-4))**2//120)
``` | vfc_17182 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/H",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n",
"output": "120",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n",
"output": "4320",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n",
"output": "52920",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1858 | Solve the following coding problem using the programming language python:
Find out if it is possible to partition the first $n$ positive integers into two non-empty disjoint sets $S_1$ and $S_2$ such that:$\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1$
Here $\mathrm{sum}(S)$ denotes the sum of all elements present in set $S$ and $\mathrm{gcd}$ means thegreatest common divisor.
Every integer number from $1$ to $n$ should be present in exactly one of $S_1$ or $S_2$.
-----Input-----
The only line of the input contains a single integer $n$ ($1 \le n \le 45\,000$)
-----Output-----
If such partition doesn't exist, print "No" (quotes for clarity).
Otherwise, print "Yes" (quotes for clarity), followed by two lines, describing $S_1$ and $S_2$ respectively.
Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty.
If there are multiple possible partitions — print any of them.
-----Examples-----
Input
1
Output
No
Input
3
Output
Yes
1 2
2 1 3
-----Note-----
In the first example, there is no way to partition a single number into two non-empty sets, hence the answer is "No".
In the second example, the sums of the sets are $2$ and $4$ respectively. The $\mathrm{gcd}(2, 4) = 2 > 1$, hence that is one of the possible answers.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
if n <= 2:
print("No")
else:
print("Yes")
print(1, (n + 1) // 2)
ans = []
for i in range(1, n + 1):
if i != (n + 1) // 2:
ans.append(i)
print(n - 1, *ans)
``` | vfc_17186 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1038/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n",
"output": "No",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "Yes\n1 2\n2 1 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n",
"output": "Yes\n1 5\n9 1 2 3 4 6 7 8 9 10 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9\n",
"output": "Yes\n1 5\n8 1 2 3 4 6 7 8 9 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1859 | Solve the following coding problem using the programming language python:
You are given an integer number $n$. The following algorithm is applied to it:
if $n = 0$, then end algorithm; find the smallest prime divisor $d$ of $n$; subtract $d$ from $n$ and go to step $1$.
Determine the number of subtrations the algorithm will make.
-----Input-----
The only line contains a single integer $n$ ($2 \le n \le 10^{10}$).
-----Output-----
Print a single integer — the number of subtractions the algorithm will make.
-----Examples-----
Input
5
Output
1
Input
4
Output
2
-----Note-----
In the first example $5$ is the smallest prime divisor, thus it gets subtracted right away to make a $0$.
In the second example $2$ is the smallest prime divisor at both steps.
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)
if N%2==0:
print(N//2)
return
for i in range(2,110000):
if N%i==0:
print( (N-i)//2 +1)
return
print(1)
``` | vfc_17190 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1076/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10000000000\n",
"output": "5000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9999999999\n",
"output": "4999999999\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "473\n",
"output": "232\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1860 | Solve the following coding problem using the programming language python:
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
-----Input-----
The only line of input contains one integer n (1 ≤ n ≤ 55) — the maximum length of a number that a door-plate can hold.
-----Output-----
Output one integer — the maximum number of offices, than can have unique lucky numbers not longer than n digits.
-----Examples-----
Input
2
Output
6
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(2**(n+1) - 2)
``` | vfc_17194 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n",
"output": "6",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "14",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "62",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "12\n",
"output": "8190",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "34\n",
"output": "34359738366",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1861 | Solve the following coding problem using the programming language python:
Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.
[Image]
Polina came up with a new game called "Hyperset". In her game, there are $n$ cards with $k$ features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with $k = 4$.
Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.
Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.
-----Input-----
The first line of each test contains two integers $n$ and $k$ ($1 \le n \le 1500$, $1 \le k \le 30$) — number of cards and number of features.
Each of the following $n$ lines contains a card description: a string consisting of $k$ letters "S", "E", "T". The $i$-th character of this string decribes the $i$-th feature of that card. All cards are distinct.
-----Output-----
Output a single integer — the number of ways to choose three cards that form a set.
-----Examples-----
Input
3 3
SET
ETS
TSE
Output
1
Input
3 4
SETE
ETSE
TSES
Output
0
Input
5 4
SETT
TEST
EEET
ESTE
STES
Output
2
-----Note-----
In the third example test, these two triples of cards are sets: "SETT", "TEST", "EEET" "TEST", "ESTE", "STES"
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def gen(a, b):
gener = ''
for i in range(k):
if a[i] == b[i]:
gener += a[i]
else:
if 'S' not in (a[i], b[i]):
gener += 'S'
elif 'E' not in (a[i], b[i]):
gener += 'E'
else:
gener += 'T'
return gener
n, k = list(map(int, input().split()))
cards = []
diff = set()
for i in range(n):
s = input()
cards.append(s)
diff.add(s)
ans = 0
was = set()
for i in range(n):
for j in range(i + 1, n):
aaa = gen(cards[i], cards[j])
if aaa in diff and max(cards[i], cards[j], aaa) + min(cards[i], cards[j], aaa) not in was:
ans += 1
was.add(max(cards[i], cards[j], aaa) + min(cards[i], cards[j], aaa))
print(ans)
``` | vfc_17198 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1287/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3\nSET\nETS\nTSE\n",
"output": "1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1862 | Solve the following coding problem using the programming language python:
Andryusha is an orderly boy and likes to keep things in their place.
Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.
Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?
-----Input-----
The first line contains the single integer n (1 ≤ n ≤ 10^5) — the number of sock pairs.
The second line contains 2n integers x_1, x_2, ..., x_2n (1 ≤ x_{i} ≤ n), which describe the order in which Andryusha took the socks from the bag. More precisely, x_{i} means that the i-th sock Andryusha took out was from pair x_{i}.
It is guaranteed that Andryusha took exactly two socks of each pair.
-----Output-----
Print single integer — the maximum number of socks that were on the table at the same time.
-----Examples-----
Input
1
1 1
Output
1
Input
3
2 1 1 3 2 3
Output
2
-----Note-----
In the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.
In the second example Andryusha behaved as follows: Initially the table was empty, he took out a sock from pair 2 and put it on the table. Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table. Socks (1, 2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe. Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table. Socks (2, 3) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe. Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe. Thus, at most two socks were on the table at the same time.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
read = lambda: map(int, input().split())
n = int(input())
a = list(read())
was = [0] * (n + 1)
bal = ans = 0
for i in a:
if was[i]:
bal -= 1
else:
bal += 1
was[i] = 1
ans = max(ans, bal)
print(ans)
``` | vfc_17202 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/780/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n1 1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1863 | Solve the following coding problem using the programming language python:
The Bitlandians are quite weird people. They have very peculiar customs.
As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.
The kids are excited because just as is customary, they're going to be paid for the job!
Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.
Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.
Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^6) — the number of eggs.
Next n lines contain two integers a_{i} and g_{i} each (0 ≤ a_{i}, g_{i} ≤ 1000; a_{i} + g_{i} = 1000): a_{i} is the price said by A. for the i-th egg and g_{i} is the price said by G. for the i-th egg.
-----Output-----
If it is impossible to assign the painting, print "-1" (without quotes).
Otherwise print a string, consisting of n letters "G" and "A". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as S_{a}, and the money Uncle J. must pay G. for the painting as S_{g}, then this inequality must hold: |S_{a} - S_{g}| ≤ 500.
If there are several solutions, you are allowed to print any of them.
-----Examples-----
Input
2
1 999
999 1
Output
AG
Input
3
400 600
400 600
400 600
Output
AGA
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
n=int(sys.stdin.readline())
A=[]
B=[]
diff=0
Ans=""
for i in range(n):
x,y=list(map(int,sys.stdin.readline().split()))
if(diff+x<=500):
diff+=x
Ans+="A"
else:
diff-=y
Ans+="G"
if(abs(diff)<=500):
sys.stdout.write(Ans)
else:
print(-1)
``` | vfc_17206 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/282/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 999\n999 1\n",
"output": "AG\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n400 600\n400 600\n400 600\n",
"output": "AGA\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n500 500\n500 500\n",
"output": "AG\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 999\n",
"output": "A\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 999\n1 999\n1 999\n1 999\n1 999\n1 999\n1 999\n1 999\n1 999\n1 999\n",
"output": "AAAAAAAAAA\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n499 501\n501 499\n",
"output": "AG\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1864 | Solve the following coding problem using the programming language python:
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
-----Input-----
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion.
The second line contains n distinct space-separated numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the values of the banknotes.
-----Output-----
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
-----Examples-----
Input
5
1 2 3 4 5
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
#fin = open("input.txt", 'r')
#fout = open("output.txt", 'w')
#fin = open("input.txt", 'r')
#fout = open("output.txt", 'w')
n = int(input())
a = list(map(int, input().split()))
if 1 not in a:
print(1)
else:
print(-1)
``` | vfc_17210 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/560/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 3 4 5\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1865 | Solve the following coding problem using the programming language python:
In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.
Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a_0, a_1, ..., a_{n} - 1 ( - 10^9 ≤ a_{i} ≤ 10^9), where a_{i} is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once.
-----Output-----
In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements a_{i} and a_{j}. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times.
If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.
-----Examples-----
Input
5
5 2 5 1 4
Output
2
0 3
4 2
Input
6
10 20 20 40 60 60
Output
0
Input
2
101 100
Output
1
0 1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import operator
n = int(input())
xs = list(map(int, str.split(input())))
if xs == sorted(xs):
print(0)
else:
swaps = []
counter = 0
while xs:
i = xs.index(min(xs))
if i:
swaps.append(str.format("{} {}", counter, i + counter))
xs[0], xs[i] = xs[i], xs[0]
xs.pop(0)
counter += 1
print(len(swaps))
print(str.join("\n", swaps))
``` | vfc_17214 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/489/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n5 2 5 1 4\n",
"output": "2\n0 3\n4 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n10 20 20 40 60 60\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n101 100\n",
"output": "1\n0 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1000000000 -1000000000\n",
"output": "1\n0 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n5 2 6 8 3 1 6 8\n",
"output": "4\n0 5\n4 2\n5 3\n6 5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1866 | Solve the following coding problem using the programming language python:
You are given an integer $n$.
You should find a list of pairs $(x_1, y_1)$, $(x_2, y_2)$, ..., $(x_q, y_q)$ ($1 \leq x_i, y_i \leq n$) satisfying the following condition.
Let's consider some function $f: \mathbb{N} \times \mathbb{N} \to \mathbb{N}$ (we define $\mathbb{N}$ as the set of positive integers). In other words, $f$ is a function that returns a positive integer for a pair of positive integers.
Let's make an array $a_1, a_2, \ldots, a_n$, where $a_i = i$ initially.
You will perform $q$ operations, in $i$-th of them you will: assign $t = f(a_{x_i}, a_{y_i})$ ($t$ is a temporary variable, it is used only for the next two assignments); assign $a_{x_i} = t$; assign $a_{y_i} = t$.
In other words, you need to simultaneously change $a_{x_i}$ and $a_{y_i}$ to $f(a_{x_i}, a_{y_i})$. Note that during this process $f(p, q)$ is always the same for a fixed pair of $p$ and $q$.
In the end, there should be at most two different numbers in the array $a$.
It should be true for any function $f$.
Find any possible list of pairs. The number of pairs should not exceed $5 \cdot 10^5$.
-----Input-----
The single line contains a single integer $n$ ($1 \leq n \leq 15\,000$).
-----Output-----
In the first line print $q$ ($0 \leq q \leq 5 \cdot 10^5$) — the number of pairs.
In each of the next $q$ lines print two integers. In the $i$-th line print $x_i$, $y_i$ ($1 \leq x_i, y_i \leq n$).
The condition described in the statement should be satisfied.
If there exists multiple answers you can print any of them.
-----Examples-----
Input
3
Output
1
1 2
Input
4
Output
2
1 2
3 4
-----Note-----
In the first example, after performing the only operation the array $a$ will be $[f(a_1, a_2), f(a_1, a_2), a_3]$. It will always have at most two different numbers.
In the second example, after performing two operations the array $a$ will be $[f(a_1, a_2), f(a_1, a_2), f(a_3, a_4), f(a_3, a_4)]$. It will always have at most two different numbers.
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())
out = []
def p(a,b,d):
out.append(str(a + 1 + d) + ' ' + str(b+1+d))
p2 = 1
while 2 * p2 <= n:
p2 *= 2
for d in (0, n - p2):
bit = 1
while bit < p2:
for i in range(p2):
if i ^ bit > i:
p(i, i ^ bit, d)
bit *= 2
print(len(out))
print('\n'.join(out))
``` | vfc_17218 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1408/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n",
"output": "2\n1 2\n2 3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1867 | Solve the following coding problem using the programming language python:
Amr has got a large array of size n. Amr doesn't like large arrays so he intends to make it smaller.
Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array.
Help Amr by choosing the smallest subsegment possible.
-----Input-----
The first line contains one number n (1 ≤ n ≤ 10^5), the size of the array.
The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6), representing elements of the array.
-----Output-----
Output two integers l, r (1 ≤ l ≤ r ≤ n), the beginning and the end of the subsegment chosen respectively.
If there are several possible answers you may output any of them.
-----Examples-----
Input
5
1 1 2 2 1
Output
1 5
Input
5
1 2 2 3 1
Output
2 3
Input
6
1 2 2 1 1 2
Output
1 5
-----Note-----
A subsegment B of an array A from l to r is an array of size r - l + 1 where B_{i} = A_{l} + i - 1 for all 1 ≤ i ≤ r - l + 1
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 = int(input())
As = list(map(int, input().split()))
def solve(n, As):
counter = collections.Counter(As)
candidates = []
prev_freq = 0
for num, freq in counter.most_common():
if prev_freq and prev_freq!= freq:
break
candidates.append(num)
prev_freq = freq
lr = {cand:[] for cand in candidates}
for i, a in enumerate(As, 1):
if a in lr:
lr[a].append(i)
minspan = float('inf')
for pos in list(lr.values()):
if pos[-1] - pos[0] < minspan:
minspan = pos[-1] - pos[0]
LR = (pos[0], pos[-1])
return LR
print(*solve(n, As))
``` | vfc_17222 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/558/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 1 2 2 1\n",
"output": "1 5",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 2 2 3 1\n",
"output": "2 3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n1 2 2 1 1 2\n",
"output": "1 5",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1000000 2 1000000 3 2 1000000 1 2 1\n",
"output": "2 7",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 2 3 4 5 5 1 2 3 4\n",
"output": "5 6",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1868 | Solve the following coding problem using the programming language python:
Consider some set of distinct characters $A$ and some string $S$, consisting of exactly $n$ characters, where each character is present in $A$.
You are given an array of $m$ integers $b$ ($b_1 < b_2 < \dots < b_m$).
You are allowed to perform the following move on the string $S$:
Choose some valid $i$ and set $k = b_i$; Take the first $k$ characters of $S = Pr_k$; Take the last $k$ characters of $S = Su_k$; Substitute the first $k$ characters of $S$ with the reversed $Su_k$; Substitute the last $k$ characters of $S$ with the reversed $Pr_k$.
For example, let's take a look at $S =$ "abcdefghi" and $k = 2$. $Pr_2 =$ "ab", $Su_2 =$ "hi". Reversed $Pr_2 =$ "ba", $Su_2 =$ "ih". Thus, the resulting $S$ is "ihcdefgba".
The move can be performed arbitrary number of times (possibly zero). Any $i$ can be selected multiple times over these moves.
Let's call some strings $S$ and $T$ equal if and only if there exists such a sequence of moves to transmute string $S$ to string $T$. For the above example strings "abcdefghi" and "ihcdefgba" are equal. Also note that this implies $S = S$.
The task is simple. Count the number of distinct strings.
The answer can be huge enough, so calculate it modulo $998244353$.
-----Input-----
The first line contains three integers $n$, $m$ and $|A|$ ($2 \le n \le 10^9$, $1 \le m \le min(\frac n 2, 2 \cdot 10^5)$, $1 \le |A| \le 10^9$) — the length of the strings, the size of the array $b$ and the size of the set $A$, respectively.
The second line contains $m$ integers $b_1, b_2, \dots, b_m$ ($1 \le b_i \le \frac n 2$, $b_1 < b_2 < \dots < b_m$).
-----Output-----
Print a single integer — the number of distinct strings of length $n$ with characters from set $A$ modulo $998244353$.
-----Examples-----
Input
3 1 2
1
Output
6
Input
9 2 26
2 3
Output
150352234
Input
12 3 1
2 5 6
Output
1
-----Note-----
Here are all the distinct strings for the first example. The chosen letters 'a' and 'b' are there just to show that the characters in $A$ are different.
"aaa" "aab" = "baa" "aba" "abb" = "bba" "bab" "bbb"
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,m,a=map(int,input().split())
b=list(map(int,input().split()))
for i in range(m):
if i==0:
diffs=[b[0]]
else:
diffs.append(b[i]-b[i-1])
powers=[a%998244353]
for i in range(30):
powers.append(powers[-1]**2%998244353)
def power(x,y,binpowers):
prod=1
bits=bin(y)[2:]
bits=bits[::-1]
for i in range(len(bits)):
if bits[i]=="1":
prod*=binpowers[i]
prod%=998244353
return prod
maxi=b[-1]
prod1=power(a,n-2*maxi,powers)
for guy in diffs:
newprod=power(a,guy,powers)
newprod=(newprod*(newprod+1))//2
newprod%=998244353
prod1*=newprod
prod1%=998244353
print(prod1)
``` | vfc_17226 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1065/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 1 2\n1\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 2 26\n2 3\n",
"output": "150352234\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "12 3 1\n2 5 6\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1 1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1869 | Solve the following coding problem using the programming language python:
You have a multiset containing several integers. Initially, it contains $a_1$ elements equal to $1$, $a_2$ elements equal to $2$, ..., $a_n$ elements equal to $n$.
You may apply two types of operations: choose two integers $l$ and $r$ ($l \le r$), then remove one occurrence of $l$, one occurrence of $l + 1$, ..., one occurrence of $r$ from the multiset. This operation can be applied only if each number from $l$ to $r$ occurs at least once in the multiset; choose two integers $i$ and $x$ ($x \ge 1$), then remove $x$ occurrences of $i$ from the multiset. This operation can be applied only if the multiset contains at least $x$ occurrences of $i$.
What is the minimum number of operations required to delete all elements from the multiset?
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 5000$).
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$).
-----Output-----
Print one integer — the minimum number of operations required to delete all elements from the multiset.
-----Examples-----
Input
4
1 4 1 1
Output
2
Input
5
1 0 1 0 1
Output
3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from sys import stdin
n = int(stdin.readline())
a = list(map(int,stdin.readline().split()))
a = [0] + a
ans = n
dp = [float("inf")] * (n+1)
dp[0] = 0
for i in range(1,n+1):
nmin = float("inf")
for j in range(i-1,-1,-1):
if a[j] <= nmin:
dp[i] = min(dp[i] , dp[j] + max(0,a[i]-a[j]) + (i-j-1) )
nmin = min(nmin,a[j])
#print (dp)
for i in range(n+1):
ans = min(ans , dp[i] + n-i)
print (ans)
``` | vfc_17230 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1400/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1 4 1 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 0 1 0 1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000000\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n3 3 3 3\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n3 3 2 3\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1870 | Solve the following coding problem using the programming language python:
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear!
More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then everything on the screen disappears and after that the word you have typed appears on the screen.
For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.
You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
-----Input-----
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 10^9) — the number of words ZS the Coder typed and the crazy computer delay respectively.
The next line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_1 < t_2 < ... < t_{n} ≤ 10^9), where t_{i} denotes the second when ZS the Coder typed the i-th word.
-----Output-----
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second t_{n}.
-----Examples-----
Input
6 5
1 3 8 14 19 20
Output
3
Input
6 1
1 3 5 7 9 10
Output
2
-----Note-----
The first sample is already explained in the problem statement.
For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 > 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
read = lambda: list(map(int, input().split()))
n, c = read()
t = list(read())
cnt = 1
for i in range(1, n):
if t[i] - t[i - 1] > c:
cnt = 1
else:
cnt += 1
print(cnt)
``` | vfc_17234 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/716/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 5\n1 3 8 14 19 20\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 1\n1 3 5 7 9 10\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1000000000\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n1 7 12 13 14\n",
"output": "4",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1871 | Solve the following coding problem using the programming language python:
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the i^{th} subject has c_{i} chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.
Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.
You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.
Please be careful that answer might not fit in 32 bit data type.
-----Input-----
The first line will contain two space separated integers n, x (1 ≤ n, x ≤ 10^5). The next line will contain n space separated integers: c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^5).
-----Output-----
Output a single integer representing the answer to the problem.
-----Examples-----
Input
2 3
4 1
Output
11
Input
4 2
5 1 2 1
Output
10
Input
3 3
1 1 1
Output
6
-----Note-----
Look at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2 × 1 = 2 hours. Hence you will need to spend 12 + 2 = 14 hours.
Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3 × 1 = 3 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2 × 4 = 8 hours. Hence you will need to spend 11 hours.
So overall, minimum of both the cases is 11 hours.
Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Codeforces Round 251 Div 2 Problem B
Author : chaotic_iak
Language: Python 3.3.4
"""
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0:
return inputs
if mode == 1:
return inputs.split()
if mode == 2:
return [int(x) for x in inputs.split()]
def write(s="\n"):
if isinstance(s, list): s = " ".join(s)
s = str(s)
print(s, end="")
################################################### SOLUTION
n,x = read()
c = read()
c.sort()
print(sum(max(x-i,1)*c[i] for i in range(n)))
``` | vfc_17238 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/439/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3\n4 1\n",
"output": "11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2\n5 1 2 1\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n1 1 1\n",
"output": "6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1872 | Solve the following coding problem using the programming language python:
It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.
A "star" figure having n ≥ 5 corners where n is a prime number is constructed the following way. On the circle of radius r n points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts. [Image]
-----Input-----
The only line of the input contains two integers n (5 ≤ n < 10^9, n is prime) and r (1 ≤ r ≤ 10^9) — the number of the star corners and the radius of the circumcircle correspondingly.
-----Output-----
Output one number — the star area. The relative error of your answer should not be greater than 10^{ - 7}.
-----Examples-----
Input
7 10
Output
108.395919545675
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 sin, cos, pi
n, r = map(int, input().split())
print(n * r**2 * sin(pi / n) * cos(pi * (n // 2) / n) / cos(pi * (n // 2 - 1) / n))
``` | vfc_17242 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/P",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 10\n",
"output": "108.395919545675",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 1\n",
"output": "1.122569941449",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 1000\n",
"output": "1083959.195456745256",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1873 | Solve the following coding problem using the programming language python:
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres.
In the bookshop, Jack decides to buy two books of different genres.
Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.
The books are given by indices of their genres. The genres are numbered from 1 to m.
-----Input-----
The first line contains two positive integers n and m (2 ≤ n ≤ 2·10^5, 2 ≤ m ≤ 10) — the number of books in the bookstore and the number of genres.
The second line contains a sequence a_1, a_2, ..., a_{n}, where a_{i} (1 ≤ a_{i} ≤ m) equals the genre of the i-th book.
It is guaranteed that for each genre there is at least one book of that genre.
-----Output-----
Print the only integer — the number of ways in which Jack can choose books.
It is guaranteed that the answer doesn't exceed the value 2·10^9.
-----Examples-----
Input
4 3
2 1 3 1
Output
5
Input
7 4
4 2 3 1 2 4 3
Output
18
-----Note-----
The answer to the first test sample equals 5 as Sasha can choose: the first and second books, the first and third books, the first and fourth books, the second and third books, the third and fourth books.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a, b = map(int, input().split(' '))
l = list(map(int, input().split(' ')))
stot = 0
ssq = 0
for i in range(1, b+1):
stot += l.count(i)
ssq += (l.count(i)**2)
print(int((stot**2 - ssq)/2))
``` | vfc_17246 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/609/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n2 1 3 1\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 4\n4 2 3 1 2 4 3\n",
"output": "18\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n1 2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n1 2 2\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1874 | Solve the following coding problem using the programming language python:
IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.
The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length. [Image]
-----Input-----
The only line of the input contains three integers l_3, l_4, l_5 (1 ≤ l_3, l_4, l_5 ≤ 1000) — the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.
-----Output-----
Output one number — the total volume of the pyramids. Absolute or relative error should not be greater than 10^{ - 9}.
-----Examples-----
Input
2 5 3
Output
38.546168065709
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from math import sqrt
a, b, c = list(map(int, input().split()))
# a, b, c = 2, 5, 3
V1 = a ** 3 * sqrt(2) / 12
V2 = sqrt(2) * (b ** 3) / 6
V3 = ((5 + sqrt(5)) / 24) * (c ** 3)
print(V1 + V2 + V3)
``` | vfc_17250 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/Q",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 5 3\n",
"output": "38.546168065709",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 4 5\n",
"output": "55.954779230131",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n",
"output": "0.655056222989",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000 1000 1000\n",
"output": "655056222.989098310000",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "999 997 998\n",
"output": "650782658.915145640000",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1876 | Solve the following coding problem using the programming language python:
You are given a tree (a connected undirected graph without cycles) of $n$ vertices. Each of the $n - 1$ edges of the tree is colored in either black or red.
You are also given an integer $k$. Consider sequences of $k$ vertices. Let's call a sequence $[a_1, a_2, \ldots, a_k]$ good if it satisfies the following criterion: We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from $a_1$ and ending at $a_k$. Start at $a_1$, then go to $a_2$ using the shortest path between $a_1$ and $a_2$, then go to $a_3$ in a similar way, and so on, until you travel the shortest path between $a_{k-1}$ and $a_k$. If you walked over at least one black edge during this process, then the sequence is good. [Image]
Consider the tree on the picture. If $k=3$ then the following sequences are good: $[1, 4, 7]$, $[5, 5, 3]$ and $[2, 3, 7]$. The following sequences are not good: $[1, 4, 6]$, $[5, 5, 5]$, $[3, 7, 3]$.
There are $n^k$ sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo $10^9+7$.
-----Input-----
The first line contains two integers $n$ and $k$ ($2 \le n \le 10^5$, $2 \le k \le 100$), the size of the tree and the length of the vertex sequence.
Each of the next $n - 1$ lines contains three integers $u_i$, $v_i$ and $x_i$ ($1 \le u_i, v_i \le n$, $x_i \in \{0, 1\}$), where $u_i$ and $v_i$ denote the endpoints of the corresponding edge and $x_i$ is the color of this edge ($0$ denotes red edge and $1$ denotes black edge).
-----Output-----
Print the number of good sequences modulo $10^9 + 7$.
-----Examples-----
Input
4 4
1 2 1
2 3 1
3 4 1
Output
252
Input
4 6
1 2 0
1 3 0
1 4 0
Output
0
Input
3 5
1 2 1
2 3 0
Output
210
-----Note-----
In the first example, all sequences ($4^4$) of length $4$ except the following are good: $[1, 1, 1, 1]$ $[2, 2, 2, 2]$ $[3, 3, 3, 3]$ $[4, 4, 4, 4]$
In the second example, all edges are red, hence there aren't any good sequences.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
rr = lambda: input().strip()
rri = lambda: int(rr())
rrm = lambda: list(map(int, rr().split()))
MOD = 10**9 + 7
class DSU:
def __init__(self, N):
#R * C is the source, and isn't a grid square
self.par = list(range(N+1))
self.rnk = [0] * (N+1)
self.sz = [1] * (N+1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def solve(N, K, edges):
graph = [[] for _ in range(N)]
dsu = DSU(N)
for u,v,w in edges:
u-=1;v-=1
if w==0: #red
dsu.union(u, v)
ans = pow(N, K, MOD)
for x in range(N):
if dsu.find(x) == x:
ans -= pow(dsu.size(x), K, MOD)
ans %= MOD
return ans
for tc in range(1):#rri()):
N, K = rrm()
edges = [rrm() for _ in range(N-1)]
print(solve(N, K, edges))
``` | vfc_17258 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1139/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 4\n1 2 1\n2 3 1\n3 4 1\n",
"output": "252",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 6\n1 2 0\n1 3 0\n1 4 0\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 5\n1 2 1\n2 3 0\n",
"output": "210",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "13 3\n9 13 1\n8 3 1\n11 9 0\n8 13 0\n10 9 0\n2 7 0\n4 8 1\n11 5 0\n10 12 0\n12 1 1\n5 7 0\n6 8 1\n",
"output": "1842",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 19\n2 4 1\n2 3 0\n1 4 0\n",
"output": "876856450",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 12\n4 5 0\n2 7 1\n7 6 1\n2 5 0\n2 3 0\n1 6 0\n",
"output": "824505797",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1878 | Solve the following coding problem using the programming language python:
Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right.
In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100) — the number of rectangles.
Each of the following n lines contains four integers x_1, y_1, x_2, y_2 (1 ≤ x_1 ≤ x_2 ≤ 100, 1 ≤ y_1 ≤ y_2 ≤ 100), where x_1 and y_1 are the number of the column and row of the lower left cell and x_2 and y_2 are the number of the column and row of the upper right cell of a rectangle.
-----Output-----
In a single line print the sum of all values in the cells of the table.
-----Examples-----
Input
2
1 1 2 3
2 2 3 3
Output
10
Input
2
1 1 3 3
1 1 3 3
Output
18
-----Note-----
Note to the first sample test:
Values of the table in the first three rows and columns will be as follows:
121
121
110
So, the sum of values will be equal to 10.
Note to the second sample test:
Values of the table in the first three rows and columns will be as follows:
222
222
222
So, the sum of values will be equal to 18.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
r = 0
for i in range(n):
a = list(map(int, input().split(' ')))
r += (a[2] - a[0] + 1) * (a[3] - a[1] + 1)
print(r)
``` | vfc_17266 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/552/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 1 2 3\n2 2 3 3\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1 3 3\n1 1 3 3\n",
"output": "18\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n4 11 20 15\n7 5 12 20\n10 8 16 12\n7 5 12 15\n2 2 20 13\n",
"output": "510\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n4 11 20 20\n6 11 20 16\n5 2 19 15\n11 3 18 15\n3 2 14 11\n",
"output": "694\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 1 1 100\n1 1 1 100\n1 1 1 100\n1 1 1 100\n1 1 1 100\n",
"output": "500\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1879 | Solve the following coding problem using the programming language python:
The polar bears are going fishing. They plan to sail from (s_{x}, s_{y}) to (e_{x}, e_{y}). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y). If the wind blows to the east, the boat will move to (x + 1, y). If the wind blows to the south, the boat will move to (x, y - 1). If the wind blows to the west, the boat will move to (x - 1, y). If the wind blows to the north, the boat will move to (x, y + 1).
Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (e_{x}, e_{y})?
-----Input-----
The first line contains five integers t, s_{x}, s_{y}, e_{x}, e_{y} (1 ≤ t ≤ 10^5, - 10^9 ≤ s_{x}, s_{y}, e_{x}, e_{y} ≤ 10^9). The starting location and the ending location will be different.
The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).
-----Output-----
If they can reach (e_{x}, e_{y}) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).
-----Examples-----
Input
5 0 0 1 1
SESNW
Output
4
Input
10 5 3 3 6
NENSWESNEE
Output
-1
-----Note-----
In the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.
In the second sample, they cannot sail to the destination.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t, sx, sy, ex, ey = map(int, input().split())
d = {'W':max(0, sx - ex), 'E':max(0, ex - sx), 'N':max(0, ey - sy), 'S':max(0, sy - ey)}
for (i, c) in enumerate(input(), 1):
if d[c] > 0:
d[c] -= 1
if any(d.values()) == False:
print(i)
break
else:
print(-1)
``` | vfc_17270 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/298/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 0 0 1 1\nSESNW\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 5 3 3 6\nNENSWESNEE\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "19 -172106364 -468680119 -172106365 -468680119\nSSEEESSSESESWSEESSS\n",
"output": "13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "39 -1000000000 -1000000000 -999999997 -1000000000\nENEENWSWSSWESNSSEESNSESWSWNSWESNENWNWEE\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "41 -264908123 -86993764 -264908123 -86993723\nNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN\n",
"output": "41\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1880 | Solve the following coding problem using the programming language python:
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.
A young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose — to show the developer the imperfection of their protection.
The found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of 12345 should lead to 13542. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number 12345 is 455 422 043 125 550 171 232. The answer is the 5 last digits of this result. For the number 12345 the answer should be 71232.
Vasya is going to write a keygen program implementing this algorithm. Can you do the same?
-----Input-----
The only line of the input contains a positive integer five digit number for which the activation code should be found.
-----Output-----
Output exactly 5 digits without spaces between them — the found activation code of the program.
-----Examples-----
Input
12345
Output
71232
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = input()
x = int(s[0] + s[2] + s[4] + s[3] + s[1])
print(str(x**5)[-5:])
``` | vfc_17274 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/L",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "12345\n",
"output": "71232",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "13542\n",
"output": "84443",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "71232\n",
"output": "10151",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11111\n",
"output": "36551",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1881 | Solve the following coding problem using the programming language python:
Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.
Their algorithm will be tested on an array of integers, where the $i$-th integer represents the color of the $i$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).
To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $k$, and each color should belong to exactly one group.
Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.
To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $k$ to the right.
[Image]
To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.
-----Input-----
The first line of input contains two integers $n$ and $k$ ($1 \leq n \leq 10^5$, $1 \leq k \leq 256$), the number of pixels in the image, and the maximum size of a group, respectively.
The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($0 \leq p_i \leq 255$), where $p_i$ is the color of the $i$-th pixel.
-----Output-----
Print $n$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.
-----Examples-----
Input
4 3
2 14 3 4
Output
0 12 3 3
Input
5 2
0 2 1 255 254
Output
0 1 1 254 254
-----Note-----
One possible way to group colors and assign keys for the first sample:
Color $2$ belongs to the group $[0,2]$, with group key $0$.
Color $14$ belongs to the group $[12,14]$, with group key $12$.
Colors $3$ and $4$ belong to group $[3, 5]$, with group key $3$.
Other groups won't affect the result so they are not listed here.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def getIntList():
return list(map(int, input().split()));
n, k = getIntList();
p=getIntList();
choosed=[False]*256;
left=[i for i in range(256)];
for i, x in enumerate(p):
if not choosed[x]:
best=x;
#print(x-1, max(-1, x-k));
for j in range(x-1, max(-1, x-k), -1):
#print('try ',j)
if not choosed[j]:
best=j;
else:
if x-left[j]<k:
best=left[j];
break;
#print('best=',best)
for j in range(best, x+1):
choosed[j]=True;
left[j]=best;
p[i]=left[x];
print(' '.join(map(str, p)));
``` | vfc_17278 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/980/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n2 14 3 4\n",
"output": "0 12 3 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n0 2 1 255 254\n",
"output": "0 1 1 254 254\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1882 | Solve the following coding problem using the programming language python:
You are preparing for an exam on scheduling theory. The exam will last for exactly T milliseconds and will consist of n problems. You can either solve problem i in exactly t_{i} milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either.
Unfortunately, your teacher considers some of the problems too easy for you. Thus, he assigned an integer a_{i} to every problem i meaning that the problem i can bring you a point to the final score only in case you have solved no more than a_{i} problems overall (including problem i).
Formally, suppose you solve problems p_1, p_2, ..., p_{k} during the exam. Then, your final score s will be equal to the number of values of j between 1 and k such that k ≤ a_{p}_{j}.
You have guessed that the real first problem of the exam is already in front of you. Therefore, you want to choose a set of problems to solve during the exam maximizing your final score in advance. Don't forget that the exam is limited in time, and you must have enough time to solve all chosen problems. If there exist different sets of problems leading to the maximum final score, any of them will do.
-----Input-----
The first line contains two integers n and T (1 ≤ n ≤ 2·10^5; 1 ≤ T ≤ 10^9) — the number of problems in the exam and the length of the exam in milliseconds, respectively.
Each of the next n lines contains two integers a_{i} and t_{i} (1 ≤ a_{i} ≤ n; 1 ≤ t_{i} ≤ 10^4). The problems are numbered from 1 to n.
-----Output-----
In the first line, output a single integer s — your maximum possible final score.
In the second line, output a single integer k (0 ≤ k ≤ n) — the number of problems you should solve.
In the third line, output k distinct integers p_1, p_2, ..., p_{k} (1 ≤ p_{i} ≤ n) — the indexes of problems you should solve, in any order.
If there are several optimal sets of problems, you may output any of them.
-----Examples-----
Input
5 300
3 100
4 150
4 80
2 90
2 300
Output
2
3
3 1 4
Input
2 100
1 787
2 788
Output
0
0
Input
2 100
2 42
2 58
Output
2
2
1 2
-----Note-----
In the first example, you should solve problems 3, 1, and 4. In this case you'll spend 80 + 100 + 90 = 270 milliseconds, falling within the length of the exam, 300 milliseconds (and even leaving yourself 30 milliseconds to have a rest). Problems 3 and 1 will bring you a point each, while problem 4 won't. You'll score two points.
In the second example, the length of the exam is catastrophically not enough to solve even a single problem.
In the third example, you have just enough time to solve both problems in 42 + 58 = 100 milliseconds and hand your solutions to the teacher with a smile.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 8 10:20:50 2018
@author: yanni
"""
#import random
n, T = [int(x) for x in input().split()]
#n, T = [100000,10000*10000]
prob = []
vals = [set() for stuff in range(n+2)]
for i in range(n):
a, t = [int(x) for x in input().split()]
#a = random.randint(1,n)
#t = random.randint(1, 10000)
prob.append((i+1,a,t))
prob.sort(key = lambda tup: tup[2])
currindex = 0
maxindex = -1
solve = set()
mem = set()
timeleft = T
target = 1
for currindex in range(n):
i, a, t = prob[currindex]
if (timeleft < t):
break
if (timeleft >= t and a >= target):
vals[a].add(currindex)
solve.add(currindex)
timeleft -= t
if (len(solve) == target):
maxindex = currindex
#print(target)
for p in vals[target]:
solve.remove(p)
timeleft += prob[p][2]
target += 1
bestsolve = solve | vals[target-1]
solvelist = [x for x in bestsolve if x<=maxindex]
target = len(solvelist)
print(target)
print(target)
for p in solvelist:
print(prob[p][0], end=" ")
print()
``` | vfc_17282 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/913/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 300\n3 100\n4 150\n4 80\n2 90\n2 300\n",
"output": "2\n2\n3 4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1883 | Solve the following coding problem using the programming language python:
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v_1, v_2, ..., v_{k} (k ≥ 1) and meet the following conditions: Objects with numbers v_1, v_2, ..., v_{k} - 1 are mountains and the object with number v_{k} is the hotel. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object v_{i}. This track goes to object v_{i} + 1. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5) — the number of objects.
The second line contains n space-separated integers type_1, type_2, ..., type_{n} — the types of the objects. If type_{i} equals zero, then the i-th object is the mountain. If type_{i} equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ n) — the description of the ski tracks. If number a_{i} equals zero, then there is no such object v, that has a ski track built from v to i. If number a_{i} doesn't equal zero, that means that there is a track built from object a_{i} to object i.
-----Output-----
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v_1, v_2, ..., v_{k} — the path. If there are multiple solutions, you can print any of them.
-----Examples-----
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
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
def Z(s):
return int(s)-1
n=int(sys.stdin.readline())
Hotels=[False]*(n)
Rep=[0]*(n+1)
Chains=[]
Type=list(map(int,sys.stdin.readline().split()))
for i in range(n):
if(Type[i]==1):
Hotels[i]=True
A=list(map(Z,sys.stdin.readline().split()))
for item in A:
Rep[item]+=1
for i in range(n):
if(Hotels[i]):
Chains.append([i])
x=A[i]
if(x==-1):
continue
while(A[x]!=-1 and Rep[x]<=1):
Chains[-1].append(x)
x=A[x]
if(Rep[x]<=1):
Chains[-1].append(x)
if(n==1):
print(1)
print(1)
else:
X=max(Chains,key=len)
sys.stdout.write(str(len(X))+"\n")
sys.stdout.write(str(X[-1]+1))
for i in range(len(X)-2,-1,-1):
sys.stdout.write(" "+str(X[i]+1))
``` | vfc_17286 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/350/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n0 0 0 0 1\n0 1 2 3 4\n",
"output": "5\n1 2 3 4 5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n0 0 1 0 1\n0 1 2 2 4\n",
"output": "2\n4 5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 0 0 0\n2 3 4 2\n",
"output": "1\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n0 0 0 0 0 0 0 0 0 1\n4 0 8 4 7 8 5 5 7 2\n",
"output": "2\n2 10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50\n0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 1 0 0 0 1 0\n28 4 33 22 4 35 36 31 42 25 50 33 25 36 18 23 23 28 43 3 18 31 1 2 15 22 40 43 29 32 28 35 18 27 48 40 14 36 27 50 40 5 48 14 36 24 32 33 26 50\n",
"output": "2\n3 20\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0\n86 12 47 46 45 31 20 47 58 79 23 70 35 72 37 20 16 64 46 87 57 7 84 72 70 3 14 40 17 42 30 99 12 20 38 98 14 40 4 83 10 15 47 30 83 58 12 7 97 46 17 6 41 13 87 37 36 12 7 25 26 35 69 13 18 5 9 53 72 28 13 51 5 57 14 64 28 25 91 96 57 69 9 12 97 7 56 42 31 15 88 16 41 88 86 13 89 81 3 42\n",
"output": "1\n44\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1884 | Solve the following coding problem using the programming language python:
One department of some software company has $n$ servers of different specifications. Servers are indexed with consecutive integers from $1$ to $n$. Suppose that the specifications of the $j$-th server may be expressed with a single integer number $c_j$ of artificial resource units.
In order for production to work, it is needed to deploy two services $S_1$ and $S_2$ to process incoming requests using the servers of the department. Processing of incoming requests of service $S_i$ takes $x_i$ resource units.
The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $S_i$ is deployed using $k_i$ servers, then the load is divided equally between these servers and each server requires only $x_i / k_i$ (that may be a fractional number) resource units.
Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.
Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.
-----Input-----
The first line contains three integers $n$, $x_1$, $x_2$ ($2 \leq n \leq 300\,000$, $1 \leq x_1, x_2 \leq 10^9$) — the number of servers that the department may use, and resource units requirements for each of the services.
The second line contains $n$ space-separated integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 10^9$) — the number of resource units provided by each of the servers.
-----Output-----
If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes).
Otherwise print the word "Yes" (without the quotes).
In the second line print two integers $k_1$ and $k_2$ ($1 \leq k_1, k_2 \leq n$) — the number of servers used for each of the services.
In the third line print $k_1$ integers, the indices of the servers that will be used for the first service.
In the fourth line print $k_2$ integers, the indices of the servers that will be used for the second service.
No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them.
-----Examples-----
Input
6 8 16
3 5 2 9 8 7
Output
Yes
3 2
1 2 6
5 4
Input
4 20 32
21 11 11 12
Output
Yes
1 3
1
2 3 4
Input
4 11 32
5 5 16 16
Output
No
Input
5 12 20
7 8 4 11 9
Output
No
-----Note-----
In the first sample test each of the servers 1, 2 and 6 will will provide $8 / 3 = 2.(6)$ resource units and each of the servers 5, 4 will provide $16 / 2 = 8$ resource units.
In the second sample test the first server will provide $20$ resource units and each of the remaining servers will provide $32 / 3 = 10.(6)$ resource units.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# python3
def readline(): return tuple(map(int, input().split()))
def ceil_div(num, den): return (num - 1) // den + 1
def main():
n, x1, x2 = readline()
c = readline()
xx = (x1, x2)
servers = sorted(enumerate(c, start=1), key=lambda p: p[1])
for (i, a) in enumerate(servers):
for (j, x) in enumerate(xx):
kj = ceil_div(x, a[1])
if i + kj < n and (n - i - kj) * servers[i + kj][1] >= sum(xx) - x:
print("Yes")
l1 = servers[i:i+kj]
l2 = servers[i+kj:]
if j: l1, l2 = l2, l1
print(len(l1), len(l2))
print(" ".join(str(d[0]) for d in l1))
print(" ".join(str(d[0]) for d in l2))
return
print("No")
main()
# Made By Mostafa_Khaled
``` | vfc_17290 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/925/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 8 16\n3 5 2 9 8 7\n",
"output": "Yes\n4 2\n3 1 2 6\n5 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 20 32\n21 11 11 12\n",
"output": "Yes\n1 3\n1\n2 3 4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1885 | Solve the following coding problem using the programming language python:
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
-----Input-----
The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.
-----Output-----
Output one integer — the number of different variants of group composition.
-----Examples-----
Input
7
Output
29
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
ans = 0
ans = ans + (n * (n-1) * (n-2) * (n-3) * (n-4)) // (2*3*4*5)
ans = ans + (n * (n-1) * (n-2) * (n-3) * (n-4) * (n-5)) // (2*3*4*5*6)
ans = ans + (n * (n-1) * (n-2) * (n-3) * (n-4) * (n-5) * (n-6)) // (2*3*4*5*6*7)
print(ans)
``` | vfc_17294 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\n",
"output": "29",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n",
"output": "92",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9\n",
"output": "246",
"type": "stdin_stdout"
}
]
} |
Subsets and Splits