source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (*r*,<=*c*) the cell located at the row *r* and at the column *c*.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (*r*,<=*c*) will go to the cell (*r*<=-<=1,<=*c*), while moving down means the pawn located in (*r*,<=*c*) will go to the cell (*r*<=+<=1,<=*c*). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
|
```python
import sys
#sys.stdin = open("input.txt")
#sys.stdout = open("output.txt", "w")
tbl = []
for i in range(8):
tbl.append(input())
bestW = 10
bestB = 10
#print(tbl)
for i in range(8):
for j in range(8):
#print(i, j)
if tbl[i][j] == 'W':
ok = True
for k in range(i):
if tbl[k][j] != '.':
ok = False
if ok:
bestW = min(bestW, i)
elif tbl[i][j] == 'B':
ok = True
for k in range(8-i-1):
if tbl[i + k + 1][j] != '.':
ok = False
if ok:
bestB = min(bestB, 8 - i - 1)
#print(bestW, bestB)
if bestW <= bestB:
print('A')
else:
print('B')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
n = int(input())
array = []
for x in range(0,n):
lister = input().split()
array.append(lister)
sum1=0
sum2=0
sum3=0
for x in range(0,len(array)):
sum1 = sum1 + int(array[x][0])
sum2 = sum2 + int(array[x][1])
sum3 = sum3 + int(array[x][2])
if sum1 == 0 and sum2 == 0 and sum3 == 0:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are *n* mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.
|
```python
#mounds = int(input())
#m = list(range(1,mounds+1))
#m1 = [1]
#m.remove(1)
#for i in range(1,len(m)+1):
# if i%2==1:
# m1.append(max(m))
# m.remove(max(m))
# else:
# m1.append(min(m))
# m.remove(min(m))
#print(' '.join(map(str,m1)))
#
mounds = int(input())
if mounds == 1:
print(1)
quit()
o = 2
h = mounds//2
t = mounds
m = [1]
for i in range(0,mounds//2+1):
if t > h:
m.append(t)
t-=1
if o <= h:
m.append(o)
o+=1
print(' '.join(map(str,m)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Anton likes to play chess, and so does his friend Danik.
Once they have played *n* games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
|
```python
while True:
n=int(input())
ch=input()
s=0
f=0
for i in range (len(ch)):
if ch[i]=="A":
s=s+1
if ch[i]=="D":
f=f+1
if f+s==n and 1<=n<=100000:
break
if s>f:
print("Anton")
elif s<f:
print("Danik")
else:
print("Friendship")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*.
For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program that will perform the *k*-rounding of *n*.
|
```python
from fractions import gcd
n, k = map (int, input ().split ())
print (n * (10 ** k) // gcd(n, 10 ** k))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus has an array, consisting of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:
- he chooses two elements of the array *a**i*, *a**j* (*i*<=≠<=*j*); - he simultaneously increases number *a**i* by 1 and decreases number *a**j* by 1, that is, executes *a**i*<==<=*a**i*<=+<=1 and *a**j*<==<=*a**j*<=-<=1.
The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times.
Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
|
```python
i=int(input())
l=list(map(int,input().split()))
if sum(l)%i==0:
print(i)
else:
print(i-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
x = input()
c = input()
k = len(x)
v = len(c)
flag = 'YES'
if k != v:
flag = 'NO'
else:
for i in range(k):
if x[i] != c[k - 1 - i]:
flag = 'NO'
print(flag)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.
A substring $s[l \ldots r]$ ($1<=\leq<=l<=\leq<=r<=\leq<=|s|$) of a string $s<==<=s_{1}s_{2} \ldots s_{|s|}$ is the string $s_{l}s_{l<=+<=1} \ldots s_{r}$.
Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word $s$ is changed into its longest substring that is not a palindrome. If all the substrings of $s$ are palindromes, she skips the word at all.
Some time ago Ann read the word $s$. What is the word she changed it into?
|
```python
s = input()
if s!=s[:: -1]:
maximo = len(s)
elif len(set(s))<2:
maximo = 0
else: maximo = len(s)-1
print(maximo)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a non-empty string *s* consisting of lowercase English letters. You have to pick exactly one non-empty substring of *s* and shift all its letters 'z' 'y' 'x' 'b' 'a' 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.
What is the lexicographically minimum string that can be obtained from *s* by performing this shift exactly once?
|
```python
str1 = input()
str2 = ''
for i in range(len(str1)):
if str1[i] != 'a':
str2 += chr(ord(str1[i]) - 1)
else:
str2 += 'z'
print(str2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team.
At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), *s* and *t*. You need to transform word *s* into word *t*". The task looked simple to the guys because they know the suffix data structures well. Bizon Senior loves suffix automaton. By applying it once to a string, he can remove from this string any single character. Bizon Middle knows suffix array well. By applying it once to a string, he can swap any two characters of this string. The guys do not know anything about the suffix tree, but it can help them do much more.
Bizon the Champion wonders whether the "Bizons" can solve the problem. Perhaps, the solution do not require both data structures. Find out whether the guys can solve the problem and if they can, how do they do it? Can they solve it either only with use of suffix automaton or only with use of suffix array or they need both structures? Note that any structure may be used an unlimited number of times, the structures may be used in any order.
|
```python
from collections import Counter
s = input()
t = input()
T = Counter(t)
S = Counter(s)
yes = True
for i in T.items():
key, val = i[0], i[1]
if(S[key] < val):
yes = False
if(yes):
# array -> just a permutation
ok = True
for i in S.items():
key, val = i[0], i[1]
if(T[key] != S[key]):
ok = False
if(ok):
print("array")
else:
if(t in s):
print("automaton")
else:
print("both")
else:
print("need tree")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Andrew and Eugene are playing a game. Initially, Andrew has string *s*, consisting of digits. Eugene sends Andrew multiple queries of type "*d**i*<=→<=*t**i*", that means "replace all digits *d**i* in string *s* with substrings equal to *t**i*". For example, if *s*<==<=123123, then query "2<=→<=00" transforms *s* to 10031003, and query "3<=→<=" ("replace 3 by an empty string") transforms it to *s*<==<=1212. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to *s* by 1000000007 (109<=+<=7). When you represent *s* as a decimal number, please ignore the leading zeroes; also if *s* is an empty string, then it's assumed that the number equals to zero.
Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!
|
```python
n = input()
k = int(input())
for i in range(k):
s = input().split('->')
n = n.replace(s[0], s[1])
print(int(n) % 1000000007)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
str = input()
up=0
for i in str:
if i.isupper():
up += 1
if up>len(str):
str=str.upper()
else:
str=str.lower()
print(str)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string *s* consisting of *n* lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
|
```python
t = int(input())
t = input()
i = 0
while i < len(t)-2:
if t[i] == "o" and t[i+1] == "g" and t[i+2] == "o":
j = i+3
t = t[:i] + "***" + t[i+3:]
while j < len(t)-1:
if t[j] + t[j+1] == "go":
t = t[:j] + "**" + t[j+2:]
else:
break
i = j
continue
else:
i = i + 1
print(t)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these *n* colors. Adding the *j*-th color to the *i*-th picture takes the *j*-th painter *t**ij* units of time.
Order is important everywhere, so the painters' work is ordered by the following rules:
- Each picture is first painted by the first painter, then by the second one, and so on. That is, after the *j*-th painter finishes working on the picture, it must go to the (*j*<=+<=1)-th painter (if *j*<=<<=*n*); - each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; - each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; - as soon as the *j*-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter.
Given that the painters start working at time 0, find for each picture the time when it is ready for sale.
|
```python
m,n=map(int,input().split())
L=[]
for i in range(m):
l=list(map(int,input().split()))
L.append(l)
ans=[0 for i in range(m)]
for i in range(n):
free=0
for j in range(m):
start=max(free,ans[j])
ans[j]=start+L[j][i]
free=ans[j]
for i in range(m):
print(ans[i],end=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
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).
|
```python
n = int(input())
cou = 0
for i in range(n):
x = input()
if '--' in x:
cou -= 1
else:
cou += 1
print(cou)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and *k*.
|
```python
n=int(input())
if n%2==0:
print(n//2,'\n'+'2 '*(n//2))
else:
print(n//2)
print(3,'2 '*(n//2-1))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the *expose* procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)
Given integers *l*, *r* and *k*, you need to print all powers of number *k* within range from *l* to *r* inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
|
```python
l, r, k = map (int, input().split())
cnt = 0
for i in range (64) :
p = pow (k, i)
if p >= l and p <= r :
cnt += 1
print (p, end = ' ');
if p >= r :
break;
if cnt == 0 :
print (-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a *d*1 meter long road between his house and the first shop and a *d*2 meter long road between his house and the second shop. Also, there is a road of length *d*3 directly connecting these two shops to each other. Help Patrick calculate the minimum distance that he needs to walk in order to go to both shops and return to his house.
Patrick always starts at his house. He should visit both shops moving only along the three existing roads and return back to his house. He doesn't mind visiting the same shop or passing the same road multiple times. The only goal is to minimize the total distance traveled.
|
```python
d1, d2, d3 = map(int, input().split())
first = (d1 * 2) + (d2 * 2)
second = d1 + d3 + d2
third = d3 + d2 + d3 + d2
print(min(first, second, third))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.
Amr has *n* instruments, it takes *a**i* days to learn *i*-th instrument. Being busy, Amr dedicated *k* days to learn how to play the maximum possible number of instruments.
Amr asked for your help to distribute his free days between instruments so that he can achieve his goal.
|
```python
n,k = map(int, input().split())
arr = sorted(list(zip(range(n), (map(int, input().split())))), key = lambda x: x[1])
ans = []
i = 0
while k-arr[i][1] >=0:
k-=arr[i][1]
ans.append(arr[i][0]+1)
i+=1
if i == n:
break
print(len(ans))
print(*ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day shooshuns found a sequence of *n* integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:
1. Find the number that goes *k*-th in the current sequence and add the same number to the end of the sequence; 1. Delete the first number of the current sequence.
The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
|
```python
#!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, k = readln()
a = readln()
if len(set(a[k - 1:])) == 1:
ans = 0
i = k - 1
while i >= 0 and a[i] == a[k - 1]:
i -= 1
ans += 1
print(ans)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least *i* is found so that name*i* does not yet exist in the database.
|
```python
n = int(input())
usernames = {}
for _ in range(n):
name = input()
if name in usernames:
prompt_num = usernames[name] + 1
prompt_name = f"{name}{prompt_num}"
usernames[name] = prompt_num
print(prompt_name)
else:
usernames[name] = 0
print("OK" )
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.
|
```python
n,q=list(map(int,input().split()))
k=list(map(int,input().split()))
p= list(dict.fromkeys(k))
u=""
for x in p:
for t in k:
if x==t:
u+=str(k.index(x))
break
list=[]
j=0
my=""
for i in u:
j=int(i)+1
list.append(j)
if len(p)==q:
print("YES")
my= ' '.join(map(str, list))
print(my)
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
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](https://en.wikipedia.org/wiki/Seven-segment_display)).
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.
|
```python
def f(x):
return 49*int(x)*10**(int(x)-1)
def g(y):
segs=[6,2,5,5,4,5,6,3,7,6]
return sum(segs[1:int(y)])
def h(z):
segs=[6,2,5,5,4,5,6,3,7,6]
return segs[int(z)]
def u(aa,bb):
if len(aa)-1==bb:
return -1
else:
return int(aa[bb+1:len(aa)])
def seg_sum(n):
j=len(n)-1
total=h(0)
for i in range(0,len(n)):
x_i = int(n[i])
total+=x_i*f(j-i)+g(x_i)*10**(j-i)+h(x_i)*(1+u(n,i))
if n[j] != '0':
total+=h(n[j])
return int(total)
def runner():
[a,b]=input().split()
if a == '0':
print(seg_sum(b))
else:
print(seg_sum(str(int(b)))-seg_sum(str(int(a)-1)))
runner()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day *n* friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together.
Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the *i*-th of them occupies the rectangle of width *w**i* pixels and height *h**i* pixels. On the group photo everybody stands in a line, thus the minimum pixel size of the photo including all the photographed friends, is *W*<=×<=*H*, where *W* is the total sum of all widths and *H* is the maximum height of all the photographed friends.
As is usually the case, the friends made *n* photos — the *j*-th (1<=≤<=*j*<=≤<=*n*) photo had everybody except for the *j*-th friend as he was the photographer.
Print the minimum size of each made photo in pixels.
|
```python
n = int(input())
width = []
heigth = []
sumw = 0
h1, h2 = 0, 0
for i in range(n):
w, h = map(int, input().split())
width.append(w)
heigth.append(h)
sumw += w
if h > h1:
h2 = h1
h1 = h
elif h > h2:
h2 = h
for i in range(n):
if heigth[i] != h1:
print((sumw - width[i]) * h1, end=' ')
else:
print((sumw - width[i]) * h2, end=' ')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
x=y=z = 0
for x in range(int(input())):
x1,y1,z1= map(int,input().split())
x+=x1
y+=y1
z+=z1
if x==y==z ==0:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has *n* rooms in total. At the moment the *i*-th room has *p**i* people living in it and the room can accommodate *q**i* people in total (*p**i*<=≤<=*q**i*). Your task is to count how many rooms has free place for both George and Alex.
|
```python
t=input()
h=0
while int(t)>0:
t=int(t)-1
x,y=input().split()
if int(y)-int(x)>=2:
h=int(h)+1
print(int(h))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed *x* in the absolute value.
Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found *n* of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?
You can assume that initially Vanya had infinitely many cards with each integer number from <=-<=*x* to *x*.
|
```python
import math
m,n=map(int,input().split())
l=list(map(int,input().split()))
print(math.ceil(abs(sum(l))/n))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
str1=str(input())
cap=0
smol=0
for i in str1:
if ord(i)>=65 and ord(i)<=96:
cap+=1
else:
smol+=1
if smol<cap:
print(str1.upper())
else:
print(str1.lower())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.
This contest offers *n* problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.
|
```python
t = int(input())
ans = 0
for x in range(1, t+1):
u = list(map(int, input().split()))
sum = u[0]+u[1]+u[2]
if sum >= 2 :
ans = ans+1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
|
```python
from math import *
a,b=[int(x) for x in input().split()]
res1,res2,res3=0,0,0
if a==b:
print(0,6,0)
else:
if (a+b)%2==0:
res2=1
else:
res2=0
for i in range(1,7):
if int(fabs(a-i))<int(fabs(b-i)):
res1+=1
print(res1,res2,6-res1-res2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in.
There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously.
For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are *k* such guards in the castle, so if there are more than *k* opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed.
Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than *k* doors were opened.
|
```python
def solution(n,k,g):
s = set(g)
prefix =[0]*(n)
for a in s :
for i in range(g.find(a),g.rfind(a)+1):
prefix[i]+=1
if max(prefix) > k :
return 'YES'
else:
return "NO"
if __name__ == "__main__":
n,k = map(int,input().split())
g = input()
print(solution(n,k,g))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
n, m, a = [input() for _ in range(3)]
n += n%a
m += m%a
n = n // a
m = m // a
print(n*m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
|
```python
# 1 - Import library
import pygame
from pygame.locals import *
# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
# 3 - Load images
player = pygame.image.load("resources/images/dude.png")
# 4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the screen elements
screen.blit(player, (100,100))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's denote a function
You are given an array *a* consisting of *n* integers. You have to calculate the sum of *d*(*a**i*,<=*a**j*) over all pairs (*i*,<=*j*) such that 1<=≤<=*i*<=≤<=*j*<=≤<=*n*.
|
```python
n = int(input())
a = list(map(int, input().split()))
ans = 0
mm = dict((a[i], 0) for i in range(n))
for i in range(n):
ans += a[i] * (i - (n - 1 - i))
mm[a[i]] += 1
ans -= mm.get(a[i] - 1, 0)
ans += mm.get(a[i] + 1, 0)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, *x**i* is the coordinate of the *i*-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.
You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.
Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.
|
```python
n = int(input())
word = input()
numbers = [int(i) for i in input().split()]
if word.count("R")==0:
print(-1)
else:
pos = word.find("R")
flag = False
minimum = 10**9
while pos!=-1:
if pos+1>=len(word):
break
if word[pos+1]!="L":
pos = word.find("R",pos+1)
else:
if (numbers[pos+1]-numbers[pos])/2<minimum:
minimum = (numbers[pos+1]-numbers[pos])/2
flag = True
pos = word.find("R",pos+1)
if pos+1==len(word)-1:
break
if flag:
print(int(minimum))
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than *k* millimeters.
The library has *n* volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is *h**i*. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.
|
```python
import sys
from array import array # noqa: F401
def input(): return sys.stdin.buffer.readline().decode('utf-8')
class BIT_MIN(object):
__slots__ = ['nodes', 'size']
def __init__(self, size: int):
self.nodes = [10**7]*(size+1)
self.size = size+1
def update(self, index: int, value: int):
while index < self.size:
if self.nodes[index] > value:
self.nodes[index] = value
index += index & -index
def get(self, right: int):
result = 10**7
while right:
if result > self.nodes[right]:
result = self.nodes[right]
right -= right & -right
return result
class BIT_MAX(object):
__slots__ = ['nodes', 'size']
def __init__(self, size: int):
self.nodes = [0]*(size+1)
self.size = size+1
def update(self, index: int, value: int):
while index < self.size:
if self.nodes[index] < value:
self.nodes[index] = value
index += index & -index
def get(self, right: int):
result = 0
while right:
if result < self.nodes[right]:
result = self.nodes[right]
right -= right & -right
return result
n, k = map(int, input().split())
h = tuple(map(int, input().split()))
min_h, max_h = BIT_MIN(n+10), BIT_MAX(n+10)
ans_a, ans_b = 0, []
for i, x in enumerate(h):
min_h.update(n-i, x)
max_h.update(n-i, x)
ok, ng = n-i, n+1
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
if max_h.get(mid) - min_h.get(mid) <= k:
ok = mid
else:
ng = mid
j = n-ok
if i - j + 1 > ans_a:
ans_a = i-j+1
ans_b = [str(j+1) + ' ' + str(i+1)]
else:
ans_b.append(str(j+1) + ' ' + str(i+1))
ans = str(ans_a) + ' ' + str(len(ans_b)) + '\n' + '\n'.join(ans_b)
sys.stdout.buffer.write(ans.encode('utf-8'))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
At regular competition Vladik and Valera won *a* and *b* candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.
More formally, the guys take turns giving each other one candy more than they received in the previous turn.
This continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they don’t consider as their own. You need to know, who is the first who can’t give the right amount of candy.
|
```python
a = list(map(int, input().split()))
d, i = 1, 0
while a[i] >= d:
a[i] -= d
i = (i + 1) % 2
d += 1
if i == 0:
print("Vladik")
else:
print("Valera")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
People in the Tomskaya region like magic formulas very much. You can see some of them below.
Imagine you are given a sequence of positive integer numbers *p*1, *p*2, ..., *p**n*. Lets write down some magic formulas:
Here, "mod" means the operation of taking the residue after dividing.
The expression means applying the bitwise *xor* (excluding "OR") operation to integers *x* and *y*. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal — by "xor".
People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence *p*, calculate the value of *Q*.
|
```python
import math
n=int(input(''))
P=list(map(int,input('').split()))
Q=[]
for i in range(n):
z=P[i]
for j in range(n):
z^=((i+1)%(j+1))
if i==0: rez=z;
else: rez^=z;
print(rez)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
The combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?
|
```python
n = int(input())
x = input()
y = input()
c = 0
for i in range(n):
c+=min(abs(int(x[i])-int(y[i])),abs(10-max(int(x[i]),int(y[i])))+min(int(x[i]),int(y[i])))
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position *x*0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals *n*. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position *a*1 to position *b*1, the second — from *a*2 to *b*2
What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.
|
```python
n, x0 = map(int, input().split())
m = -1
M = float('inf')
for i in range(n):
a, b = map(int, input().split())
if a > b:
a, b = b, a
m = max(a, m)
M = min(b, M)
if m > M:
print(-1)
exit()
if x0 > M:
print(x0-M)
elif m <= x0 <= M:
print(0)
else:
print(m-x0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all *n* dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals *s*.
If Kirito starts duelling with the *i*-th (1<=≤<=*i*<=≤<=*n*) dragon and Kirito's strength is not greater than the dragon's strength *x**i*, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by *y**i*.
Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.
|
```python
#Coder_1_neel
a,s=map(int,input().split())
con=0
for i in range(s):
x,y=map(int,input().split())
if(x<=a):
con+=1
a+=y
else:
print("NO")
break
if con==s:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
while True :
n=int(input(" n= "))
if 1<=n<=1000000000:
break
else:
continue
while True :
m=int(input(" m= "))
if 1<=m<=1000000000:
break
else:
continue
while True :
a=int(input(" a= "))
if 1<=a<=1000000000:
break
else:
continue
s=m*n
nb=int(s//p)
print(nb)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.
Formally we will assume that segment [*a*,<=*b*] covers segment [*c*,<=*d*], if they meet this condition *a*<=≤<=*c*<=≤<=*d*<=≤<=*b*.
|
```python
n = int(input())
s = []
for i in range (n):
s.append(list(map(int, input().split())))
def big_segment (a):
index = -1
lowest = a[0][0]
highest = a[0][1]
if lowest != highest:
index = 1
for i in range (len(a)):
if i > 0:
if a[i][0]<= lowest and a[i][1] >= highest:
lowest = a[i][0]
highest = a[i][1]
index = i+1
return index
print(big_segment(s))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In this problem at each moment you have a set of intervals. You can move from interval (*a*,<=*b*) from our set to interval (*c*,<=*d*) from our set if and only if *c*<=<<=*a*<=<<=*d* or *c*<=<<=*b*<=<<=*d*. Also there is a path from interval *I*1 from our set to interval *I*2 from our set if there is a sequence of successive moves starting from *I*1 so that we can reach *I*2.
Your program should handle the queries of the following two types:
1. "1 x y" (*x*<=<<=*y*) — add the new interval (*x*,<=*y*) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals.1. "2 a b" (*a*<=≠<=*b*) — answer the question: is there a path from *a*-th (one-based) added interval to *b*-th (one-based) added interval?
Answer all the queries. Note, that initially you have an empty set of intervals.
|
```python
queries = int(input())
output = []
intervals = []
dic = {}
def dfs(cur, target):
if not cur or cur not in dic:
return False
if cur == target:
return True
temp = dic[cur]
for edge in temp:
if edge == target:
return True
dfs(edge, target)
return False
for _ in range(queries):
q, a, b = [int(item) for item in input().split()]
if q == 1:
intervals.append((a, b))
# update map to see if we got any new edges
if len(intervals) == 1:
continue
for i in range(len(intervals)-1):
c, d = intervals[i]
# check if (a, b) has an edge to (c, d)
if a > c and a < d or b > c and b < d:
if len(intervals)-1 not in dic:
dic[len(intervals)-1] = []
dic[len(intervals)-1].append(i)
# check if (c, d) has an edge to (a, b)
if c > a and c < b or d > a and d < b:
if i not in dic:
dic[i] = []
dic[i].append(len(intervals)-1)
else:
# check if we can go from a to b
res = dfs(a, b)
if res:
output.append("YES")
else:
output.append("NO")
for item in output:
print(item)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
n=int(input())
arr=[]
for i in range(n):
word=input()
arr.append(word)
for item in arr:
if len(item)<10:
print(item)
else:
print(item[0],len(item)-2,item[len(item)-1],sep='')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Calculate the minimum number of characters you need to change in the string *s*, so that it contains at least *k* different letters, or print that it is impossible.
String *s* consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
|
```python
def main():
line = input()
k = int(input())
start_number_dif = len(set(line))
av_for_change = len(line) - start_number_dif
if k - start_number_dif > av_for_change:
print("impossible")
else:
print(k - start_number_dif)
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.
He has a *n*<=×<=*n* chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number *x* written on it, if this cell is attacked by one of the bishops Gargari will get *x* dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.
We assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).
|
```python
n=int(input())
mat=[]
for i in range(n):
mat.append([int(i) for i in input().split()])
pri=[0]*(2*n)
sec=[0]*(2*n)
for i in range(n):
for j in range(n):
pri[i-j+n]+=mat[i][j]
sec[i+j]+=mat[i][j]
resw=0
resb=0
indw=[]
indb=[]
for i in range(n):
for j in range(n):
curr=pri[i-j+n]+sec[i+j]-mat[i][j]
if (i+j)&1:
#i am blck
if curr>resb:
resb=curr
indb=[i+1,j+1]
else:
if curr>resw:
resw=curr
indw=[i+1,j+1]
print(resw+resb)
print(indb[0],indb[1],end=' ')
print(*indw)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer *n* that for each positive integer *m* number *n*·*m*<=+<=1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any *n*.
|
```python
nr = int(input())
m = 1
case = True
while case:
ourNumber = (nr * m) + 1
for x in range(ourNumber - 1, 1, -1):
if ourNumber % x == 0:
case = False
if case:
m += 1
print(m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.
How many bars each of the players will consume?
|
```python
bars = int(input())
times = input().split()
for i in range(len(times)):
times[i] = int(times[i])
a_começou = False
b_começou = False
a = 0
b = 0
atu_alice = 0
atu_bob = -1
tempo = 0
while atu_alice != len(times)+atu_bob:
tempo = tempo + 1
if tempo == times[atu_alice]:
atu_alice = atu_alice + 1
times[atu_bob] = times[atu_bob] - tempo
tempo = 0
a = a + 1
a_começou = True
b_começou = False
if tempo == times[atu_bob]:
atu_bob = atu_bob - 1
times[atu_alice] = times[atu_alice] - tempo
tempo = 0
b = b + 1
a_começou = False
b_começou = True
if tempo == 0:
a = a + 1
else:
b = b + 1
print(b, a)
# 1513957264550
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Imagine a city with *n* horizontal streets crossing *m* vertical streets, forming an (*n*<=-<=1)<=×<=(*m*<=-<=1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traffic moves only from north to south or only from south to north in each vertical street. It is possible to enter a horizontal street from a vertical street, or vice versa, at their intersection.
The mayor has received some street direction patterns. Your task is to check whether it is possible to reach any junction from any other junction in the proposed street direction pattern.
|
```python
n, m = list(map(int, input().split()))
h = input()
v = input()
if '<' in h and '>' in h and 'v' in v and '^' in v:
if (h[0] == '<' and v[0] == '^') or (h[-1] == '>' and v[-1] == 'v') or (h[0] == '>' and v[-1] == '^') or (h[-1] == 'v' and v[0] == 'v'):
print('NO')
else:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of *n* integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly *k* changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.
The operation of changing a number's sign is the operation of multiplying this number by -1.
Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly *k* changes.
|
```python
n, k = list(map(int, input().split()))
arr = list(map(int, input().split()))
arr.sort()
i = 0
while k > 0:
arr[i] = arr[i] * (-1)
k -= 1
i += 1
print(sum(arr))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
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*.
|
```python
import sys
from collections import Counter
n, m = map(int, input().split())
cnt = Counter(map(int, input().split()))
ans = 0
for k, v in cnt.items():
n -= v
ans += v * n
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an *a*1<=×<=*b*1 rectangle, the paintings have shape of a *a*2<=×<=*b*2 and *a*3<=×<=*b*3 rectangles.
Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?
|
```python
def check( x, y, a1, b1, a2, b2):
a = a1 + a2
b = max(b1, b2)
if((a <= x and b <= y) or (a <= y and b <= x)):
return 1
b = b1 + b2
a = max (a1, a2);
if((a<=x and b<=y) or (a<=y and b<=x)):
return 1
return 0
a = list(map(int, input().split(" ")))
b = list(map(int, input().split(" ")))
c = list(map(int, input().split(" ")))
if(check(a[0], a[1], b[0], b[1], c[0], c[1]) or check(a[0], a[1], b[1], b[0], c[0], c[1]) or check(a[0], a[1], b[1], b[0], c[1], c[0])):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.
Little Tommy has *n* lanterns and Big Banban has *m* lanterns. Tommy's lanterns have brightness *a*1,<=*a*2,<=...,<=*a**n*, and Banban's have brightness *b*1,<=*b*2,<=...,<=*b**m* respectively.
Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.
Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.
You are asked to find the brightness of the chosen pair if both of them choose optimally.
|
```python
n,m=map(int,input().split(' '))
a=list(map(int,input().split(' ')))
b=list(map(int,input().split(' ')))
cmp=a[0]*b[0]
idx=0
for i in range(n):
for j in range(m):
if(a[i]*b[j]>=cmp):
cmp=a[i]*b[j]
idx=i
ans=int(-1*1e18)
for i in range(n):
for j in range(m):
if(i!=idx and a[i]*b[j]>=ans):
ans=a[i]*b[j]
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.
Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs *n* ingredients, and for each ingredient she knows the value *a**i* — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all *n* ingredients.
Apollinaria has *b**i* gram of the *i*-th ingredient. Also she has *k* grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the *n* ingredients and can be used for baking cookies.
Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.
|
```python
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
def f(x):
s = 0
for i in range(n):
s += max(0,x*a[i]-b[i])
return s
ans = 0
lo = 0
hi = 10*18
while lo <= hi:
mid = (lo+hi)//2
if f(mid)<=k:
ans = mid
lo = mid + 1
else:
hi = mid - 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word $s$ is Berlanese.
|
```python
test=True
n=input()
i=0
while test and i<len(n)-1:
if n[i]in["a","o","u","i","e"] and (not(n[i+1]in["a","o","u","i","e","n"])) or (n[i]in["a","o","u","i","e","n"] and (n[i+1]in["a","o","u","i","e","n"])) :
print(i)
i=i+1
elif n[i+1]in["a","o","u","i","e","n"] and (not(n[i]in["a","o","u","i","e","n"])) :
print(i)
i=i+1
elif n[i]=="n" and n[i+1]in["a","o","u","i","e","n"]:
i=i+1
else :
print("a")
test=False
if test :
print("YES")
else :
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.
There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.
You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
|
```python
n=int(input())
u=[]
for i in range(n):
a,b=map(int,input().split())
u.append((a,b))
c=0
for i in range(n):
for j in range(n):
if(i!=j and u[i][0]==u[j][1]):
c+=1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
|
```python
s=input()
j=0
x='hello'
for i in range (len(s)-1):
if(x[j]==s[i]):
j=j+1
if j==5:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer *k* and a sequence *a*, consisting of *n* integers.
He wants to know how many subsequences of length three can be selected from *a*, so that they form a geometric progression with common ratio *k*.
A subsequence of length three is a combination of three such indexes *i*1,<=*i*2,<=*i*3, that 1<=≤<=*i*1<=<<=*i*2<=<<=*i*3<=≤<=*n*. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.
A geometric progression with common ratio *k* is a sequence of numbers of the form *b*·*k*0,<=*b*·*k*1,<=...,<=*b*·*k**r*<=-<=1.
Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
|
```python
import sys
input = sys.stdin.readline
n,k = map(int,input().split())
a = list(map(int,input().split()))
left = dict()
right = dict()
for i in range(n):
if a[i] in right:
right[a[i]]+=1
else:
right.update({a[i]:1})
left.update({a[i]:0})
ans = 0
for i in range(n):
right[a[i]]-=1
if not a[i]%k:
if a[i]//k in left and a[i]*k in right:
ans += left[a[i]//k]*right[a[i]*k]
left[a[i]]+=1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu".
Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something!
Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.
|
```python
t, s, ans = input(), 1, ''
for i in range(1, len(t)):
if t[i] == t[i - 1]: s += 1
else:
if s % 2: ans += t[i - 1]
s = 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are *n* schools numerated from 1 to *n*. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools *i* and *j* costs and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
|
```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
n=int(input())
print(int(n/2)-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
To stay woke and attentive during classes, Karen needs some coffee!
Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".
She knows *n* coffee recipes. The *i*-th recipe suggests that coffee should be brewed between *l**i* and *r**i* degrees, inclusive, to achieve the optimal taste.
Karen thinks that a temperature is admissible if at least *k* recipes recommend it.
Karen has a rather fickle mind, and so she asks *q* questions. In each question, given that she only wants to prepare coffee with a temperature between *a* and *b*, inclusive, can you tell her how many admissible integer temperatures fall within the range?
|
```python
n, k, q = [int(x) for x in input().split()]
seg = [0] * 200010
par = [0] * 200010
for i in range(n):
li, ri = [int(x) for x in input().split()]
seg[li] += 1
seg[ri + 1] -= 1
s = 0
for i in range(1, 200001):
s += seg[i]
seg[i] = s
par[i] = par[i - 1] + (1 if s >= k else 0)
for i in range(q):
ai, bi = [int(x) for x in input().split()]
print(par[bi] - par[ai - 1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
|
```python
a,b=map(int,input().split())
#m=list(map(int,input().split()))
#k=0
#for i in range(a):
# if m[i]>=m[b-1] and m[i]!=0:
# k += 1
# else: break
if b%2==0:
a=(b // 2)*a
else: a=(b//2)*a+(a//2)
print(a)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something.
The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people"
Igor just couldn't get why the required minimum is 6 people. "Well, that's the same for five people, too!" — he kept on repeating in his mind. — "Let's take, say, Max, Ilya, Vova — here, they all know each other! And now let's add Dima and Oleg to Vova — none of them is acquainted with each other! Now, that math is just rubbish!"
Igor K. took 5 friends of his and wrote down who of them is friends with whom. Now he wants to check whether it is true for the five people that among them there are either three pairwise acquainted or three pairwise not acquainted people.
|
```python
# Time complexity: O(1)
# Space complexity: O(m)
# Rationale: Since there are at most 5 points, we can just use brute force to loop
# through relations among three points. If they are the same, then "win".
m = int(input())
relation = [[] for _ in range(6)]
# Builds the relation graph without duplicates.
for _ in range(m):
a, b = map(int, input().split())
if a < b:
relation[a].append(b)
else:
relation[b].append(a)
# Loops through relation among three points and checks if they are all acq/unacq.
for x in range(1, 6):
for y in range(x + 1, 6):
for z in range(y + 1, 6):
if z in relation[x] == z in relation[y] == y in relation[x]:
print("WIN")
exit()
print("Fail")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these *n* colors. Adding the *j*-th color to the *i*-th picture takes the *j*-th painter *t**ij* units of time.
Order is important everywhere, so the painters' work is ordered by the following rules:
- Each picture is first painted by the first painter, then by the second one, and so on. That is, after the *j*-th painter finishes working on the picture, it must go to the (*j*<=+<=1)-th painter (if *j*<=<<=*n*); - each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; - each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; - as soon as the *j*-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter.
Given that the painters start working at time 0, find for each picture the time when it is ready for sale.
|
```python
m, n = [int(x) for x in input().split()]
t = [[0]*n for _ in range(m)]
for i in range(m):
t[i] = [int(x) for x in input().split()]
dp = [[0]*n for _ in range(m)]
for i in range(m):
for j in range(n):
if i > 0:
dp[i][j] = dp[i-1][j]
if j > 0:
dp[i][j] = dp[i][j-1]
dp[i][j] += t[i][j]
res = []
for i in range(m):
res.append(dp[i][n-1])
print(*res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya recieved a gift of a string *s* with length up to 105 characters for his birthday. He took two more empty strings *t* and *u* and decided to play a game. This game has two possible moves:
- Extract the first character of *s* and append *t* with this character. - Extract the last character of *t* and append *u* with this character.
Petya wants to get strings *s* and *t* empty and string *u* lexicographically minimal.
You should write a program that will help Petya win the game.
|
```python
def solve():
s=input()
t=list(s).sort()
print("".join(t))
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
s=input()
if(len(s)<=10):
print(s)
else:
s=list(s)
a=s[0]
b=s[-1]
del s[0]
del s[-1]
print(a,len(s),b)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if *n*<==<=3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.
Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.
Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.
|
```python
n = int(input())
a = list(map(int, input()))
b = list(map(int, input()))
a.sort()
b.sort()
j = n-1
ans1 = 0
ans2 = 0
for i in range(n):
if a[i] > b[i]:
ans1 += 1
if a[i] < b[j]:
ans2 += 1
j -=1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in.
There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously.
For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are *k* such guards in the castle, so if there are more than *k* opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed.
Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than *k* doors were opened.
|
```python
import sys
n,k=map(int,input().split())
s=input()
lp={}
act=set()
for i in range(n):
lp[s[i]]=i
for i in range(n):
act.add(s[i])
if len(act)>k:
print("YES")
sys.exit()
elif lp[s[i]]==i:
act.remove(s[i])
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As we all know, Winnie-the-Pooh just adores honey. Ones he and the Piglet found out that the Rabbit has recently gotten hold of an impressive amount of this sweet and healthy snack. As you may guess, Winnie and the Piglet asked to come at the Rabbit's place. Thus, there are *n* jars of honey lined up in front of Winnie-the-Pooh, jar number *i* contains *a**i* kilos of honey. Winnie-the-Pooh eats the honey like that: each time he chooses a jar containing most honey. If the jar has less that *k* kilos of honey or if Winnie-the-Pooh has already eaten from it three times, he gives the jar to Piglet. Otherwise he eats exactly *k* kilos of honey from the jar and puts it back. Winnie does so until he gives all jars to the Piglet. Count how much honey Piglet will overall get after Winnie satisfies his hunger.
|
```python
n,k = [int(i) for i in input().split(' ')]
T = [int(i) for i in input().split(' ')]
func = lambda x: (x>k)*k + (x<=k)*x
T1 = map(func,T)
print(sum(list(T1)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A string is called a *k*-string if it can be represented as *k* concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string *s*, consisting of lowercase English letters and a positive integer *k*. Your task is to reorder the letters in the string *s* in such a way that the resulting string is a *k*-string.
|
```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
k = int(input())
cnt = [0] * 26
s = list(input().rstrip())
for i in s:
cnt[i - 97] += 1
ok = 1
for i in cnt:
if i % k:
ok = 0
break
if not ok:
ans = -1
else:
x = []
for i in range(26):
x.append(chr(i + 97) * (cnt[i] // k))
ans = "".join(x) * k
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.
This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.
|
```python
user_name=input()
distinct_chars=set(user_name)
if len(distinct_chars)%2==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
|
```python
a = input()
b = 1
d = "NO"
for i in range(len(a)-1):
if a[i] == a[i+1]:
b+=1
if b >= 7:
d = "YES"
print(d)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* people and *k* keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.
You are to determine the minimum time needed for all *n* people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.
|
```python
print("_RANDOM_GUESS_1690486862.7831087")# 1690486862.7831285
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fafa owns a company that works on huge projects. There are *n* employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best *l* employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees *n*, find in how many ways Fafa could choose the number of team leaders *l* in such a way that it is possible to divide employees between them evenly.
|
```python
from math import ceil
def f(val, ret = []):
for i in range(2, ceil(val/2)):
while val%i == 0:
val //= i
ret += [i]
if len(set(ret))==1:
return 2
return len(ret)+1
print(f(int(input())))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and *k*.
|
```python
import collections
import math
def function():
n = int(input())
res = []
p = 0
if n % 2 == 0:
p = n//2
res = ['2' for _ in range(p)]
elif n % 3 == 0 or n % 5 == 0:
n = n - 3
p = (n//2)
res = ['2' for _ in range(p)]
res.append('3')
print(len(res))
print(' '.join(e for e in res))
if __name__ == "__main__":
print(function())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Duff is addicted to meat! Malek wants to keep her happy for *n* days. In order to be happy in *i*-th day, she needs to eat exactly *a**i* kilograms of meat.
There is a big shop uptown and Malek wants to buy meat for her from there. In *i*-th day, they sell meat for *p**i* dollars per kilogram. Malek knows all numbers *a*1,<=...,<=*a**n* and *p*1,<=...,<=*p**n*. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.
Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for *n* days.
|
```python
a=int(input())
ans=[]
for i in range(a):
x,y=map(int,input().split())
ans.append([x,y])
total=0
total+=ans[0][0]*ans[0][1]
mini=ans[0][1]
for i in range(1,len(ans)):
mini=min(mini,ans[i][1])
total+=mini*ans[i][0]
print(total)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed.
Pasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed.
|
```python
row,lie,total = [ int(_) for _ in input().split() ]
s = []
def check(x,i):
m = 0
if [x[0]-1,x[1]-1] in s and [x[0],x[1]-1] in s and [x[0]-1,x[1]] in s:
m += 1
if [x[0]-1,x[1]+1] in s and [x[0],x[1]+1] in s and [x[0]-1,x[1]] in s:
m += 1
if [x[0]+1,x[1]+1] in s and [x[0],x[1]+1] in s and [x[0]+1,x[1]] in s:
m += 1
if [x[0]+1,x[1]-1] in s and [x[0],x[1]-1] in s and [x[0]+1,x[1]] in s:
m += 1
if m != 0:
print(i + 1)
else:
s.append(x)
for i in range(total):
a,b = [int(_) for _ in input().split() ]
check([a,b],i)
if total == len(s):
print("0")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into *a* pieces, and the second one — into *b* pieces.
Ivan knows that there will be *n* people at the celebration (including himself), so Ivan has set *n* plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met:
1. Each piece of each cake is put on some plate; 1. Each plate contains at least one piece of cake; 1. No plate contains pieces of both cakes.
To make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number *x* such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least *x* pieces of cake.
Help Ivan to calculate this number *x*!
|
```python
n,a,b=input().split()
a=int(a)
b=int(b)
n=int(n)
l=[]
for i in range(1,n-1):
num=min(a/i,b/(n-i))
l.append(num)
l.sort()
print(int(l[-1]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
We had a string *s* consisting of *n* lowercase Latin letters. We made *k* copies of this string, thus obtaining *k* identical strings *s*1,<=*s*2,<=...,<=*s**k*. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given *k* strings *s*1,<=*s*2,<=...,<=*s**k*, and you have to restore any string *s* so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, *k*·*n*<=≤<=5000).
|
```python
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = 1e9;
const ll inf = 1LL<<62;
template<int MOD> struct ModInt {
static const int Mod = MOD; unsigned x; ModInt() : x(0) { }
ModInt(signed sig) { x = sig < 0 ? sig % MOD + MOD : sig % MOD; }
ModInt(signed long long sig) { x = sig < 0 ? sig % MOD + MOD : sig % MOD; }
int get() const { return (int)x; }
ModInt &operator+=(ModInt that) { if ((x += that.x) >= MOD) x -= MOD; return *this; }
ModInt &operator-=(ModInt that) { if ((x += MOD - that.x) >= MOD) x -= MOD; return *this; }
ModInt &operator*=(ModInt that) { x = (unsigned long long)x * that.x % MOD; return *this; }
ModInt &operator/=(ModInt that) { return *this *= that.inverse(); }
ModInt operator+(ModInt that) const { return ModInt(*this) += that; }
ModInt operator-(ModInt that) const { return ModInt(*this) -= that; }
ModInt operator*(ModInt that) const { return ModInt(*this) *= that; }
ModInt operator/(ModInt that) const { return ModInt(*this) /= that; }
ModInt inverse() const { long long a = x, b = MOD, u = 1, v = 0;
while (b) { long long t = a / b; a -= t * b; std::swap(a, b); u -= t * v; std::swap(u, v); }
return ModInt(u); }
bool operator==(ModInt that) const { return x == that.x; }
bool operator!=(ModInt that) const { return x != that.x; }
ModInt operator-() const { ModInt t; t.x = x == 0 ? 0 : Mod - x; return t; }
};
template<int MOD> ostream& operator<<(ostream& st, const ModInt<MOD> a) { st << a.get(); return st; };
template<int MOD> ModInt<MOD> operator^(ModInt<MOD> a, unsigned long long k) {
ModInt<MOD> r = 1; while (k) { if (k & 1) r *= a; a *= a; k >>= 1; } return r; }
typedef ModInt<1000000007> mint;
const mint base = 100000007;
void solve() {
int k, n; cin >> k >> n;
vector<string> s(k);
for (int i=0; i<k; i++) cin >> s[i];
set<int> hash;
vector<mint> bases(n);
bases[0] = mint(1);
for (int i=1; i<n; i++) bases[i] = bases[i-1]*base;
auto calc = [&](string &t) -> mint {
mint res = 0;
for (int i=0; i<t.size(); i++) {
res += bases[i]*mint(t[i] - '0');
}
return res;
};
for (int i=0; i<n; i++) for (int j=i+1; j<n; j++) {
swap(s[0][i], s[0][j]);
hash.insert(calc(s[0]).get());
swap(s[0][i], s[0][j]);
}
for (int i=1; i<k; i++) {
set<int> hash_;
for (int j=0; j<n; j++) for (int l=j+1; l<n; l++) {
swap(s[i][j], s[i][l]);
int r = calc(s[i]).get();
if (hash.count(r)) hash_.insert(r);
swap(s[i][j], s[i][l]);
}
swap(hash, hash_);
if (hash.size() == 0) {
cout << -1 << '\n';
return;
}
}
int H = *hash.begin();
for (int i=0; i<n; i++) for (int j=i+1; j<n; j++) {
swap(s[0][i], s[0][j]);
if (H == calc(s[0]).get()) {
cout << s[0] << '\n';
return;
}
swap(s[0][i], s[0][j]);
}
}
int main() {
ios::sync_with_stdio(false);
std::cin.tie(nullptr);
// int t; cin >> t;
/*while (t--)*/ solve();
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.
|
```python
n = int(input())
a = list(map(int,input().split()))
for i in range(n):
if a.count(a[i])>1:
a[i] = - 100000000000000000
else:
print(a[i])
exit()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Artem is given a graph, constructed as follows: start with some *k*-clique, then add new vertices one by one, connecting them to *k* already existing vertices that form a *k*-clique.
Artem wants to count the number of spanning trees in this graph modulo 109<=+<=7.
|
```python
print("_RANDOM_GUESS_1692206826.8607752")# 1692206826.860792
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals *n* (*n* is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first *n*<=/<=2 digits) equals the sum of digits in the second half (the sum of the last *n*<=/<=2 digits). Check if the given ticket is lucky.
|
```python
n=int(input())
s=input()
f1,f2=1,1
for i in range(n):
if s[i] in "12356890":
f1=0
if f1:
if s[:n//2].count("4")==s[n//2:].count("4") and s[:n//2].count("7")==s[n//2:].count("7"):
print("YES")
else:
print("NO")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given string *s*. Your task is to determine if the given string *s* contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
|
```python
s = input()
ind1 = s.find("AB")
ind2 = s.find("BA", ind1+(ind1>=0)*2)
if not(ind1 == -1 or ind2 == -1):
print("YES")
quit()
ind1 = s.find("BA")
ind2 = s.find("AB", ind1+(ind1>=0)*2)
if not(ind1 == -1 or ind2 == -1):
print("YES")
quit()
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Little Elephant has an integer *a*, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number *a* fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number *a* in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).
The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.
|
```python
s = input()
n = s.index('0')
print(s[:n]+s[n+1:])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
|
```python
# import sys
# sys.stdin=open("input1.in","r")
# sys.stdout=open("output2.out","w")
L=list(input())
for i in range(len(L)-1,0,-1):
if L[i]!='?' and L[i]!=' ':
if L[i]=='A' or L[i]=='E' or L[i]=='O' or L[i]=='Y' or L[i]=='U' or L[i]=='a' or L[i]=='e' and L[i]=='y' or L[i]=='i' or L[i]=='u':
print("YES")
else:
print("NO")
break
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Chef has a recipe book. He wishes to read it completely as soon as possible so that he could try to cook the dishes mentioned in the book.
The pages of the book are numbered $1$ through $N$. Over a series of days, Chef wants to read each page. On each day, Chef can choose to read any set of pages such that there is no prime that divides the numbers of two or more of these pages, i.e. the numbers of pages he reads on the same day must be pairwise coprime. For example, Chef can read pages $1$, $3$ and $10$ on one day, since $(1, 3)$, $(3, 10)$ and $(1, 10)$ are pairs of coprime integers; however, he cannot read pages $1$, $3$ and $6$ on one day, as $3$ and $6$ are both divisible by $3$. Since chef might get bored by reading the same recipe again and again, Chef will read every page exactly once.
Given $N$, determine the minimum number of days Chef needs to read the entire book and the pages Chef should read on each of these days.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single integer $N$.
-----Output-----
For each test case:
- First, print a line containing a single integer $D$ ― the minimum number of days required to read the book. Let's number these days $1$ through $D$.
- Then, print $D$ lines describing the pages Chef should read. For each valid $i$, the $i$-th of these lines should contain an integer $C_i$ followed by a space and $C_i$ space-separated integers ― the numbers of pages Chef should read on the $i$-th day.
If there are multiple solutions with the minimum number of days, you may print any one.
-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^6$
-----Subtasks-----
Subtask #1 (20 points): $N \le 100$
Subtask #2 (80 points): original constraints
-----Example Input-----
1
5
-----Example Output-----
2
3 1 2 5
2 3 4
-----Explanation-----
Example case 1:
- On the first day, Chef should read three pages: $1$, $2$ and $5$.
- On the second day, Chef should read the remaining two pages: $3$ and $4$.
There are other valid solutions as well.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
def ugcd(n):
ans = [[1]]
if(n==1):
return ans
elif(n%2==1):
ans = [[1, 2, n]]
else:
ans = [[1, 2]]
for k in range(1, int(n//2)):
ans.append([k*2+1, k*2+2])
return ans
t = int(input())
for i in range(t):
n = int(input())
s = (ugcd(n))
print(len(s))
for j in range(len(s)):
print(len(s[j]), end=" ")
print(*s[j])
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.
The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing $N$ gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves: Take one gold coin from the chest. Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even.
Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally.
-----Input-----
The first line contains a single integer $T$ $(1 \le T \le 10^5)$ denotes the number of test cases.
The next $T$ lines each contain a single integer $N$ $(1 \le N \le 10^{18})$.
-----Output-----
$T$ lines, each line is the answer requested by Mr. Chanek.
-----Example-----
Input
2
5
6
Output
2
4
-----Note-----
For the first case, the game is as follows: Mr. Chanek takes one coin. The opponent takes two coins. Mr. Chanek takes one coin. The opponent takes one coin.
For the second case, the game is as follows: Mr. Chanek takes three coins. The opponent takes one coin. Mr. Chanek takes one coin. The opponent takes one coin.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
from sys import stdin, stdout
from collections import defaultdict
input = stdin.readline
for _ in range(int(input())):
n = int(input())
chanek = 0
flag = 1
while n>0:
if n%4==0 and n!=4:
if flag:
chanek += 1
n-=1
flag = 0
else:
n-=1
flag = 1
elif n%2:
if flag:
chanek += 1
n-=1
flag = 0
else:
n-=1
flag = 1
else:
if flag:
chanek += n//2
n//=2
flag = 0
else:
n//=2
flag = 1
print(chanek)
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole n ordered piles of worms such that i-th pile contains a_{i} worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a_1, worms in second pile are labeled with numbers a_1 + 1 to a_1 + a_2 and so on. See the example for a better understanding.
Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.
Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^5), the number of piles.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^3, a_1 + a_2 + ... + a_{n} ≤ 10^6), where a_{i} is the number of worms in the i-th pile.
The third line contains single integer m (1 ≤ m ≤ 10^5), the number of juicy worms said by Marmot.
The fourth line contains m integers q_1, q_2, ..., q_{m} (1 ≤ q_{i} ≤ a_1 + a_2 + ... + a_{n}), the labels of the juicy worms.
-----Output-----
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number q_{i} is.
-----Examples-----
Input
5
2 7 3 4 9
3
1 25 11
Output
1
5
3
-----Note-----
For the sample input:
The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
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()))
k=[]
for i in range(n):
for j in range(a[i]):
k.append(i+1)
m=int(input())
b=list(map(int,input().split()))
for i in b:
print(k[i-1])
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money.
The manager of logging factory wants them to go to the jungle and cut n trees with heights a_1, a_2, ..., a_{n}. They bought a chain saw from a shop. Each time they use the chain saw on the tree number i, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is i (the tree that have height a_{i} in the beginning), then the cost of charging the chain saw would be b_{i}. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each i < j, a_{i} < a_{j} and b_{i} > b_{j} and also b_{n} = 0 and a_1 = 1. Kalila and Dimna want to cut all the trees completely, with minimum cost.
They want you to help them! Will you?
-----Input-----
The first line of input contains an integer n (1 ≤ n ≤ 10^5). The second line of input contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). The third line of input contains n integers b_1, b_2, ..., b_{n} (0 ≤ b_{i} ≤ 10^9).
It's guaranteed that a_1 = 1, b_{n} = 0, a_1 < a_2 < ... < a_{n} and b_1 > b_2 > ... > b_{n}.
-----Output-----
The only line of output must contain the minimum cost of cutting all the trees completely.
Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
5
1 2 3 4 5
5 4 3 2 0
Output
25
Input
6
1 2 3 10 20 30
6 5 4 3 2 0
Output
138
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = [0] * n
stk = [0]
for i in range(1, n):
while len(stk) > 1 and c[stk[1]] - c[stk[0]] <= a[i] * (b[stk[0]] -
b[stk[1]]):
del stk[0]
c[i] = c[stk[0]] + a[i] * b[stk[0]]
while len(stk) > 1 and ((c[stk[-1]] - c[stk[-2]]) * (b[stk[-1]] - b[i]) >
(b[stk[-2]] - b[stk[-1]]) * (c[i] - c[stk[-1]])):
del stk[-1]
stk.append(i)
print(c[n - 1])
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell $(0, 0)$. Robot can perform the following four kinds of operations: U — move from $(x, y)$ to $(x, y + 1)$; D — move from $(x, y)$ to $(x, y - 1)$; L — move from $(x, y)$ to $(x - 1, y)$; R — move from $(x, y)$ to $(x + 1, y)$.
Vasya also has got a sequence of $n$ operations. Vasya wants to modify this sequence so after performing it the robot will end up in $(x, y)$.
Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: $maxID - minID + 1$, where $maxID$ is the maximum index of a changed operation, and $minID$ is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices $2$, $5$ and $7$ are changed, so the length of changed subsegment is $7 - 2 + 1 = 6$. Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is $1$.
If there are no changes, then the length of changed subsegment is $0$. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.
Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from $(0, 0)$ to $(x, y)$, or tell him that it's impossible.
-----Input-----
The first line contains one integer number $n~(1 \le n \le 2 \cdot 10^5)$ — the number of operations.
The second line contains the sequence of operations — a string of $n$ characters. Each character is either U, D, L or R.
The third line contains two integers $x, y~(-10^9 \le x, y \le 10^9)$ — the coordinates of the cell where the robot should end its path.
-----Output-----
Print one integer — the minimum possible length of subsegment that can be changed so the resulting sequence of operations moves the robot from $(0, 0)$ to $(x, y)$. If this change is impossible, print $-1$.
-----Examples-----
Input
5
RURUU
-2 3
Output
3
Input
4
RULR
1 1
Output
0
Input
3
UUU
100 100
Output
-1
-----Note-----
In the first example the sequence can be changed to LULUU. So the length of the changed subsegment is $3 - 1 + 1 = 3$.
In the second example the given sequence already leads the robot to $(x, y)$, so the length of the changed subsegment is $0$.
In the third example the robot can't end his path in the cell $(x, y)$.
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)
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)
S = input()
X, Y = getIntList()
dd = ( (0,1), (0,-1), (-1,0), (1,0))
pp = 'UDLR'
zz = {}
for i in range(4):
zz[ pp[i]] = dd[i]
if abs(X) + abs(Y) >N:
print(-1)
return
if abs(X+Y-N)%2==1:
print(-1)
return
fromLeft = [None for i in range(N)]
fromRight = fromLeft.copy()
x0 = 0
y0 = 0
for i in range(N):
x = S[i]
fromLeft[i] = (x0,y0)
g = zz[x]
x0+= g[0]
y0+= g[1]
if x0==X and y0==Y:
print(0)
return
x0 = 0
y0 = 0
for i in range(N-1,-1,-1):
x = S[i]
fromRight[i] = (x0,y0)
g = zz[x]
x0+= g[0]
y0+= g[1]
up = N
down = 0
dprint(fromLeft)
dprint(fromRight)
while down+1<up:
mid = (up+down)//2
dprint('mid', mid)
ok = False
for i in range(N-mid + 1):
tx = fromLeft[i][0] + fromRight[i+mid-1][0]
ty = fromLeft[i][1] + fromRight[i+mid-1][1]
gg = abs(X-tx) + abs(Y- ty)
if gg <= mid:
ok = True
break
if ok:
up = mid
else:
down = mid
print(up)
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. [Image]
Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:
1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars.
2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.
Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
-----Input-----
The first line of input contains a single integer q (1 ≤ q ≤ 1 000).
The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u.
1 ≤ v, u ≤ 10^18, v ≠ u, 1 ≤ w ≤ 10^9 states for every description line.
-----Output-----
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
-----Example-----
Input
7
1 3 4 30
1 4 1 2
1 3 6 8
2 4 3
1 6 1 40
2 3 7
2 2 4
Output
94
0
32
-----Note-----
In the example testcase:
Here are the intersections used: [Image] Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
q = int(input())
def full_way(u):
res = set()
while u >= 1:
res.add(u)
u //= 2
return res
def get_way(u, v):
res1 = full_way(u)
res2 = full_way(v)
m = max(res1 & res2)
res = set()
for x in res1 | res2:
if x > m:
res.add(x)
return res
d = {}
for i in range(q):
a = input().split()
if a[0] == '1':
v, u, w = map(int, a[1:])
for x in get_way(u, v):
if x not in d:
d[x] = 0
d[x] += w
else:
v, u = map(int, a[1:])
res = 0
for x in get_way(u, v):
if x in d:
res += d[x]
print(res)
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Once upon a time, a king and a few of his soldiers were caught by an enemy king in a war.
He puts them in a circle. The first man in the circle has to kill the second man, the third man has to kill the fourth, fifth man to kill the sixth and so on. When the circle is completed, the remaining people have to form a circle and the process has to repeat. The last man standing will be set free.
If the king has to be set free, which position must he take? For any given N number of people, write a program to find the position that the king has to take.
-----Input-----
Any positive integer in the range 1 to 10000.
-----Output-----
A positive integer indicating safest position
-----Example-----
Input:
9
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())
arr=[]
for i in range(1,n+1):
arr.append(i)
c=0
i=0
f=0;
while(c<n-1):
if(arr[i%n]!=-1 and f):
arr[i%n]=-1
c=c+1
f=0
if(arr[i%n]!=-1):
f=1
i=i+1
for i in range(0,n):
if(arr[i]!=-1):
ans=arr[i]
break;
print(ans)
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $2n$ jars of strawberry and blueberry jam.
All the $2n$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $n$ jars to his left and $n$ jars to his right.
For example, the basement might look like this: [Image]
Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.
Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.
For example, this might be the result: [Image] He has eaten $1$ jar to his left and then $5$ jars to his right. There remained exactly $3$ full jars of both strawberry and blueberry jam.
Jars are numbered from $1$ to $2n$ from left to right, so Karlsson initially stands between jars $n$ and $n+1$.
What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?
Your program should answer $t$ independent test cases.
-----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 a single integer $n$ ($1 \le n \le 10^5$).
The second line of each test case contains $2n$ integers $a_1, a_2, \dots, a_{2n}$ ($1 \le a_i \le 2$) — $a_i=1$ means that the $i$-th jar from the left is a strawberry jam jar and $a_i=2$ means that it is a blueberry jam jar.
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 — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
-----Example-----
Input
4
6
1 1 1 2 2 1 2 1 2 1 1 2
2
1 2 1 2
3
1 1 1 1 1 1
2
2 1 1 1
Output
6
0
6
2
-----Note-----
The picture from the statement describes the first test case.
In the second test case the number of strawberry and blueberry jam jars is already equal.
In the third test case Karlsson is required to eat all $6$ jars so that there remain $0$ jars of both jams.
In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $1$ jar of both jams.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
for tcase in range(int(input())):
n=int(input())
ls = list(map(int, input().split()))
oneneed = 2*(n - ls.count(1))
ldct = {0:0}
ctr = 0
eaten = 0
for i in range(n-1,-1,-1):
eaten += 1
ctr += (1 if ls[i] == 2 else -1)
if ctr not in ldct:
ldct[ctr] = eaten
rdct = {0:0}
ctr = 0
eaten = 0
for i in range(n,2*n):
eaten += 1
ctr += (1 if ls[i] == 2 else -1)
if ctr not in rdct:
rdct[ctr] = eaten
#print(oneneed, ldct, rdct)
best=99**99
for k in list(rdct.keys()):
otk = oneneed - k
if otk in ldct:
best = min(best, rdct[k]+ldct[otk])
print(best)
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Lots of geeky customers visit our chef's restaurant everyday. So, when asked to fill the feedback form, these customers represent the feedback using a binary string (i.e a string that contains only characters '0' and '1'.
Now since chef is not that great in deciphering binary strings, he has decided the following criteria to classify the feedback as Good or Bad :
If the string contains the substring "010" or "101", then the feedback is Good, else it is Bad. Note that, to be Good it is not necessary to have both of them as substring.
So given some binary strings, you need to output whether according to the chef, the strings are Good or Bad.
-----Input-----
The first line contains an integer T denoting the number of feedbacks. Each of the next T lines contains a string composed of only '0' and '1'.
-----Output-----
For every test case, print in a single line Good or Bad as per the Chef's method of classification.
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ |S| ≤ 105
Sum of length of all strings in one test file will not exceed 6*106.
-----Example-----
Input:
2
11111110
10101010101010
Output:
Bad
Good
-----Explanation-----
Example case 1.
The string doesn't contain 010 or 101 as substrings.
Example case 2.
The string contains both 010 and 101 as substrings.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
# cook your dish here
t=int(input())
for i in range(t):
s=input()
fl=-1
n=len(s)
for i in range(n-2):
if(s[i:i+3]=="010" or s[i:i+3]=="101"):
fl=0
print("Good")
break
if(fl==-1):
print("Bad")
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Let's denote as $\text{popcount}(x)$ the number of bits set ('1' bits) in the binary representation of the non-negative integer x.
You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and $\text{popcount}(x)$ is maximum possible. If there are multiple such numbers find the smallest of them.
-----Input-----
The first line contains integer n — the number of queries (1 ≤ n ≤ 10000).
Each of the following n lines contain two integers l_{i}, r_{i} — the arguments for the corresponding query (0 ≤ l_{i} ≤ r_{i} ≤ 10^18).
-----Output-----
For each query print the answer in a separate line.
-----Examples-----
Input
3
1 2
2 4
1 10
Output
1
3
7
-----Note-----
The binary representations of numbers from 1 to 10 are listed below:
1_10 = 1_2
2_10 = 10_2
3_10 = 11_2
4_10 = 100_2
5_10 = 101_2
6_10 = 110_2
7_10 = 111_2
8_10 = 1000_2
9_10 = 1001_2
10_10 = 1010_2
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
def popcount(n):
res = 0
while n > 0:
res += n & 1
n >>= 2
def A(l, r):
r += 1
t = 1 << 64
while t & (l ^ r) == 0:
t >>= 1
res = l | (t - 1)
#print(t, res)
return res
def __starting_point():
"""assert(A(1, 2) == 1)
assert(A(2, 4) == 3)
assert(A(1, 10) == 7)
assert(A(13, 13) == 13)
assert(A(1, 7) == 7)"""
n = int(input())
for _ in range(n):
l, r = list(map(int, input().split()))
res = A(l, r)
print(res)
__starting_point()
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
Chef is going to organize a hill jumping competition and he is going to be one of the judges in it. In this competition there are N hills in a row, and the initial height of i-th hill is Ai. Participants are required to demonstrate their jumping skills by doing what the judges tell them.
Judges will give each participant a card which has two numbers, i and k, which means that the participant should start at the i-th hill and jump k times, where one jump should be from the current hill to the nearest hill to the right which is strictly higher (in height) than the current one. If there is no such hill or its distance (i.e. difference between their indices) is more than 100 then the participant should remain in his current hill.
Please help Chef by creating a program to use it during the competitions. It should read the initial heights of the hill and should support two kinds of operations:
Type 1: Given a two numbers: i and k, your program should output the index of the hill the participant is expected to finish if he starts from the i-th hill (as explained above).
Type 2: Given three numbers: L, R, X, the heights of all the hills between L and R, both end points inclusive, should be increased by X (if X is negative then their height is decreased).
-----Input-----
- First line contains two integers N and Q, denoting the number of hills and number of operations respectively.
- Second line contains N space-separated integers A1, A2, ..., AN denoting the initial heights of the hills.
- Each of the next Q lines describes an operation. If the first integer is equal to 1, it means that the operation is of Type 1, and it will be followed by two integers i and k. Otherwise the first number will be equal to 2, and it means that the operation is of Type 2, and so it will be followed by three integers L, R and X.
-----Output-----
For each operation of Type 1, output the index of the hill in which the participant will finish.
-----Constraints-----
- 1 ≤ N, Q ≤ 100,000
- 1 ≤ Ai ≤ 1,000,000
- 1 ≤ L ≤ R ≤ N
- -1,000,000 ≤ X ≤ 1,000,000
- 1 ≤ i, k ≤ N
-----Subtasks-----
- Subtask 1 (20 points) : 1 ≤ N, Q ≤ 1,000
- Subtask 2 (80 points) : Original constraints
-----Example-----
Input:
5 3
1 2 3 4 5
1 1 2
2 3 4 -1
1 1 2
Output:
3
4
-----Explanation-----
The initial heights are (1, 2, 3, 4, 5). The first operation is of Type 1 and starts from Hill 1 and wants to jump twice. The first jump will be to Hill 2, and the second jump will be to Hill 3. Hence the output for this is 3.
The second operation changes the heights to (1, 2, 2, 3, 5).
The last operation starts from Hill 1. The first jump is to Hill 2. But the next jump will skip Hill 3 (because it's height is not strictly greater than the current hill's height), and will go to Hill 4. Hence the output is 4.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
n,q=list(map(int,input().split()))
final=[]
height=list(map(int,input().split()))
for k in range(0,q):
b=input().split()
if int(b[0])==1:
step=int(b[1])-1
for k in range(0,int(b[2])):
temp = 0
j=1
while j in range(1,101) and temp==0 and step+j<n:
if height[step+j]>height[step]:
step=step+j
temp=1
j+=1
final.append(step+1)
elif int(b[0])==2:
for k in range(int(b[1])-1,int(b[2])):
height[k]=height[k]+int(b[3])
for l in range(0,len(final)):
print(final[l])
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
People in Karunanagar are infected with Coronavirus. To understand the spread of disease and help contain it as early as possible, Chef wants to analyze the situation in the town. Therefore, he does the following:
- Chef represents the population of Karunanagar as a binary string of length $N$ standing in a line numbered from $1$ to $N$ from left to right, where an infected person is represented as $1$ and an uninfected person as $0$.
- Every day, an infected person in this binary string can infect an adjacent (the immediate left and right) uninfected person.
- Therefore, if before Day 1, the population is $00100$, then at the end of Day 1, it becomes $01110$ and at the end of Day 2, it becomes $11111$.
But people of Karunanagar are smart and they know that if they 'socially isolate' themselves as early as possible, they reduce the chances of the virus spreading. Therefore on $i$-th day, person numbered $P_i$ isolates himself from person numbered $P_i - 1$, thus cannot affect each other. This continues in the town for $D$ days.
Given the population binary string before Day 1, Chef wants to calculate the total number of infected people in Karunanagar at the end of the day $D$. Since Chef has gone to wash his hands now, can you help do the calculation for him?
-----Input:-----
- First line will contain $T$, number of testcases. Then the test cases follow.
- The first line of each test case contains a single integer $N$ denoting the length of the binary string.
- The next line contains a binary string of length $N$ denoting the population before the first day, with $1$ for an infected person and $0$ for uninfected.
- The next line contains a single integer $D$ - the number of days people isolate themselves.
- The next line contains $P$ - a list of $D$ distinct space-separated integers where each $P_{i}$ denotes that at the start of $i^{th}$ day, person $P_{i}$ isolated him/herself from the person numbered $P_i-1$.
-----Output:-----
For each test case, print a single integer denoting the total number of people who are infected after the end of $D^{th}$ day.
-----Constraints-----
- $1 \leq T \leq 200$
- $2 \leq N \leq 10^{4}$
- $1 \leq D < N$
- $2 \leq P_{i} \leq N$ for $1 \le i \le D$
-----Subtasks-----
Subtask #1(30 points): $1 \leq T \leq 100$, $2 \leq N \leq 2000$
Subtask #2(70 points): Original Constraints
-----Sample Input:-----
2
9
000010000
3
2 5 8
5
00001
1
5
-----Sample Output:-----
6
1
-----EXPLANATION:-----
For the purpose of this explanation, a social distance can be denoted with a '$|$'.
For the first testcase:
-
Before Day $1$, the population is: $0|00010000$
-
Before Day $2$, the population is: $0|001|11000$
-
Before Day $3$, the population is: $0|011|111|00$
-
Therefore, after Day $3$, the population will be: $0|111|111|00$
So, there are $6$ infected persons.
For the second testcase:
Before Day $1$, the population is: $0000|1$
Therefore, there is one infected person.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
# cook your dish here
T = int(input())
for i in range(T):
N,data,D,People = int(input()),list(map(int,list(input()))),int(input()),list(map(int,input().split()))
data.insert(0,"|"),data.append("|")
infected = []
for i in range(1,N+1):
if(data[i]==1):
infected.append(i)
i = 0
while(i<D):
boundary = People[i] + i
data.insert(boundary,"|")
times = len(infected)
for p in range(times):
index = infected[p]
if(index>=boundary):
index+=1
infected[p]+=1
if(data[index]==1):
if(data[index+1]==0):
data[index+1] = 1
infected.append(index+1)
if(data[index-1]==0):
data[index-1] = 1
infected.append(index-1)
else:
infected.remove(index)
times-=1
i+=1
infected.sort()
print(data.count(1))
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
This problem is a version of problem D from the same contest with some additional constraints and tasks.
There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $1$ and two candies of type $2$ is bad).
It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.
You really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number $f_i$ is given, which is equal to $0$ if you really want to keep $i$-th candy for yourself, or $1$ if you don't mind including it into your gift. It is possible that two candies of the same type have different values of $f_i$.
You want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having $f_i = 1$ in your gift.
You have to answer $q$ independent queries.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
-----Input-----
The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries.
The first line of each query contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of candies.
Then $n$ lines follow, each containing two integers $a_i$ and $f_i$ ($1 \le a_i \le n$, $0 \le f_i \le 1$), where $a_i$ is the type of the $i$-th candy, and $f_i$ denotes whether you want to keep the $i$-th candy for yourself ($0$ if you want to keep it, $1$ if you don't mind giving it away).
It is guaranteed that the sum of $n$ over all queries does not exceed $2 \cdot 10^5$.
-----Output-----
For each query print two integers:
the maximum number of candies in a gift you can compose, according to the constraints in the statement; the maximum number of candies having $f_i = 1$ in a gift you can compose that contains the maximum possible number of candies.
-----Example-----
Input
3
8
1 0
4 1
2 0
4 1
5 1
6 1
3 0
2 0
4
1 1
1 1
2 1
2 1
9
2 0
2 0
4 1
4 1
4 1
7 0
7 1
7 0
7 1
Output
3 3
3 3
9 5
-----Note-----
In the first query, you can include two candies of type $4$ and one candy of type $5$. All of them have $f_i = 1$ and you don't mind giving them away as part of the gift.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code.
|
```python
# @author
import sys
class GCandyBoxHardVersion:
def solve(self):
q = int(input())
for _ in range(q):
n = int(input())
a = [0] * n
f = [0] * n
for i in range(n):
a[i], f[i] = [int(_) for _ in input().split()]
d = {key: [0, 0] for key in a}
for i in range(n):
d[a[i]][f[i]] += 1
rev_d = {sum(key): [] for key in list(d.values())}
for x in d:
rev_d[d[x][0] + d[x][1]] += [d[x]]
for x in rev_d:
rev_d[x].sort(key=lambda item:item[1])
# print(rev_d)
cur = max(rev_d)
cnt = max(rev_d)
nb_candies = 0
given_away = 0
while 1:
if cnt == 0 or cur == 0:
break
if cur > cnt:
cur -= 1
continue
if cnt not in rev_d or not rev_d[cnt]:
cnt -= 1
continue
mx_f = -1
v = -1
for max_cnt in range(cur, cnt + 1):
if max_cnt in rev_d and rev_d[max_cnt] and rev_d[max_cnt][-1][1] > mx_f:
v = max_cnt
mx_f = rev_d[max_cnt][-1][1]
to_take = rev_d[v].pop()
# rev_d[cnt] -= 1
nb_candies += cur
given_away += min(to_take[1], cur)
cur -= 1
# rev_d[cnt - cur] += 1
print(nb_candies, given_away)
solver = GCandyBoxHardVersion()
input = sys.stdin.readline
solver.solve()
```
|
|
open-r1/verifiable-coding-problems-python-10k
|
Solve the following coding problem using the programming language python:
You visit a doctor on a date given in the format $yyyy:mm:dd$. Your doctor suggests you to take pills every alternate day starting from that day. You being a forgetful person are pretty sure won’t be able to remember the last day you took the medicine and would end up in taking the medicines on wrong days.
So you come up with the idea of taking medicine on the dates whose day is odd or even depending on whether $dd$ is odd or even. Calculate the number of pills you took on right time before messing up for the first time.
-----Note:-----
Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, in the format $yyyy:mm:dd$
-----Output:-----
For each testcase, output in a single line the required answer.
-----Constraints-----
- $ 1 \leq T \leq 1000 $
- $ 1900 \leq yyyy \leq 2038 $
- $yyyy:mm:dd$ is a valid date
-----Sample Input:-----
1
2019:03:31
-----Sample Output:-----
1
-----EXPLANATION:-----
You can take pill on the right day only on 31st March. Next you will take it on 1st April which is not on the alternate day.
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())
li1=[31,29,31,30,31,30,31,31,30,31,30,31]
li2=[31,28,31,30,31,30,31,31,30,31,30,31]
for z in range(t):
y,m,d=list(map(int,input().split(':')))
if y%4 == 0:
if y%100 == 0:
if y%400 == 0:
li=li1
else:
li=li2
else:
li=li1
else:
li=li2
c=0
if d%2 == 0:
while d%2 == 0:
c+=1
d+=2
if d>li[m-1]:
d=d%li[m-1]
m+=1
else:
while d%2 != 0:
c+=1
d+=2
if d>li[m-1]:
d=d%li[m-1]
m+=1
print(c)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.