text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide a correct Python 3 solution for this coding contest problem.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
"Correct Solution:
```
s = input()
d = {}
for i in s:
if i in d.keys():
d[i] += 1
else:
d[i] = 1
if "n" not in d.keys() or "i" not in d.keys() or "e" not in d.keys() or "t" not in d.keys():
print(0)
else:
x = min(d["i"] , d["t"])
y = min((d["n"] - 1) // 2 , d["e"] // 3)
print(min(x , y))
```
| 92,100 |
Provide a correct Python 3 solution for this coding contest problem.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
"Correct Solution:
```
word = input()
if word.count('n') > 1:
ns = 1 + (word.count('n') - 3) // 2
else:
ns = 0
lst = [ns, word.count('e') // 3, word.count('i'), word.count('t')]
print(min(lst))
```
| 92,101 |
Provide a correct Python 3 solution for this coding contest problem.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
"Correct Solution:
```
s=input()
vl={"n":-1,"i":0,"e":0,"t":0}
for i in s:
if i in vl:
vl[i]+=1
vl["e"]/=3
vl["n"]/=2
m=100000
for i in vl.values():
m=min(m,i)
print(int(m))
```
| 92,102 |
Provide a correct Python 3 solution for this coding contest problem.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
"Correct Solution:
```
import sys
s = input().strip()
inpDict = {}
for c in s:
inpDict[c] = inpDict.get(c,0) + 1
nn = "nineteen"
nDict = {}
for c in nn:
nDict[c] = nDict.get(c,0) + 1
m = sys.maxsize
for c in nDict.keys():
if(c != 'n'):
m = min(m, inpDict.get(c,0)//nDict[c])
if((inpDict.get('n',0)-1)//2 >= m):
if(m>=0):
print(m)
else:
print(0)
else:
x = (inpDict.get('n',0)-1)//2
if(x>=0):
print(x)
else:
print(0)
```
| 92,103 |
Provide a correct Python 3 solution for this coding contest problem.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
"Correct Solution:
```
entrada=input()
n=0
e=0
i=0
t=0
for k in range (len(entrada)):
if entrada[k]=="n":
n+=1
if entrada[k]=="e":
e+=1
if entrada[k]=="i":
i+=1
if entrada[k]=="t":
t+=1
if n%2==0:
n-=1
n=((n-3)//2)+1
if n==-1:
n=0
e=e//3
def fmenor(a,b,c,d):
menor:None
if a<=b and a<=c and a<=d:
menor=a
elif b<=a and b<=c and b<=d:
menor=b
elif c<=d and c<=a and c<=b:
menor=c
else:
menor=d
return menor
print(fmenor(n,e,i,t))
```
| 92,104 |
Provide a correct Python 3 solution for this coding contest problem.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
"Correct Solution:
```
str = list(input())
cntN = max((str.count('n') - 3) // 2 + 1, 0)
cntI = max(str.count('i') // 1, 0)
cntE = max(str.count('e') // 3, 0)
cntT = max(str.count('t') // 1, 0)
print(min(cntN, cntI, cntE, cntT))
```
| 92,105 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
Submitted Solution:
```
n,c=input(),0
nc=n.count('n')
#print(nc)
if(nc>=3):
c=1
nc-=3
print(min(nc//2+c,n.count('i'),n.count('t'),n.count('e')//3))
else:
print('0')
```
Yes
| 92,106 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
Submitted Solution:
```
from collections import Counter
s = input()
a = Counter('nineteen')
c = Counter(s)
set_ = {'n', 'i', 'e', 't'}
ans = 100
for el in set_:
if el != 'n':
ans = min(ans, s.count(el) // a[el])
else:
ans = min(ans, max(0, (s.count('n') - 1) // 2))
print(ans)
```
Yes
| 92,107 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
Submitted Solution:
```
import math
s = input()
n_count = s.count("n")
e_count = s.count("e")
n = math.floor((n_count - 1) / 2)
e = math.floor(e_count/3)
i = s.count("i")
t = s.count("t")
print(max(min(n,i,t,e),0))
```
Yes
| 92,108 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
Submitted Solution:
```
from typing import Dict
#nineteen
def count_9teen(string : str) -> int:
if len(string) < 8:
return 0
count = 0
letter_count = init_9teen_counter()
original_count = get_9teen_letter_count()
for c in string:
if c in letter_count:
letter_count[c] = letter_count[c] + 1
counts = [letter_count[c]//original_count[c] for c in 'iet']
if letter_count['n'] >= 3:
counts.append( 1+ (letter_count['n']-3)//2)
else:
counts.append(0)
return min(counts)
def init_9teen_counter() -> Dict[chr, int]:
letter_count = {}
letter_count['i'] = 0
letter_count['n'] = 0
letter_count['e'] = 0
letter_count['t'] = 0
return letter_count
def get_9teen_letter_count()-> Dict[chr, int]:
letter_count={}
letter_count['i'] = 1
letter_count['n'] = 3
letter_count['e'] = 3
letter_count['t'] = 1
return letter_count
if __name__ =='__main__':
string = input()
print(count_9teen(string))
```
Yes
| 92,109 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
Submitted Solution:
```
x=input()
c=["n","i","e","t"]
z=[0,0,0,0]
v=0
for i in x:
if i==c[0]:
z[0]=z[0]+1
elif i==c[1]:
z[1]=z[1]+1
elif i==c[2]:
z[2]=z[2]+1
elif i==c[3]:
z[3]=z[3]+1
if z[0]%2!=0 and z[0]!=1:
z[0]=z[0]
while True:
z[1]=z[1]-1
z[2]=z[2]-3
z[3]=z[3]-1
if z[1]<0 or z[2]<0 or z[3]<0 or z[0]<3 :
break
else:
v=v+1
print(v)
```
No
| 92,110 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
Submitted Solution:
```
s=input()
n = s.count('n')
i = s.count('i')
e = s.count('e')
t = s.count('t')
#print(str(n)+" "+str(i)+" "+str(e)+" "+str(t))
if e-n==1:
n=e
if i<1 or n<3 or e<3 or t<1:
print(0)
else:
x = min(n,e)
y = min(i,t)
if x<y:
y = min(i,t,3)
#print(z)
for j in range(y,0,-1):
if 3*j<=x:
print(int(j))
break
```
No
| 92,111 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
Submitted Solution:
```
s = str(input())
nn = 0
ii = 0
ee = 0
tt = 0
for i in range(0,len(s)):
if s[i] == 'i':
ii += 1
elif s[i] == 'n':
nn += 1
elif s[i] == 'e':
ee += 1
elif s[i] == 't':
tt += 1
nn //= 3
ee //= 3
print(min(nn, min(ii, min(ee, tt))));
```
No
| 92,112 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
Input
The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100.
Output
Print a single integer β the maximum number of "nineteen"s that she can get in her string.
Examples
Input
nniinneetteeeenn
Output
2
Input
nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii
Output
2
Input
nineteenineteen
Output
2
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 25 18:57:03 2019
@author: Lenovo
"""
al=['n','i','e','t']
ac=[3,1,3,1]
cl=[]
str=input()
for i in range(len(al)):
ca=(str.count(al[i]))
if ca%3==2 and i==0:
ca+=1
cl.append(ca//ac[i])
print(min(cl))
```
No
| 92,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Tags: brute force, dp, implementation
Correct Solution:
```
n,m=map(int,input().split())
l=[]
b=[0]*m
for i in range(n):
l.append(list(map(int,input().split())))
for i in range(n):
for j in range(m):
if j==0:
b[0]+=l[i][0]
else:
if b[j]>=b[j-1]:
b[j]+=l[i][j]
else:
b[j]=b[j-1]+l[i][j]
print(b[-1],end=" ")
```
| 92,114 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Tags: brute force, dp, implementation
Correct Solution:
```
from sys import stdin,stdout
a,b=map(int,stdin.readline().split())
z=[list(map(int,stdin.readline().split())) for _ in " "*a]
k=[[0]*b for _ in " "*a];ans=['']*a
for i in range(a):
if i==0:
for j in range(b):k[i][j]+=k[i][j-1]+z[i][j]
else:
for j in range(b):
if j==0:k[i][j]+=k[i-1][j]+z[i][j]
else:k[i][j]=max(k[i-1][j],k[i][j-1])+z[i][j]
ans[i]=str(k[i][b-1])
stdout.write(' '.join(ans))
```
| 92,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Tags: brute force, dp, implementation
Correct Solution:
```
m, n = map(int, input().split())
t = [[int(i) for i in input().split()] for _ in range(m)]
a = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
x = 0
if i - 1 >= 0:
x = max(x, a[i - 1][j])
if j - 1 >= 0:
x = max(x, a[i][j - 1])
a[i][j] = x + t[i][j]
for i in range(m):
print(a[i][-1], end=' ')
print()
```
| 92,116 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Tags: brute force, dp, implementation
Correct Solution:
```
m, n = map(int, input().split())
mat = [list(map(int, input().split())) for _ in range(m)]
t = [[0] * m for _ in range(n)]
for p in range(n):
for i in range(m):
t[p][i] = max(t[p - 1][i] if p > 0 else 0, t[p][i - 1]) + mat[i][p]
print(' '.join(map(str, t[n - 1])))
```
| 92,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Tags: brute force, dp, implementation
Correct Solution:
```
n , m = map(int,input().split())
painters = [0] * (m+1)
l = []
for i in range(n):
l.append(list(map(int,input().split())))
ans = []
for i in range(n):
for j in range(m):
if i == 0 :
if j == 0 :
painters[j+1] += l[i][j]
else:
painters[j+1]= painters[j] + l[i][j]
else:
if j == 0 :
painters[j+1] += l[i][j]
else:
if painters[j] <= painters[j+1]:
painters[j+1] += l[i][j]
else:
painters[j+1] = painters[j] + l[i][j]
ans.append(painters[m])
print(*ans)
```
| 92,118 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Tags: brute force, dp, implementation
Correct Solution:
```
R = lambda:map(int, input().split())
m, n = R()
t = [0] * (n + 1)
c = []
for i in range(m):
a = list(R())
for j in range(n):
t[j + 1] = max(t[j], t[j + 1]) + a[j]
c += [str(t[n])]
print(" ".join(c))
```
| 92,119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Tags: brute force, dp, implementation
Correct Solution:
```
m, n = map(int, input().split())
t = [[]] * m
ans = [[]] * m
for i in range(m):
t[i] = list(map(int, input().split()))
ans[i] = [0] * n
for i in range(m):
for j in range(n):
a1 = ans[i - 1][j] if i > 0 else 0
a2 = ans[i][j - 1] if j > 0 else 0
ans[i][j] = max(a1, a2) + t[i][j]
print(' '.join(map(lambda o: str(ans[o][n - 1]), range(m))))
```
| 92,120 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Tags: brute force, dp, implementation
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
from collections import Counter
# c=sorted((i,int(val))for i,val in enumerate(input().split()))
import heapq
# c=sorted((i,int(val))for i,val in enumerate(input().split()))
# n = int(input())
# ls = list(map(int, input().split()))
# n, k = map(int, input().split())
# n =int(input())
# e=list(map(int, input().split()))
from collections import Counter
# n =int(input())
n, k = map(int, input().split())
t=[]
for _ in range(n):
#n, k = map(int, input().split())
arr=list(map(int, input().split()))
t.append(arr)
time=[0]*n
for i in range(k):
for j in range(n):
if j==0:
time[j]+=t[j][i]
else:
if j>0 and n>1:
time[j]=max(time[j],time[j-1])+t[j][i]
else:
time[j]+=t[j][i]
#print(time)
print(*time)
```
| 92,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Submitted Solution:
```
m,n = list(map(int,input().split()))
t = [[0]*n] + [list(map(int,input().split())) for _ in range(m)]
for i in range(1,m+1):
t[i][0] += t[i-1][0]
for j in range(1,n):
t[i][j] += max(t[i-1][j],t[i][j-1])
print(*[t[i][-1] for i in range(1,m+1)])
```
Yes
| 92,122 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Submitted Solution:
```
"""
Codeforces Round 241 Div 1 Problem B
Author : chaotic_iak
Language: Python 3.3.4
"""
class InputHandlerObject(object):
inputs = []
def getInput(self, n = 0):
res = ""
inputs = self.inputs
if not inputs: inputs.extend(input().split(" "))
if n == 0:
res = inputs[:]
inputs[:] = []
while n > len(inputs):
inputs.extend(input().split(" "))
if n > 0:
res = inputs[:n]
inputs[:n] = []
return res
InputHandler = InputHandlerObject()
g = InputHandler.getInput
############################## SOLUTION ##############################
m,n = [int(x) for x in g()]
q = []
for i in range(m):
q.append([int(x) for x in g()])
p = q[:]
for j in range(n):
for i in range(m):
if i == 0 and j == 0:
continue
if i == 0:
p[i][j] = p[i][j-1] + q[i][j]
continue
if j == 0:
p[i][j] = p[i-1][j] + q[i][j]
continue
p[i][j] = max(p[i-1][j], p[i][j-1]) + q[i][j]
for i in range(m):
print(p[i][n-1], end=" ")
```
Yes
| 92,123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Submitted Solution:
```
#from dust i have come dust i will be
import sys
m,n=map(int,input().split())
a=[[]*n for i in range(m)]
for i in range(m):
a[i]=list(map(int,input().split()))
for i in range(1,m):
a[i][0]+=a[i-1][0]
for i in range(1,n):
a[0][i]+=a[0][i-1]
for i in range(1,m):
for j in range(1,n):
a[i][j]+=max(a[i-1][j],a[i][j-1])
for i in range(m):
sys.stdout.write(str(a[i][n-1])+" ")
```
Yes
| 92,124 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Submitted Solution:
```
n , m = map(int, input().split())
mat = [[0 for i in range(m+1)]for j in range(n+1)]
a = []
for i in range(n):
a.append(list(map(int , input().split())))
for i in range(1 , n+1):
for j in range(1 , m+1):
mat[i][j] = a[i-1][j-1] + max(mat[i-1][j], mat[i][j-1])
#print(mat)
for i in range(1 , n+1):
print(mat[i][m] , end = " ")
```
Yes
| 92,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Submitted Solution:
```
m,n=map(int, input().split())
a=[0]*8
for i in range(m):
x=list(map(int, input().split()))
for j in range(1, n+1):
a[j]=a[j-1]+x[j-1]
print(a[n], end=' ')
```
No
| 92,126 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Submitted Solution:
```
n,m=map(int,input().split())
L=[list(map(int,input().split())) for i in range(n)]
L1=[[0 for j in range(m)] for i in range(n)]
g=0
p=sum(L[0])
out=[p]
for i in range(1,n) :
d=sum(L[i-1])
d-=L[i-1][0]
d+=g
e=d
g=max(0,d-L[i][0])
for j in range(m-1) :
f=d-L[i][j]
if f>0 :
L1[i][j]=0
e-=L[i-1][j+1]
d-=L[i][j]
d=min(d,e)
else :
L1[i][j]=abs(d-L[i][j])
d=0
L1[i][m-1]=L[i][m-1]
for i in range(1,n) :
p+=sum(L1[i])
out.append(p)
print(*out)
```
No
| 92,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Submitted Solution:
```
m,n=map(int, input().split())
a=[0]*8;
for i in range(m):
for j in range(1,n):
x=int(input())
a[j]=max(a[j], a[j-1])+x
print(a[n], end=' ')
```
No
| 92,128 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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 tij 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.
Input
The first line of the input contains integers m, n (1 β€ m β€ 50000, 1 β€ n β€ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 β€ tij β€ 1000), where tij is the time the j-th painter needs to work on the i-th picture.
Output
Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.
Examples
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Submitted Solution:
```
m,n=[int(x) for x in input().split()]
ans=[[0 for i in range(n)] for i in range(m)]
a=[]
for i in range(m):
a.append([int(x) for x in input().split()])
ans[0][0]=a[0][0]
for i in range(1,m):
ans[i][0]=ans[i-1][0]+a[i][0]
for i in range(1,n):
ans[0][i]=ans[0][i-1]+a[0][i]
for i in range(1,n):
key=ans[0][i]
for j in range(1,m):
if ans[j][i-1]<=key:
ans[j][i]=ans[j-1][i]+a[j][i]
else:
ans[j][i]=ans[j][i-1]+a[j][i]
key=a[j][i]
# print(ans[n-1])
for i in range(m):
print(ans[i][n-1],end=" ")
```
No
| 92,129 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gena doesn't like geometry, so he asks you to solve this problem for him.
A rectangle with sides parallel to coordinate axes contains n dots. Let's consider some point of the plane. Let's count the distances from this point to the given n points. Let's sort these numbers in the non-decreasing order. We'll call the beauty of the point the second element of this array. If there are two mimimum elements in this array, the beaty will be equal to this minimum.
Find the maximum beauty of a point inside the given rectangle.
Input
The first line contains three integers w, h, n (1 β€ w, h β€ 106, 2 β€ n β€ 1000) β the lengths of the rectangle sides and the number of points. Next n lines contain two integers xi, yi (0 β€ xi β€ w, 0 β€ yi β€ h) each β the coordinates of a point. It is possible that it will be coincident points.
Output
Print a single number β the maximum beauty of a point with the absolute or relative error of at most 10 - 9.
Examples
Input
5 5 4
0 0
5 0
0 5
5 5
Output
4.99999999941792340
Input
5 5 3
4 0
2 5
4 1
Output
5.65685424744772010
Note
The point which beauty we need to find must have coordinates (x, y), where 0 β€ x β€ w, 0 β€ y β€ h. Some of the n points can coincide.
Submitted Solution:
```
import math
d = [eval(i) for i in input().split()]
v = []
for i in range(int(d[2])):
s = input().split()
v.append(round(float(math.sqrt(float(s[0])**2 + float(s[1])**2)), 9))
v = sorted(v)
print(v[1])
```
No
| 92,130 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Tags: implementation
Correct Solution:
```
n=int(input())
x=input()
s="0b"+x[::-1]
s=bin(int(s,2)+1)[2:]
if len(s)>n:
s=s[1:]
elif len(s)<n:
d=n-len(s)
s="0"*d+s
s=s[::-1]
c=0
for i in range(n):
if s[i]!=x[i]:
c+=1
print(c)
```
| 92,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Tags: implementation
Correct Solution:
```
n = int(input())
ls = [int(u) for u in input()]
if 0 in ls:
print(ls.index(0)+1)
else:
print(len(ls))
```
| 92,132 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Tags: implementation
Correct Solution:
```
import re
def main():
n = int(input())
num = input()
l = len(re.match(r'^1*', num).group(0))
print(l + 1 if l < n else n)
if __name__ == '__main__':
main()
```
| 92,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(input())
sum = 0
for i in range(n):
if a[i] == '1':
sum += 1
else:
sum += 1
break
print(sum)
```
| 92,134 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Tags: implementation
Correct Solution:
```
N = int(input())
S = input().split("0")
print(min(N,1+len(S[0])))
```
| 92,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Tags: implementation
Correct Solution:
```
n=input()
s=input()
count=0
for i in s:
count+=1
if i=='0':
break
print(count)
```
| 92,136 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Tags: implementation
Correct Solution:
```
def input_ints():
return list(map(int, input().split()))
def solve():
n = int(input())
s = input()
x = int(s[::-1], 2)
y = (x + 1) % (1 << n)
print(bin(x ^ y).count('1'))
if __name__ == '__main__':
solve()
```
| 92,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Tags: implementation
Correct Solution:
```
n=int(input())
s=input()
print(min(len((s.split('0')[0]))+1,n))
```
| 92,138 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Submitted Solution:
```
n = int(input())
s = input()
i = 0
while i < n and s[i] == '1':
i += 1
if i < n:
print(i+1)
else:
print(i)
```
Yes
| 92,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Submitted Solution:
```
x=int(input());a=list(map(int,input()));p=1;j=0
for i in range(x):
if a[i]==1 and p==1:
a[i]=0
j+=1
elif a[i]==0 and p==1:
a[i]=1
p=0
j+=1
print(j)
```
Yes
| 92,140 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Submitted Solution:
```
n=int(input())
a=input()
c,d=0,0
for i in range(n):
if a[i]=="1":
c+=1
d=1
elif a[i]=="0" and d==1:
c+=1
d=0
break
elif i==0 and a[i]=="0" and d==0:
c+=1
break
print(c)
```
Yes
| 92,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Submitted Solution:
```
n=int(input())
st=input()
num=0
for i in range(n):
if(st[i]=='1'):
num+=(2**i)
num=num+1
b=bin(num).replace("0b","")
b=b[::-1]
ans=0
l=min(n,len(b))
for i in range(l):
if(st[i]!=b[i]):
ans+=1
for i in range(l,n):
if(st[i]!='0'):
ans=ans+1
print(ans)
```
Yes
| 92,142 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Submitted Solution:
```
b=int(input())
a=input()
l=0
i=0
p=[]
while i<(len(a)):
while True:
if a[i]=="1":
l=l+1
i=i+1
if i==len(a):
p.append(l)
l=0
break
else:
p.append(l)
l=0
i=i+1
break
if max(p)==len(a):
print(max(p))
else:
print(max(p)+1)
```
No
| 92,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Submitted Solution:
```
input()
a = input()
a += "0"
print(a.index("0")+1)
```
No
| 92,144 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Submitted Solution:
```
'''input
4
1100
'''
n = int(input())
b = list(input())
if set(b) == {"1"}:
print(n)
else:
print(n-1)
```
No
| 92,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.
Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values ββof the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of bits in the cell.
The second line contains a string consisting of n characters β the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.
Output
Print a single integer β the number of bits in the cell which change their state after we add 1 to the cell.
Examples
Input
4
1100
Output
3
Input
4
1111
Output
4
Note
In the first sample the cell ends up with value 0010, in the second sample β with 0000.
Submitted Solution:
```
n = int(input())
ar = input()
ind = 0
s = 0
print(ar)
for i in ar:
if i == '1' and ind == 0:
s += 1
else:
ind = 1
if s < len(ar):
print(s + 1)
else:
print(len(ar))
```
No
| 92,146 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.
There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as <image>. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.
Find the matching between students and pseudonyms with the maximum quality.
Input
The first line contains number n (1 β€ n β€ 100 000) β the number of students in the summer school.
Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.
The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.
The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
Output
In the first line print the maximum possible quality of matching pseudonyms to students.
In the next n lines describe the optimal matching. Each line must have the form a b (1 β€ a, b β€ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.
The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
Examples
Input
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel
Output
11
4 1
2 5
1 3
5 2
3 4
Note
The first test from the statement the match looks as follows:
* bill β bilbo (lcp = 3)
* galya β galadriel (lcp = 3)
* gennady β gendalf (lcp = 3)
* toshik β torin (lcp = 2)
* boris β smaug (lcp = 0)
Tags: dfs and similar, strings, trees
Correct Solution:
```
import sys
class Node:
def __init__(self, d):
global nodes
self.ch = {}
self.a = [[], []]
self.d = d
nodes += [self]
nodes = []
pairs = []
res = 0
N = int(sys.stdin.readline())
_input = sys.stdin.readlines()
_input = [s[:-1] for s in _input]
A = [_input[:N], _input[N:]]
T = Node(0)
for i, l in enumerate(A):
for j, s in enumerate(l):
t = T
for c in s:
v = ord(c) - ord('a')
if not v in t.ch:
t.ch[v] = Node(t.d + 1)
t = t.ch[v]
t.a[i] += [j + 1]
for n in reversed(nodes):
for i in n.ch:
n.a[0] += n.ch[i].a[0]
n.a[1] += n.ch[i].a[1]
k = min(len(n.a[0]), len(n.a[1]))
for i in range(k):
pairs += [str(n.a[0][-1]) + ' ' + str(n.a[1][-1])]
n.a[0].pop()
n.a[1].pop()
res += n.d
print(res)
print('\n'.join(pairs))
```
| 92,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.
There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as <image>. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.
Find the matching between students and pseudonyms with the maximum quality.
Input
The first line contains number n (1 β€ n β€ 100 000) β the number of students in the summer school.
Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.
The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.
The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
Output
In the first line print the maximum possible quality of matching pseudonyms to students.
In the next n lines describe the optimal matching. Each line must have the form a b (1 β€ a, b β€ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.
The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
Examples
Input
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel
Output
11
4 1
2 5
1 3
5 2
3 4
Note
The first test from the statement the match looks as follows:
* bill β bilbo (lcp = 3)
* galya β galadriel (lcp = 3)
* gennady β gendalf (lcp = 3)
* toshik β torin (lcp = 2)
* boris β smaug (lcp = 0)
Tags: dfs and similar, strings, trees
Correct Solution:
```
import sys
SIGMA = 26
nodes = []
pairs = []
res = 0
class Node:
def __init__(self):
self.ch = {}
self.a = []
self.b = []
self.d = 0
def add(self, s, i):
t = self
for c in s:
v = ord(c) - ord('a')
if not v in t.ch:
t.ch[v] = Node()
t.ch[v].d = t.d + 1
nodes.append(t.ch[v])
t = t.ch[v]
t.a.append(i)
def inc(self, s, i):
t = self
for c in s:
v = ord(c) - ord('a')
if not v in t.ch:
break
t = t.ch[v]
t.b.append(i)
def solve(self):
global pairs
global res
for i in range(SIGMA):
if i in self.ch:
self.a.extend(self.ch[i].a)
self.b.extend(self.ch[i].b)
k = min(len(self.a), len(self.b))
for i in range(k):
pairs.append(str(self.a[-1]) + ' ' + str(self.b[-1]))
self.a.pop()
self.b.pop()
res += self.d
return res
sys.setrecursionlimit(2000000)
_input = sys.stdin.readlines()
_input = [s[:-1] for s in _input]
N = int(_input[0])
A = _input[1 : N + 1]
B = _input[N + 1 :]
T = Node()
nodes.append(T)
for i, s in enumerate(A):
T.add(s, i + 1)
for i, s in enumerate(B):
T.inc(s, i + 1)
for n in reversed(nodes):
n.solve()
print(res)
print('\n'.join(pairs))
```
| 92,148 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.
There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as <image>. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.
Find the matching between students and pseudonyms with the maximum quality.
Input
The first line contains number n (1 β€ n β€ 100 000) β the number of students in the summer school.
Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.
The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.
The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
Output
In the first line print the maximum possible quality of matching pseudonyms to students.
In the next n lines describe the optimal matching. Each line must have the form a b (1 β€ a, b β€ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.
The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
Examples
Input
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel
Output
11
4 1
2 5
1 3
5 2
3 4
Note
The first test from the statement the match looks as follows:
* bill β bilbo (lcp = 3)
* galya β galadriel (lcp = 3)
* gennady β gendalf (lcp = 3)
* toshik β torin (lcp = 2)
* boris β smaug (lcp = 0)
Tags: dfs and similar, strings, trees
Correct Solution:
```
import sys
SIGMA = 26
nodes = []
pairs = []
res = 0
class Node:
def __init__(self):
self.ch = {}
self.a = []
self.b = []
self.d = 0
def add(self, s, i):
t = self
for c in s:
v = ord(c) - ord('a')
if not v in t.ch:
t.ch[v] = Node()
t.ch[v].d = t.d + 1
nodes.append(t.ch[v])
t = t.ch[v]
t.a.append(i)
def inc(self, s, i):
t = self
for c in s:
v = ord(c) - ord('a')
if not v in t.ch:
break
t = t.ch[v]
t.b.append(i)
def solve(self):
global pairs
global res
for i in range(SIGMA):
if i in self.ch:
self.a.extend(self.ch[i].a)
self.b.extend(self.ch[i].b)
k = min(len(self.a), len(self.b))
for i in range(k):
pairs.append(str(self.a[-1]) + ' ' + str(self.b[-1]))
self.a.pop()
self.b.pop()
res += self.d
return res
_input = sys.stdin.readlines()
_input = [s[:-1] for s in _input]
N = int(_input[0])
A = _input[1 : N + 1]
B = _input[N + 1 :]
T = Node()
nodes.append(T)
for i, s in enumerate(A):
T.add(s, i + 1)
for i, s in enumerate(B):
T.inc(s, i + 1)
for n in reversed(nodes):
n.solve()
print(res)
print('\n'.join(pairs))
```
| 92,149 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.
There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as <image>. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.
Find the matching between students and pseudonyms with the maximum quality.
Input
The first line contains number n (1 β€ n β€ 100 000) β the number of students in the summer school.
Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.
The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.
The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
Output
In the first line print the maximum possible quality of matching pseudonyms to students.
In the next n lines describe the optimal matching. Each line must have the form a b (1 β€ a, b β€ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.
The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
Examples
Input
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel
Output
11
4 1
2 5
1 3
5 2
3 4
Note
The first test from the statement the match looks as follows:
* bill β bilbo (lcp = 3)
* galya β galadriel (lcp = 3)
* gennady β gendalf (lcp = 3)
* toshik β torin (lcp = 2)
* boris β smaug (lcp = 0)
Submitted Solution:
```
s = int(input())
n = str(input())
nol = n.count("0")
satu = n.count("1")
while True:
if satu == 0 or nol ==0:
break
nol -= 1
satu -=1
if satu == 0 or nol == 0:
break
if nol == 0:
print(satu)
elif satu ==0 :
print(nol)
print (nol)
else :
print("0")
```
No
| 92,150 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.
There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as <image>. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.
Find the matching between students and pseudonyms with the maximum quality.
Input
The first line contains number n (1 β€ n β€ 100 000) β the number of students in the summer school.
Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.
The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.
The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
Output
In the first line print the maximum possible quality of matching pseudonyms to students.
In the next n lines describe the optimal matching. Each line must have the form a b (1 β€ a, b β€ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.
The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
Examples
Input
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel
Output
11
4 1
2 5
1 3
5 2
3 4
Note
The first test from the statement the match looks as follows:
* bill β bilbo (lcp = 3)
* galya β galadriel (lcp = 3)
* gennady β gendalf (lcp = 3)
* toshik β torin (lcp = 2)
* boris β smaug (lcp = 0)
Submitted Solution:
```
n=int(input())
s=input()
one=s.count('1')
zero=s.count('0')
k=min(one,zero)
k*=2
print(n-k)
```
No
| 92,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.
There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as <image>. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.
Find the matching between students and pseudonyms with the maximum quality.
Input
The first line contains number n (1 β€ n β€ 100 000) β the number of students in the summer school.
Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.
The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.
The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
Output
In the first line print the maximum possible quality of matching pseudonyms to students.
In the next n lines describe the optimal matching. Each line must have the form a b (1 β€ a, b β€ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.
The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
Examples
Input
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel
Output
11
4 1
2 5
1 3
5 2
3 4
Note
The first test from the statement the match looks as follows:
* bill β bilbo (lcp = 3)
* galya β galadriel (lcp = 3)
* gennady β gendalf (lcp = 3)
* toshik β torin (lcp = 2)
* boris β smaug (lcp = 0)
Submitted Solution:
```
class Tree():
def __init__(self, value, index):
self.value = value
self.left = None
self.right = None
self.count = 1
self.index = index
def insert(self, value, index):
if value < self.value:
if self.left is None:
self.left = Tree(value, index)
return
self.left.insert(value, index)
if value >= self.value:
if self.right is None:
self.right = Tree(value, index)
return
self.right.insert(value, index)
@staticmethod
def largest_common_prefix(str1, str2):
common = 0
for i in range(len(str1)):
if str1[i] == str2[i]:
common += 1
else: return common
return len(str1)
def lnr(self):
if self.left is not None:
self.left.lnr()
print (self.value, self.index)
if self.right is not None:
self.right.lnr()
def search(self, value):
root_prefix = self.largest_common_prefix(self.value, value)
if value == self.value:
if self.count == 1:
self.count -= 1
return len(value), self.index
else:
return self.right.search(value)
if value > self.value: #kiem tra ben phai
if self.right: #coi co node phai khong
right_prefix = self.largest_common_prefix(self.right.value, value)
if root_prefix > right_prefix:
if self.count > 0:
self.count -= 1
return root_prefix, self.index
else:
return 0, 0
else:
return self.right.search(value)
else: #khong co thi thang similar nhat la thang root
if self.count > 0:
self.count -= 1
return root_prefix, self.index
else:
return 0, 0
if value < self.value: #kiem tra ben trai
if self.left: #coi co node trai khong
left_prefix = self.largest_common_prefix(self.left.value, value)
if root_prefix > left_prefix:
if self.count > 0:
self.count -= 1
return root_prefix, self.index
else:
return 0, 0
else:
return self.left.search(value)
else:
if self.count > 0:
self.count -= 1
return root_prefix, self.index
else:
return 0, 0
# @staticmethod
def count_nhanh(self):
if self.count == 1:
return True
if self.left:
return self.left.count_nhanh()
if self.right:
return self.right.count_nhanh()
return False
def search_zero(self, value):
if self.right:
check_right = self.right.count_nhanh()
else:
check_right = False
if self.left:
check_left = self.left.count_nhanh()
else:
check_left = False
if check_left == check_right == False and self.count == 1:
return self.index
if value > self.value:
if check_right == True:
return self.right.search_zero(value)
else:
return self.left.search_zero(value)
if value < self.value:
if check_left == True:
return self.left.search_zero(value)
else:
return self.right.search_zero(value)
if __name__ == "__main__":
n = int(input())
tree = Tree(input(), 1)
for i in range(n-1):
tree.insert(input(), i+2)
save = {}
queue = []
for i in range(n):
pseudonyms = input()
value, index = tree.search(pseudonyms)
if value == 0:
queue.append([pseudonyms, i+1])
else:
save["{} {}".format(index, i+1)] = value
for remain in queue:
index = tree.search_zero(remain[0])
save["{} {}".format(index, remain[1])] = 0
#return output
print (sum(save.values()))
for i,v in enumerate(save):
if i % 2 == 0:
print (v)
else:
print (v[::-1])
```
No
| 92,152 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.
There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as <image>. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.
Find the matching between students and pseudonyms with the maximum quality.
Input
The first line contains number n (1 β€ n β€ 100 000) β the number of students in the summer school.
Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.
The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.
The total length of all the names and pseudonyms doesn't exceed 800 000 characters.
Output
In the first line print the maximum possible quality of matching pseudonyms to students.
In the next n lines describe the optimal matching. Each line must have the form a b (1 β€ a, b β€ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.
The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.
Examples
Input
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel
Output
11
4 1
2 5
1 3
5 2
3 4
Note
The first test from the statement the match looks as follows:
* bill β bilbo (lcp = 3)
* galya β galadriel (lcp = 3)
* gennady β gendalf (lcp = 3)
* toshik β torin (lcp = 2)
* boris β smaug (lcp = 0)
Submitted Solution:
```
n = int(input())
def lcp(fStr, sStr):
maxx = 0
string = fStr[0]
if string == fStr[0]:
maxx += 1
for i in range(1, len(fStr)):
string += fStr[i]
if string in sStr:
maxx += 1
else:
return 0
return maxx
names = []
psevd = []
ans = []
ansNum = 0
for _ in range(n):
names.append(str(input()))
for _ in range(n):
psevd.append(str(input()))
for psev in psevd:
maxLen = 0
nameIndex = 0
psevdInvex = psevd.index(psev)
num = 0
for name in names:
if name != "":
num = lcp(name, psev)
print(name, psev, num)
if num >= maxLen:
maxLen = num
nameIndex = names.index(name)
ans.append([nameIndex + 1, psevdInvex + 1])
names[nameIndex] = ""
ansNum += maxLen
print(ansNum - 1)
for elem in ans:
print(elem[0], elem[1])
"""
5
gennady
galya
boris
bill
toshik
bilbo
torin
gendalf
smaug
galadriel
"""
```
No
| 92,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While Duff was resting in the beach, she accidentally found a strange array b0, b1, ..., bl - 1 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0, ..., an - 1 that b can be build from a with formula: bi = ai mod n where a mod b denoted the remainder of dividing a by b.
<image>
Duff is so curious, she wants to know the number of subsequences of b like bi1, bi2, ..., bix (0 β€ i1 < i2 < ... < ix < l), such that:
* 1 β€ x β€ k
* For each 1 β€ j β€ x - 1, <image>
* For each 1 β€ j β€ x - 1, bij β€ bij + 1. i.e this subsequence is non-decreasing.
Since this number can be very large, she want to know it modulo 109 + 7.
Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.
Input
The first line of input contains three integers, n, l and k (1 β€ n, k, n Γ k β€ 106 and 1 β€ l β€ 1018).
The second line contains n space separated integers, a0, a1, ..., an - 1 (1 β€ ai β€ 109 for each 0 β€ i β€ n - 1).
Output
Print the answer modulo 1 000 000 007 in one line.
Examples
Input
3 5 3
5 9 1
Output
10
Input
5 10 3
1 2 3 4 5
Output
25
Note
In the first sample case, <image>. So all such sequences are: <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image> and <image>.
Submitted Solution:
```
import sys
readline = sys.stdin.readline
MOD = 10**9+7
def frac(limit):
frac = [1]*limit
for i in range(2,limit):
frac[i] = i * frac[i-1]%MOD
fraci = [None]*limit
fraci[-1] = pow(frac[-1], MOD -2, MOD)
for i in range(-2, -limit-1, -1):
fraci[i] = fraci[i+1] * (limit + i + 1) % MOD
return frac, fraci
frac, fraci = frac(1341398)
def comb(a, b):
if not a >= b >= 0:
return 0
return frac[a]*fraci[b]*fraci[a-b]%MOD
def compress(L):
L2 = list(set(L))
L2.sort()
C = {v : k for k, v in enumerate(L2)}
return L2, C
N, L, K = map(int, readline().split())
A = list(map(int, readline().split()))
_, Ca = compress(A)
A = [Ca[a] for a in A]
dp1 = [1]*N
R = (L//N)
if N <= L:
ans = R*N
D = [R]*N
else:
ans = 0
D = [0]*N
cr = R
for r in range(2, min(R, K)+1):
da = [0]*N
for j in range(N):
a = A[j]
da[a] = (da[a] + dp1[j])%MOD
for a in range(1, N):
da[a] = (da[a] + da[a-1])%MOD
cr = cr*(R-r+1)*fraci[r]*frac[r-1]%MOD
for j in range(N):
a = A[j]
dp1[j] = da[a]
ans = (ans + cr*dp1[j])%MOD
if r < K:
D[j] = (D[j] + cr*dp1[j])%MOD
da = [0]*N
for j in range(N):
a = A[j]
da[a] = (da[a] + D[j])%MOD
for a in range(1, N):
da[a] = (da[a] + da[a-1])%MOD
for j in range(L%N):
a = A[j]
ans = (ans+da[a])%MOD
ans = (ans + L%N)%MOD
print(ans)
```
No
| 92,154 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While Duff was resting in the beach, she accidentally found a strange array b0, b1, ..., bl - 1 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0, ..., an - 1 that b can be build from a with formula: bi = ai mod n where a mod b denoted the remainder of dividing a by b.
<image>
Duff is so curious, she wants to know the number of subsequences of b like bi1, bi2, ..., bix (0 β€ i1 < i2 < ... < ix < l), such that:
* 1 β€ x β€ k
* For each 1 β€ j β€ x - 1, <image>
* For each 1 β€ j β€ x - 1, bij β€ bij + 1. i.e this subsequence is non-decreasing.
Since this number can be very large, she want to know it modulo 109 + 7.
Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.
Input
The first line of input contains three integers, n, l and k (1 β€ n, k, n Γ k β€ 106 and 1 β€ l β€ 1018).
The second line contains n space separated integers, a0, a1, ..., an - 1 (1 β€ ai β€ 109 for each 0 β€ i β€ n - 1).
Output
Print the answer modulo 1 000 000 007 in one line.
Examples
Input
3 5 3
5 9 1
Output
10
Input
5 10 3
1 2 3 4 5
Output
25
Note
In the first sample case, <image>. So all such sequences are: <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image> and <image>.
Submitted Solution:
```
#import sys
from operator import itemgetter
#sys.stdin = open('input.txt')
MOD = int(1e09+7)
n, l, k = map(int, input().split())
a = [[int(x), False] for x in input().split()]
rem = (l - 1)%n + 1
i = 0
while i < rem:
a[i][1] = True
i += 1
a.sort(key=itemgetter(0))
ans = 0
sums = []
k2 = (l - 1)//n + 1
k1 = min(k, k2)
cur = 0
i = 0
while i < min(l, n):
if a[i][0] != cur:
sums.append([0, False])
cur = a[i][0]
if a[i][1]:
sums[len(sums) - 1][1] = True
i += 1
len1 = len(sums)
sums[0][0] = 1
i = 1
while i <= k1:
not_last = i != k1
if sums[0][1]:
ans = (ans + k2 - i + 1) % MOD
elif not_last:
ans = (ans + k2 - i) % MOD
j = 1
while j < len1:
sums[j][0] = (sums[j][0] + sums[j - 1][0]) % MOD
if sums[j][1]:
ans = (ans + sums[j][0]*(k2 - i + 1)) % MOD
elif not_last:
ans = (ans + sums[j][0]*(k2 - 1)) % MOD
j += 1
i += 1
print(ans)
```
No
| 92,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While Duff was resting in the beach, she accidentally found a strange array b0, b1, ..., bl - 1 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0, ..., an - 1 that b can be build from a with formula: bi = ai mod n where a mod b denoted the remainder of dividing a by b.
<image>
Duff is so curious, she wants to know the number of subsequences of b like bi1, bi2, ..., bix (0 β€ i1 < i2 < ... < ix < l), such that:
* 1 β€ x β€ k
* For each 1 β€ j β€ x - 1, <image>
* For each 1 β€ j β€ x - 1, bij β€ bij + 1. i.e this subsequence is non-decreasing.
Since this number can be very large, she want to know it modulo 109 + 7.
Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.
Input
The first line of input contains three integers, n, l and k (1 β€ n, k, n Γ k β€ 106 and 1 β€ l β€ 1018).
The second line contains n space separated integers, a0, a1, ..., an - 1 (1 β€ ai β€ 109 for each 0 β€ i β€ n - 1).
Output
Print the answer modulo 1 000 000 007 in one line.
Examples
Input
3 5 3
5 9 1
Output
10
Input
5 10 3
1 2 3 4 5
Output
25
Note
In the first sample case, <image>. So all such sequences are: <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image> and <image>.
Submitted Solution:
```
import sys
readline = sys.stdin.readline
MOD = 10**9+7
def frac(limit):
frac = [1]*limit
for i in range(2,limit):
frac[i] = i * frac[i-1]%MOD
fraci = [None]*limit
fraci[-1] = pow(frac[-1], MOD -2, MOD)
for i in range(-2, -limit-1, -1):
fraci[i] = fraci[i+1] * (limit + i + 1) % MOD
return frac, fraci
frac, fraci = frac(1341398)
def comb(a, b):
if not a >= b >= 0:
return 0
return frac[a]*fraci[b]*fraci[a-b]%MOD
def compress(L):
L2 = list(set(L))
L2.sort()
C = {v : k for k, v in enumerate(L2)}
return L2, C
N, L, K = map(int, readline().split())
A = list(map(int, readline().split()))
_, Ca = compress(A)
A = [Ca[a] for a in A]
R = (L//N)
if R == 0:
print(L%MOD)
elif N >= L:
print(L%MOD)
else:
ans = L%MOD
D = [R]*N
dp1 = [1]*N
cr = R
for r in range(2, min(R, K)+1):
da = [0]*N
for j in range(N):
a = A[j]
da[a] = (da[a] + dp1[j])%MOD
for a in range(1, N):
da[a] = (da[a] + da[a-1])%MOD
cr = cr*(R-r+1)*fraci[r]*frac[r-1]%MOD
for j in range(N):
a = A[j]
dp1[j] = da[a]
ans = (ans + cr*dp1[j])%MOD
if r < K:
D[j] = (D[j] + cr*dp1[j])%MOD
if K > 1:
da = [0]*N
for j in range(N):
a = A[j]
da[a] = (da[a] + D[j])%MOD
for a in range(1, N):
da[a] = (da[a] + da[a-1])%MOD
for j in range(L%N):
a = A[j]
ans = (ans+da[a])%MOD
print(ans)
```
No
| 92,156 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While Duff was resting in the beach, she accidentally found a strange array b0, b1, ..., bl - 1 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0, ..., an - 1 that b can be build from a with formula: bi = ai mod n where a mod b denoted the remainder of dividing a by b.
<image>
Duff is so curious, she wants to know the number of subsequences of b like bi1, bi2, ..., bix (0 β€ i1 < i2 < ... < ix < l), such that:
* 1 β€ x β€ k
* For each 1 β€ j β€ x - 1, <image>
* For each 1 β€ j β€ x - 1, bij β€ bij + 1. i.e this subsequence is non-decreasing.
Since this number can be very large, she want to know it modulo 109 + 7.
Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.
Input
The first line of input contains three integers, n, l and k (1 β€ n, k, n Γ k β€ 106 and 1 β€ l β€ 1018).
The second line contains n space separated integers, a0, a1, ..., an - 1 (1 β€ ai β€ 109 for each 0 β€ i β€ n - 1).
Output
Print the answer modulo 1 000 000 007 in one line.
Examples
Input
3 5 3
5 9 1
Output
10
Input
5 10 3
1 2 3 4 5
Output
25
Note
In the first sample case, <image>. So all such sequences are: <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image> and <image>.
Submitted Solution:
```
import sys
readline = sys.stdin.readline
MOD = 10**9+7
def frac(limit):
frac = [1]*limit
for i in range(2,limit):
frac[i] = i * frac[i-1]%MOD
fraci = [None]*limit
fraci[-1] = pow(frac[-1], MOD -2, MOD)
for i in range(-2, -limit-1, -1):
fraci[i] = fraci[i+1] * (limit + i + 1) % MOD
return frac, fraci
frac, fraci = frac(1341398)
def comb(a, b):
if not a >= b >= 0:
return 0
return frac[a]*fraci[b]*fraci[a-b]%MOD
def compress(L):
L2 = list(set(L))
L2.sort()
C = {v : k for k, v in enumerate(L2)}
return L2, C
N, L, K = map(int, readline().split())
A = list(map(int, readline().split()))
_, Ca = compress(A)
A = [Ca[a] for a in A]
dp1 = [1]*N
R = (L//N)
if N <= L:
ans = R*N
D = [1]*N
else:
ans = 0
D = [0]*N
cr = R
for r in range(2, min(R, K)+1):
da = [0]*N
for j in range(N):
a = A[j]
da[a] = (da[a] + dp1[j])%MOD
for a in range(1, N):
da[a] = (da[a] + da[a-1])%MOD
for j in range(N):
a = A[j]
dp1[j] = da[a]
cr = cr*(R-r+1)*fraci[r]*frac[r-1]%MOD
for i in range(N):
d1 = dp1[i]
c = cr*d1%MOD
ans = (ans + c)%MOD
if r < K:
D[i] = (D[i] + c)%MOD
da = [0]*N
for j in range(N):
a = A[j]
da[a] = (da[a] + D[j])%MOD
for a in range(1, N):
da[a] = (da[a] + da[a-1])%MOD
for j in range(L%N):
a = A[j]
ans = (ans+da[a])%MOD
ans = (ans + L%N)%MOD
print(ans)
```
No
| 92,157 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Tags: binary search, greedy, two pointers
Correct Solution:
```
#### IMPORTANT LIBRARY ####
############################
### DO NOT USE import random --> 250ms to load the library
############################
### In case of extra libraries: https://github.com/cheran-senthil/PyRival
######################
####### IMPORT #######
######################
from functools import cmp_to_key
from collections import deque, Counter
from heapq import heappush, heappop
from math import log, ceil
######################
#### STANDARD I/O ####
######################
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def print(*args, **kwargs):
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
def inp():
return sys.stdin.readline().rstrip("\r\n") # for fast input
def ii():
return int(inp())
def si():
return str(inp())
def li(lag = 0):
l = list(map(int, inp().split()))
if lag != 0:
for i in range(len(l)):
l[i] += lag
return l
def mi(lag = 0):
matrix = list()
for i in range(n):
matrix.append(li(lag))
return matrix
def lsi(): #string list
return list(map(str, inp().split()))
def print_list(lista, space = " "):
print(space.join(map(str, lista)))
######################
### BISECT METHODS ###
######################
def bisect_left(a, x):
"""i tale che a[i] >= x e a[i-1] < x"""
left = 0
right = len(a)
while left < right:
mid = (left+right)//2
if a[mid] < x:
left = mid+1
else:
right = mid
return left
def bisect_right(a, x):
"""i tale che a[i] > x e a[i-1] <= x"""
left = 0
right = len(a)
while left < right:
mid = (left+right)//2
if a[mid] > x:
right = mid
else:
left = mid+1
return left
def bisect_elements(a, x):
"""elementi pari a x nell'Γ‘rray sortato"""
return bisect_right(a, x) - bisect_left(a, x)
######################
### MOD OPERATION ####
######################
MOD = 10**9 + 7
maxN = 5
FACT = [0] * maxN
INV_FACT = [0] * maxN
def add(x, y):
return (x+y) % MOD
def multiply(x, y):
return (x*y) % MOD
def power(x, y):
if y == 0:
return 1
elif y % 2:
return multiply(x, power(x, y-1))
else:
a = power(x, y//2)
return multiply(a, a)
def inverse(x):
return power(x, MOD-2)
def divide(x, y):
return multiply(x, inverse(y))
def allFactorials():
FACT[0] = 1
for i in range(1, maxN):
FACT[i] = multiply(i, FACT[i-1])
def inverseFactorials():
n = len(INV_FACT)
INV_FACT[n-1] = inverse(FACT[n-1])
for i in range(n-2, -1, -1):
INV_FACT[i] = multiply(INV_FACT[i+1], i+1)
def coeffBinom(n, k):
if n < k:
return 0
return multiply(FACT[n], multiply(INV_FACT[k], INV_FACT[n-k]))
######################
#### GRAPH ALGOS #####
######################
# ZERO BASED GRAPH
def create_graph(n, m, undirected = 1, unweighted = 1):
graph = [[] for i in range(n)]
if unweighted:
for i in range(m):
[x, y] = li(lag = -1)
graph[x].append(y)
if undirected:
graph[y].append(x)
else:
for i in range(m):
[x, y, w] = li(lag = -1)
w += 1
graph[x].append([y,w])
if undirected:
graph[y].append([x,w])
return graph
def create_tree(n, unweighted = 1):
children = [[] for i in range(n)]
if unweighted:
for i in range(n-1):
[x, y] = li(lag = -1)
children[x].append(y)
children[y].append(x)
else:
for i in range(n-1):
[x, y, w] = li(lag = -1)
w += 1
children[x].append([y, w])
children[y].append([x, w])
return children
def dist(tree, n, A, B = -1):
s = [[A, 0]]
massimo, massimo_nodo = 0, 0
distanza = -1
v = [-1] * n
while s:
el, dis = s.pop()
if dis > massimo:
massimo = dis
massimo_nodo = el
if el == B:
distanza = dis
for child in tree[el]:
if v[child] == -1:
v[child] = 1
s.append([child, dis+1])
return massimo, massimo_nodo, distanza
def diameter(tree):
_, foglia, _ = dist(tree, n, 0)
diam, _, _ = dist(tree, n, foglia)
return diam
def dfs(graph, n, A):
v = [-1] * n
s = [[A, 0]]
v[A] = 0
while s:
el, dis = s.pop()
for child in graph[el]:
if v[child] == -1:
v[child] = dis + 1
s.append([child, dis + 1])
return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges
def bfs(graph, n, A):
v = [-1] * n
s = deque()
s.append([A, 0])
v[A] = 0
while s:
el, dis = s.popleft()
for child in graph[el]:
if v[child] == -1:
v[child] = dis + 1
s.append([child, dis + 1])
return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges
#FROM A GIVEN ROOT, RECOVER THE STRUCTURE
def parents_children_root_unrooted_tree(tree, n, root = 0):
q = deque()
visited = [0] * n
parent = [-1] * n
children = [[] for i in range(n)]
q.append(root)
while q:
all_done = 1
visited[q[0]] = 1
for child in tree[q[0]]:
if not visited[child]:
all_done = 0
q.appendleft(child)
if all_done:
for child in tree[q[0]]:
if parent[child] == -1:
parent[q[0]] = child
children[child].append(q[0])
q.popleft()
return parent, children
# CALCULATING LONGEST PATH FOR ALL THE NODES
def all_longest_path_passing_from_node(parent, children, n):
q = deque()
visited = [len(children[i]) for i in range(n)]
downwards = [[0,0] for i in range(n)]
upward = [1] * n
longest_path = [1] * n
for i in range(n):
if not visited[i]:
q.append(i)
downwards[i] = [1,0]
while q:
node = q.popleft()
if parent[node] != -1:
visited[parent[node]] -= 1
if not visited[parent[node]]:
q.append(parent[node])
else:
root = node
for child in children[node]:
downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse = True)[0:2]
s = [node]
while s:
node = s.pop()
if parent[node] != -1:
if downwards[parent[node]][0] == downwards[node][0] + 1:
upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1])
else:
upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0])
longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1
for child in children[node]:
s.append(child)
return longest_path
### TBD SUCCESSOR GRAPH 7.5
### TBD TREE QUERIES 10.2 da 2 a 4
### TBD ADVANCED TREE 10.3
### TBD GRAPHS AND MATRICES 11.3.3 e 11.4.3 e 11.5.3 (ON GAMES)
######################
## END OF LIBRARIES ##
######################
n,m,k,s = li()
cd = li()
ce = li()
d = list()
e = list()
for i in range(m):
t, v = li()
if t == 1:
d.append([v,i])
else:
e.append([v,i])
d.sort()
e.sort()
prd = [0 for i in range(len(d)+1)]
pre = [0 for i in range(len(e)+1)]
for i in range(max(len(d), len(e))):
if i < len(d):
prd[i+1] = prd[i] + d[i][0]
if i < len(e):
pre[i+1] = pre[i] + e[i][0]
md = list()
me = list()
mind = float("inf")
didx = -1
mine = float("inf")
eidx = -1
for i in range(n):
if cd[i] < mind:
mind = cd[i]
didx = i
if ce[i] < mine:
mine = ce[i]
eidx = i
md.append([mind, didx])
me.append([mine, eidx])
left = 0
right = n
compro = [-1, -1,-1,-1,-1] # min giorno, giorno doll, num doll, giorno eu, num eu
flag = False
while left < right:
mid = (left+right)//2
currd, idxd = md[mid]
curre, idxe = me[mid]
for i in range(k+1):
if i < len(prd) and k-i < len(pre):
amount = currd*prd[i]+curre*pre[k-i]
if amount <= s:
flag = True
compro = [mid+1, idxd+1,i,idxe+1,k-i]
if flag == True:
right = mid
else:
left = mid+1
flag = False
if compro[0] != -1:
print(compro[0])
for i in range(compro[2]):
print_list([d[i][1]+1, compro[1]])
for j in range(compro[4]):
print_list([e[j][1]+1, compro[3]])
else:
print(-1)
```
| 92,158 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Tags: binary search, greedy, two pointers
Correct Solution:
```
from itertools import accumulate
import sys
def solve(f, g):
n, m, k, s = [int(x) for x in f.readline().split()]
a_price = [(int(x), i+1) for i, x in enumerate(f.readline().split())]
b_price = [(int(x), i+1) for i, x in enumerate(f.readline().split())]
a_gadgets = []
b_gadgets = []
for i, line in enumerate(f):
t, price = [int(x) for x in line.split()]
if t == 1:
a_gadgets.append((price, i + 1))
else:
b_gadgets.append((price, i + 1))
a_gadgets.sort()
b_gadgets.sort()
prefix_a = [0] + list(accumulate(gadget[0] for gadget in a_gadgets))
prefix_b = [0] + list(accumulate(gadget[0] for gadget in b_gadgets))
la = min(k, len(a_gadgets))
lb = min(k, len(b_gadgets))
min_price_for_k = [(prefix_a[i], prefix_b[k - i], i) for i in range(k-lb, la+1)]
for i in range(1, n):
a_price[i] = min(a_price[i], a_price[i-1])
b_price[i] = min(b_price[i], b_price[i-1])
def expence(day):
return lambda x: a_price[day][0]*x[0] + b_price[day][0]*x[1]
x, y = 0, n-1
while x <= y-1:
day = (x + y) // 2
min_cost = min(min_price_for_k, key = expence(day))
if expence(day)(min_cost) > s:
x = day+1
else:
y = day
min_cost = min(min_price_for_k, key = expence(x))
if expence(x)(min_cost) > s:
g.write('-1\n')
else:
g.write(str(x+1) + '\n')
i1 = min_cost[-1]
A, B = ' ' + str(a_price[x][1]) + '\n', ' ' + str(b_price[x][1]) + '\n'
for i in range(i1):
g.write(str(a_gadgets[i][1]) + A)
for i in range(k - i1):
g.write(str(b_gadgets[i][1]) + B)
solve(sys.stdin, sys.stdout)
```
| 92,159 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Tags: binary search, greedy, two pointers
Correct Solution:
```
from sys import stdin, stdout
def ints():
return [int(x) for x in stdin.readline().split()]
n, m, k, s = ints()
a = ints()
b = ints()
d_gad = [];
p_gad = [];
for i in range(m):
t, c = ints()
if t == 1:
d_gad.append([c, i + 1])
else:
p_gad.append([c, i + 1])
d_gad.sort()
p_gad.sort()
mn_dol = [0] * n
mn_pou = [0] * n
day_mn_dol = [1] * n
day_mn_pou = [1] * n
mn_dol[0] = a[0]
mn_pou[0] = b[0]
for i in range(1, n):
mn_dol[i] = min(mn_dol[i - 1], a[i])
day_mn_dol[i] = (i + 1 if mn_dol[i] == a[i] else day_mn_dol[i - 1])
for i in range(1, n):
mn_pou[i] = min(mn_pou[i - 1], b[i])
day_mn_pou[i] = (i + 1 if mn_pou[i] == b[i] else day_mn_pou[i - 1])
def Check(x):
i = 0
j = 0
mnd = mn_dol[x]
mnp = mn_pou[x]
SuM = 0
for u in range(k):
if i == len(d_gad):
SuM += p_gad[j][0] * mnp
j += 1
elif j == len(p_gad):
SuM += d_gad[i][0] * mnd
i += 1
else:
p1 = d_gad[i][0] * mnd
p2 = p_gad[j][0] * mnp
if p1 <= p2:
SuM += p1
i += 1
else:
SuM += p2
j += 1
if SuM > s:
return False
return True
def Print_Ans(x):
i = 0
j = 0
mnd = mn_dol[x]
mnp = mn_pou[x]
dayd = day_mn_dol[x]
dayp = day_mn_pou[x]
ans = []
for u in range(k):
if i == len(d_gad):
ans.append(str(p_gad[j][1]) + ' ' + str(dayp))
j += 1
elif j == len(p_gad):
ans.append(str(d_gad[i][1]) + ' ' + str(dayd))
i += 1
else:
if d_gad[i][0] * mnd <= p_gad[j][0] * mnp:
ans.append(str(d_gad[i][1]) + ' ' + str(dayd))
i += 1
else:
ans.append(str(p_gad[j][1]) + ' ' + str(dayp))
j += 1
stdout.write('\n'.join(ans))
if not Check(n - 1):
print(-1)
else:
p = 0
q = n - 1
while p < q:
mid = (p + q) // 2
if Check(mid):
q = mid
else:
p = mid + 1
stdout.write(f'{p + 1}\n')
Print_Ans(p)
```
| 92,160 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Tags: binary search, greedy, two pointers
Correct Solution:
```
import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = 'x' in file.mode or 'w' in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b'\n') + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
import heapq
def can_do(check_days, n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val):
# get low in the range 1 -> check_days
min_d = prefx_min_d_val[check_days][0]
min_p = prefx_min_p_val[check_days][0]
min_d_idx = prefx_min_d_val[check_days][1]
min_p_idx = prefx_min_p_val[check_days][1]
vals_d = [0] * (k + 1)
vals_p = [0] * (k + 1)
for i in range(1, k + 1):
# print(i)
if i <= len(d_gadgets):
vals_d[i] = ((min_d * d_gadgets[i - 1][0]) + vals_d[i - 1])
if i <= len(p_gadgets):
vals_p[i] = ((min_p * p_gadgets[i - 1][0]) + vals_p[i - 1])
for x in range(k + 1):
# x from dollar and k - x from pounds
if x <= len(d_gadgets) and k - x <= len(p_gadgets):
if ((x > 0 and vals_d[x] > 0) or x == 0) \
and ((k - x > 0 and vals_p[k - x] > 0) or k - x == 0):
total = vals_d[x] + vals_p[k - x]
if total <= s:
res = []
for i in range(x):
res.append((d_gadgets[i][1], min_d_idx))
for i in range(k - x):
res.append((p_gadgets[i][1], min_p_idx))
return (True, res)
return (False, [])
def check(n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val):
lo = 0
hi = n
res = -1
while lo <= hi:
mid = lo + (hi - lo) // 2
if can_do(mid, n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val)[0]:
res = mid
hi = mid - 1
else:
lo = mid + 1
if res == -1:
return res, []
return res, can_do(res, n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val)[1]
def solve():
n, m, k, s = map(int, input().split())
d_vals = list(map(int, input().split()))
d_vals.insert(0, float("inf"))
p_vals = list(map(int, input().split()))
p_vals.insert(0, float("inf"))
d_gadgets = []
p_gadgets = []
for i in range(m):
t, c = map(int, input().split())
if t == 1:
d_gadgets.append((c, i + 1))
else:
p_gadgets.append((c, i + 1))
prefx_min_d_val = [(d_vals[0], 0)] * len(d_vals)
for i in range(1, len(d_vals)):
if prefx_min_d_val[i - 1][0] < d_vals[i]:
prefx_min_d_val[i] = (prefx_min_d_val[i - 1][0], prefx_min_d_val[i - 1][1])
else:
prefx_min_d_val[i] = (d_vals[i], i)
prefx_min_p_val = [(p_vals[0], 0)] * len(p_vals)
for i in range(1, len(p_vals)):
if prefx_min_p_val[i - 1][0] < p_vals[i]:
prefx_min_p_val[i] = (prefx_min_p_val[i - 1][0], prefx_min_p_val[i - 1][1])
else:
prefx_min_p_val[i] = (p_vals[i], i)
d_gadgets.sort(key=lambda x: x[0])
p_gadgets.sort(key=lambda x: x[0])
# print(prefx_min_d_val)
# print(prefx_min_p_val)
# print(d_gadgets)
# print(p_gadgets)
# can_do(9, n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val)
res, r = check(n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val)
cout<<res<<endl
for p in r:
cout<<p[0]<<" "<<p[1]<<endl
def main():
solve()
if __name__ == "__main__":
main()
```
| 92,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Tags: binary search, greedy, two pointers
Correct Solution:
```
import sys
from itertools import accumulate
n, m, k, s = map(int, input().split())
_rate = [list(map(int, input().split())), list(map(int, input().split()))]
rate = [list(accumulate(_rate[0], min)), list(accumulate(_rate[1], min))]
items = [[[0, -1]], [[0, -1]]]
for i in range(m):
t, c = map(int, sys.stdin.readline().split())
items[t-1].append([c, i+1])
items[0].sort()
items[1].sort()
for i in range(2):
for j in range(1, len(items[i])):
items[i][j][0] += items[i][j-1][0]
ok, ng = n, -1
ans_size = [0, 0]
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
cnt_1 = min(len(items[0])-1, k)
cnt_2 = k - cnt_1
while cnt_1 >= 0 and cnt_2 < len(items[1]):
dollers = items[0][cnt_1][0]
pounds = items[1][cnt_2][0]
if dollers * rate[0][mid] + pounds * rate[1][mid] <= s:
ok = mid
ans_size = [cnt_1, cnt_2]
break
cnt_1 -= 1
cnt_2 += 1
else:
ng = mid
if ok < n:
print(ok+1)
for i in range(2):
day = 0
for j in range(0, n):
if _rate[i][j] == rate[i][ok]:
day = j+1
break
for j in range(1, ans_size[i]+1):
print(items[i][j][1], day)
else:
print(-1)
```
| 92,162 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Tags: binary search, greedy, two pointers
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=-10**9, func=lambda a, b: max(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m,k,s=map(int,input().split())
w=list(map(int,input().split()))
w1=list(map(int,input().split()))
mi=[0]*n
mi1=[0]*n
mi[0]=w[0]
mi1[0]=w1[0]
d=[]
p=[]
for i in range(m):
a,b=map(int,input().split())
if a==1:
d.append((b,i))
else:
p.append((b,i))
d.sort()
p.sort()
su=[0]*(len(d)+1)
su1=[0]*(len(p)+1)
for i in range(len(d)):
su[i+1]=su[i]+d[i][0]
for i in range(len(p)):
su1[i+1]=su1[i]+p[i][0]
for i in range(1,n):
mi[i]=min(mi[i-1],w[i])
for i in range(1,n):
mi1[i]=min(mi1[i-1],w1[i])
def find(x):
x-=1
dol=mi[x]
pou=mi1[x]
for i in range(min(k,len(d))+1):
if k-i>len(p):
continue
ans=dol*su[i]
ans+=pou*su1[k-i]
if ans<=s:
return (True,i)
return (False,-1)
st=1
end=n
ans=(-1,-1)
while(st<=end):
mid=(st+end)//2
r=find(mid)
if r[0]==True:
ans=[mid,r[1]]
end=mid-1
else:
st=mid+1
if ans[0]==-1:
print(ans[0])
sys.exit(0)
print(ans[0])
d1=w.index(min(w[:ans[0]]))
p1=w1.index(min(w1[:ans[0]]))
for i in range(ans[1]):
print(d[i][1]+1,d1+1)
for i in range(k-ans[1]):
print(p[i][1]+1,p1+1)
```
| 92,163 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Tags: binary search, greedy, two pointers
Correct Solution:
```
'''
Auther: ghoshashis545 Ashis Ghosh
College: Jalpaiguri Govt Enggineering College
'''
from os import path
from io import BytesIO, IOBase
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,Counter,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def bo(i):
return ord(i)-ord('0')
file = 1
def ceil(a,b):
return (a+b-1)//b
def solve():
# for _ in range(1,ii()+1):
n,m,k,s = mi()
a = li()
b = li()
gadgets = [[] for i in range(2)]
for i in range(m):
x,y = mi()
gadgets[x-1].append([y,i+1])
gadgets[0].sort()
gadgets[1].sort()
sz = [len(gadgets[0]),len(gadgets[1])]
def check(idx):
mnx1 = inf
mnx2 = inf
for i in range(idx+1):
mnx1 = min(mnx1,a[i])
mnx2 = min(mnx2,b[i])
l1,l2,res = 0,0,0
if k > sz[0] + sz[1]:
return 0
for i in range(k):
if l1 == sz[0]:
res += gadgets[1][l2][0]*mnx2
l2 += 1
elif l2 == sz[1]:
res += gadgets[0][l1][0]*mnx1
l1 += 1
elif gadgets[0][l1][0]*mnx1 <= gadgets[1][l2][0]*mnx2:
res += gadgets[0][l1][0]*mnx1
l1 += 1
else:
res += gadgets[1][l2][0]*mnx2
l2 += 1
return res <= s
l = 0
r = n-1
ans = -1
while l<=r:
mid = (l+r)>>1
if check(mid):
ans = mid+1
r = mid-1
else:
l=mid+1
print(ans)
if ans == -1:
return
mnx1 = inf
mnx2 = inf
idx1,idx2 = -1,-1
for i in range(ans):
if a[i] < mnx1:
mnx1 = a[i]
idx1 = i
if b[i] < mnx2:
mnx2 = b[i]
idx2 = i
l1,l2,res = 0,0,[]
for i in range(k):
if l1 == sz[0]:
res.append([gadgets[1][l2][1],idx2+1])
l2 += 1
elif l2==sz[1]:
res.append([gadgets[0][l1][1],idx1+1])
l1 += 1
elif gadgets[0][l1][0]*mnx1 <= gadgets[1][l2][0]*mnx2:
res.append([gadgets[0][l1][1],idx1+1])
l1 += 1
else:
res.append([gadgets[1][l2][1],idx2+1])
l2 += 1
for i in res:
print(*i)
if __name__ =="__main__":
if(file):
if path.exists('input.txt'):
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt','w')
else:
input=sys.stdin.readline
solve()
```
| 92,164 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Tags: binary search, greedy, two pointers
Correct Solution:
```
from sys import stdin, stdout
def ints():
return [int(x) for x in stdin.readline().split()]
n, m, k, s = ints()
a = ints()
b = ints()
d_gad = [];
p_gad = [];
for i in range(m):
t, c = ints()
if t == 1:
d_gad.append([c, i + 1])
else:
p_gad.append([c, i + 1])
d_gad.sort()
p_gad.sort()
mn_dol = [0] * n
mn_pou = [0] * n
day_mn_dol = [1] * n
day_mn_pou = [1] * n
mn_dol[0] = a[0]
mn_pou[0] = b[0]
for i in range(1, n):
mn_dol[i] = min(mn_dol[i - 1], a[i])
day_mn_dol[i] = (i + 1 if mn_dol[i] == a[i] else day_mn_dol[i - 1])
for i in range(1, n):
mn_pou[i] = min(mn_pou[i - 1], b[i])
day_mn_pou[i] = (i + 1 if mn_pou[i] == b[i] else day_mn_pou[i - 1])
def Check(x):
i = 0
j = 0
mnd = mn_dol[x]
mnp = mn_pou[x]
SuM = 0
for u in range(k):
if i == len(d_gad):
SuM += p_gad[j][0] * mnp
j += 1
elif j == len(p_gad):
SuM += d_gad[i][0] * mnd
i += 1
else:
p1 = d_gad[i][0] * mnd
p2 = p_gad[j][0] * mnp
if p1 <= p2:
SuM += p1
i += 1
else:
SuM += p2
j += 1
if SuM > s:
return False
return True
def Print_Ans(x):
i = 0
j = 0
mnd = mn_dol[x]
mnp = mn_pou[x]
dayd = day_mn_dol[x]
dayp = day_mn_pou[x]
for u in range(k):
if i == len(d_gad):
stdout.write(f'{p_gad[j][1]} {dayp}\n')
j += 1
elif j == len(p_gad):
stdout.write(f'{d_gad[i][1]} {dayd}\n')
i += 1
else:
if d_gad[i][0] * mnd <= p_gad[j][0] * mnp:
stdout.write(f'{d_gad[i][1]} {dayd}\n')
i += 1
else:
stdout.write(f'{p_gad[j][1]} {dayp}\n')
j += 1
if not Check(n - 1):
print(-1)
else:
p = 0
q = n - 1
while p < q:
mid = (p + q) // 2
if Check(mid):
q = mid
else:
p = mid + 1
stdout.write(f'{p + 1}\n')
Print_Ans(p)
```
| 92,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Submitted Solution:
```
from sys import stdin, stdout
def ints():
return [int(x) for x in stdin.readline().split()]
n, m, k, s = ints()
a = ints()
b = ints()
d_gad = [(0,)] * m;
p_gad = [(0,)] * m;
ix = 0
jx = 0
for i in range(m):
t, c = ints()
if t == 1:
d_gad[ix] = (c, i + 1)
ix += 1
else:
p_gad[jx] = (c, i + 1)
jx += 1
d_gad = sorted(d_gad[:ix])
p_gad = sorted(p_gad[:jx])
mn_dol = [0] * n
mn_pou = [0] * n
day_mn_dol = [1] * n
day_mn_pou = [1] * n
mn_dol[0] = a[0]
mn_pou[0] = b[0]
for i in range(1, n):
mn_dol[i] = min(mn_dol[i - 1], a[i])
day_mn_dol[i] = (i + 1 if mn_dol[i] == a[i] else day_mn_dol[i - 1])
for i in range(1, n):
mn_pou[i] = min(mn_pou[i - 1], b[i])
day_mn_pou[i] = (i + 1 if mn_pou[i] == b[i] else day_mn_pou[i - 1])
def Check(x):
i = 0
j = 0
mnd = mn_dol[x]
mnp = mn_pou[x]
SuM = 0
for u in range(k):
if i == ix:
SuM += p_gad[j][0] * mnp
j += 1
elif j == jx:
SuM += d_gad[i][0] * mnd
i += 1
else:
p1 = d_gad[i][0] * mnd
p2 = p_gad[j][0] * mnp
if p1 <= p2:
SuM += p1
i += 1
else:
SuM += p2
j += 1
if SuM > s:
return False
return True
def Print_Ans(x):
i = 0
j = 0
mnd = mn_dol[x]
mnp = mn_pou[x]
dayd = day_mn_dol[x]
dayp = day_mn_pou[x]
for u in range(k):
if i == ix:
stdout.write(f'{p_gad[j][1]} {dayp}\n')
j += 1
elif j == jx:
stdout.write(f'{d_gad[i][1]} {dayd}\n')
i += 1
else:
if d_gad[i][0] * mnd <= p_gad[j][0] * mnp:
stdout.write(f'{d_gad[i][1]} {dayd}\n')
i += 1
else:
stdout.write(f'{p_gad[j][1]} {dayp}\n')
j += 1
if not Check(n - 1):
stdout.write('-1\n')
else:
p = 0
q = n - 1
while p < q:
mid = (p + q) // 2
if Check(mid):
q = mid
else:
p = mid + 1
stdout.write(f'{p + 1}\n')
Print_Ans(p)
```
Yes
| 92,166 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Submitted Solution:
```
from itertools import accumulate
import sys
def solve(f):
n, m, k, s = [int(x) for x in f.readline().split()]
a_price = [(int(x), i+1) for i, x in enumerate(f.readline().split())]
b_price = [(int(x), i+1) for i, x in enumerate(f.readline().split())]
a_gadgets = []
b_gadgets = []
for i, line in enumerate(f):
t, price = [int(x) for x in line.split()]
if t == 1:
a_gadgets.append((price, i + 1))
else:
b_gadgets.append((price, i + 1))
a_gadgets.sort()
b_gadgets.sort()
prefix_a = [0] + list(accumulate(gadget[0] for gadget in a_gadgets))
prefix_b = [0] + list(accumulate(gadget[0] for gadget in b_gadgets))
la = min(k, len(a_gadgets))
lb = min(k, len(b_gadgets))
min_price_for_k = [(prefix_a[i], prefix_b[k - i], i) for i in range(k-lb, la+1)]
min_a, min_b = [a_price[0]], [b_price[0]]
for i in range(1, n):
min_a.append(min(min_a[i-1], a_price[i]))
min_b.append(min(min_b[i-1], b_price[i]))
def expence(day):
return lambda x: min_a[day][0]*x[0] + min_b[day][0]*x[1]
x, y = 0, n-1
while x <= y-1:
day = (x + y) // 2
min_cost = min(min_price_for_k, key = expence(day))
if expence(day)(min_cost) > s:
x = day+1
else:
y = day
min_cost = min(min_price_for_k, key = expence(x))
if expence(x)(min_cost) > s:
print(-1)
else:
print(x+1)
i1 = min_cost[-1]
for i in range(i1):
print(a_gadgets[i][1], min_a[x][1])
for i in range(k - i1):
print(b_gadgets[i][1], min_b[x][1])
from time import time
t = time()
solve(sys.stdin)
print(time() - t)
```
No
| 92,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Submitted Solution:
```
from sys import stdin, stdout
def ints():
return [int(x) for x in stdin.readline().split()]
n, m, k, s = ints()
a = ints()
b = ints()
d_gad = [(0,)] * m;
p_gad = [(0,)] * m;
ix = 0
jx = 0
for i in range(m):
t, c = ints()
if t == 1:
d_gad[ix] = (c, i + 1)
ix += 1
else:
p_gad[jx] = (c, i + 1)
jx += 1
d_gad[:ix].sort()
p_gad[:jx].sort()
mn_dol = [0] * n
mn_pou = [0] * n
day_mn_dol = [1] * n
day_mn_pou = [1] * n
mn_dol[0] = a[0]
mn_pou[0] = b[0]
for i in range(1, n):
mn_dol[i] = min(mn_dol[i - 1], a[i])
day_mn_dol[i] = (i + 1 if mn_dol[i] == a[i] else day_mn_dol[i - 1])
for i in range(1, n):
mn_pou[i] = min(mn_pou[i - 1], b[i])
day_mn_pou[i] = (i + 1 if mn_pou[i] == b[i] else day_mn_pou[i - 1])
def Check(x):
i = 0
j = 0
mnd = mn_dol[x]
mnp = mn_pou[x]
SuM = 0
for u in range(k):
if i == ix:
SuM += p_gad[j][0] * mnp
j += 1
elif j == jx:
SuM += d_gad[i][0] * mnd
i += 1
else:
p1 = d_gad[i][0] * mnd
p2 = p_gad[j][0] * mnp
if p1 <= p2:
SuM += p1
i += 1
else:
SuM += p2
j += 1
if SuM > s:
return False
return True
def Print_Ans(x):
i = 0
j = 0
mnd = mn_dol[x]
mnp = mn_pou[x]
dayd = day_mn_dol[x]
dayp = day_mn_pou[x]
for u in range(k):
if i == ix:
stdout.write(f'{p_gad[j][1]} {dayp}\n')
j += 1
elif j == jx:
stdout.write(f'{d_gad[i][1]} {dayd}\n')
i += 1
else:
if d_gad[i][0] * mnd <= p_gad[j][0] * mnp:
stdout.write(f'{d_gad[i][1]} {dayd}\n')
i += 1
else:
stdout.write(f'{p_gad[j][1]} {dayp}\n')
j += 1
if not Check(n - 1):
stdout.write('-1\n')
else:
p = 0
q = n - 1
while p < q:
mid = (p + q) // 2
if Check(mid):
q = mid
else:
p = mid + 1
stdout.write(f'{p + 1}\n')
Print_Ans(p)
```
No
| 92,168 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Submitted Solution:
```
def check(x):
global n, m, k, s, q, c, d
cur1 = 0
cur2 = 0
q.clear()
for i in range(x):
if a[i] < a[cur1]:
cur1 = i
if b[i] < b[cur2]:
cur2 = i
for i in range(k):
if c[i] == 1:
q.append((d[i] * a[cur1], i, cur1))
else:
q.append((d[i] * b[cur2], i, cur2))
q.sort()
cur = 0
for i in range(k):
cur += q[i][0]
return cur <= s
n, m, k, s = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = []
d = []
for i in range(m):
x, y = map(int, input().split())
c.append(x)
d.append(y)
l = 1
r = n
q = []
while r - l > 1:
mid = (r + l) >> 1
if check(mid):
r = mid
else:
l = mid
if check(l):
print(l)
for i in range(k):
print(q[i][1] + 1, q[i][2] + 1)
else:
if check(r):
print(r)
for i in range(k):
print(q[i][1] + 1, q[i][2] + 1)
else:
print(-1)
```
No
| 92,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
Input
First line contains four integers n, m, k, s (1 β€ n β€ 2Β·105, 1 β€ k β€ m β€ 2Β·105, 1 β€ s β€ 109) β number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers ai (1 β€ ai β€ 106) β the cost of one dollar in burles on i-th day.
Third line contains n integers bi (1 β€ bi β€ 106) β the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers ti, ci (1 β€ ti β€ 2, 1 β€ ci β€ 106) β type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d β the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
Examples
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
Submitted Solution:
```
import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = 'x' in file.mode or 'w' in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b'\n') + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
import heapq
def can_do(check_days, n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val):
# get low in the range 1 -> check_days
min_d = prefx_min_d_val[check_days][0]
min_p = prefx_min_p_val[check_days][0]
min_d_idx = prefx_min_d_val[check_days][1]
min_p_idx = prefx_min_p_val[check_days][1]
vals_d = [0] * (k + 1)
vals_p = [0] * (k + 1)
for i in range(1, k + 1):
# print(i)
if i < len(d_gadgets):
vals_d[i] = ((min_d * d_gadgets[i - 1][0]) + vals_d[i - 1])
if i < len(p_gadgets):
vals_p[i] = ((min_p * p_gadgets[i - 1][0]) + vals_p[i - 1])
for x in range(k + 1):
# x from dollar and k - x from pounds
if x <= len(d_gadgets) and k - x <= len(p_gadgets):
if ((x > 0 and vals_d[x] > 0) or x == 0) \
and ((k - x > 0 and vals_p[k - x] > 0) or k - x == 0):
total = vals_d[x] + vals_p[k - x]
if total <= s:
res = []
for i in range(x):
res.append((d_gadgets[i][1], min_d_idx))
for i in range(k - x):
res.append((p_gadgets[i][1], min_p_idx))
return (True, res)
return (False, [])
def check(n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val):
lo = 0
hi = n
res = -1
while lo <= hi:
mid = lo + (hi - lo) // 2
if can_do(mid, n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val)[0]:
res = mid
hi = mid - 1
else:
lo = mid + 1
if res == -1:
return res, []
return res, can_do(res, n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val)[1]
def solve():
n, m, k, s = map(int, input().split())
d_vals = list(map(int, input().split()))
d_vals.insert(0, float("inf"))
p_vals = list(map(int, input().split()))
p_vals.insert(0, float("inf"))
d_gadgets = []
p_gadgets = []
for i in range(m):
t, c = map(int, input().split())
if t == 1:
d_gadgets.append((c, i + 1))
else:
p_gadgets.append((c, i + 1))
prefx_min_d_val = [(d_vals[0], 0)] * len(d_vals)
for i in range(1, len(d_vals)):
if prefx_min_d_val[i - 1][0] < d_vals[i]:
prefx_min_d_val[i] = (prefx_min_d_val[i - 1][0], prefx_min_d_val[i - 1][1])
else:
prefx_min_d_val[i] = (d_vals[i], i)
prefx_min_p_val = [(p_vals[0], 0)] * len(p_vals)
for i in range(1, len(p_vals)):
if prefx_min_p_val[i - 1][0] < p_vals[i]:
prefx_min_p_val[i] = (prefx_min_p_val[i - 1][0], prefx_min_p_val[i - 1][1])
else:
prefx_min_p_val[i] = (p_vals[i], i)
d_gadgets.sort(key=lambda x: x[0])
p_gadgets.sort(key=lambda x: x[0])
res, r = check(n, m, k, s, d_gadgets, p_gadgets, prefx_min_d_val, prefx_min_p_val)
cout<<res<<endl
for p in r:
cout<<p[0]<<" "<<p[1]<<endl
def main():
solve()
if __name__ == "__main__":
main()
```
No
| 92,170 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Tags: combinatorics, math
Correct Solution:
```
a=int(input());print(sum([2*2**i for i in range(a)]))
```
| 92,171 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Tags: combinatorics, math
Correct Solution:
```
n = int ( input() )
ans = 0
i = 1
while i <= n :
ans += 2**i
i += 1
print ( ans )
```
| 92,172 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Tags: combinatorics, math
Correct Solution:
```
n = input()
c = 0
for i in range(1, int(n)+1):
c += 2**i
print (c)
```
| 92,173 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Tags: combinatorics, math
Correct Solution:
```
from math import factorial
n = int(input())
a = 0
for i in range(1, n+1):
for j in range(0, i+1):
a += int(factorial(i) / (factorial(j) * factorial(i-j)))
print(a)
```
| 92,174 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Tags: combinatorics, math
Correct Solution:
```
a = input()
print(2 ** (int(a)+1) - 2)
```
| 92,175 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Tags: combinatorics, math
Correct Solution:
```
n = int(input())
print(sum(2**(i + 1) for i in range(n)))
```
| 92,176 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Tags: combinatorics, math
Correct Solution:
```
num_digits = int(input())
print(sum(2 ** i for i in range(1, num_digits + 1)))
```
| 92,177 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Tags: combinatorics, math
Correct Solution:
```
n = 56
lista = [1] * n
lista[0] = 0
lista[1] = 2
for i in range(2, n):
lista[i] = lista[i - 1] + 2 ** i
dig = int(input())
print(lista[dig])
```
| 92,178 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Submitted Solution:
```
n = int(input())
sum = 0
for i in range(1,n+1) :
sum += 2**i
print (sum)
```
Yes
| 92,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Submitted Solution:
```
a = int(input())
a=2**(a+1)-2
print(a)
```
Yes
| 92,180 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Submitted Solution:
```
n = int(input())
print(2**(n)*2 - 2)
```
Yes
| 92,181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Submitted Solution:
```
maxn = int(input())
answer = 0
for i in range(maxn):
a = 1
for j in range(i+1):
a = a*2
answer+=a
print(answer)
```
Yes
| 92,182 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Submitted Solution:
```
import sys
input = sys.stdin.readline
def list_input():
return list(map(int, input().split()))
def float_compare(a, b):
if abs(a-b) < float(1e-9):
return True
else:
return False
def sub_mod(x, mod):
x = x % mod
if x < 0:
x += mod
return x
def divisor(n):
i = 1
dv = []
while i*i <= n:
if n % i == 0:
dv.append(i)
if i*i != n:
dv.append(n//i)
i += 1
return dv
n = int(input().strip())
print((3**(n-1))*2)
```
No
| 92,183 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Submitted Solution:
```
n=int(input())
print(2**n+2)
```
No
| 92,184 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Submitted Solution:
```
first = int(input())
total = 0
for i in range(1,first+1):
total += i*2
#plz
print(total)
```
No
| 92,185 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The only line of input contains one integer n (1 β€ n β€ 55) β the maximum length of a number that a door-plate can hold.
Output
Output one integer β the maximum number of offices, than can have unique lucky numbers not longer than n digits.
Examples
Input
2
Output
6
Submitted Solution:
```
i = 1
n = eval(input())
s = 0
while(i<=n):
s = s + i ** 2
i = i + 1
```
No
| 92,186 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Tags: *special
Correct Solution:
```
'kitten'
f,l,t=map(int,input().split())
s=[input() for _ in range(f)]
a=0
for j in range(l):
c=0
for i in range(f):
c+=s[i][j]=='Y';
a+=c>=t
print(a)
```
| 92,187 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Tags: *special
Correct Solution:
```
#kitten
F, I, T = list(map(int, input().split()))
s = [""] * F
for i in range(F):
s[i] = input()
a = 0
for j in range(I):
c = 0
for i in range(F):
c += (s[i][j] == 'Y')
a += (c >= T)
print(a)
```
| 92,188 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Tags: *special
Correct Solution:
```
import sys
n,m,k=map(int,sys.stdin.readline().split ())
c=[0]*m
for i in range(n):
T=sys.stdin.readline()
for j in range(m) :
if T[j]=='Y' :
c[j]+=1
kitten=0
for i in range(m):
if c[i]>=k:
kitten+=1
print(kitten)
```
| 92,189 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Tags: *special
Correct Solution:
```
f,i,t = map(int,input().split())
a = [0] * i
for z in range(f):
u = input().strip()
for q in range(i):
if u[q] == 'Y': a[q] += 1
print(len([_ for _ in a if _ >= t]))
# kitten
# meow~~
```
| 92,190 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Tags: *special
Correct Solution:
```
f,l,t = map(int,input().split())
s = []
for i in range(f):
s.append(input())
ans = 0
for i in range(l):
cnt = 0
for j in range(f):
cnt += (s[j][i]=='Y')
ans += (cnt >= t)
# kitten
print( ans )
```
| 92,191 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Tags: *special
Correct Solution:
```
c = []
F, I, T = map(int, input().split())
for i in range(F):
s = input()
for j in range(I):
c.append(0)
c[j] += s[j] == 'Y'
r = 0
for i in range(I):
r += c[i] >= T
print(r)
kitten = 0
```
| 92,192 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Tags: *special
Correct Solution:
```
f, i, t = [int(x) for x in input().split()]
s = [0] * i
for kitten in range(f):
l = input()
for o in range(i):
if l[o] == 'Y':
s[o]+=1
print(sum([1 for x in s if x >= t]))
```
| 92,193 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Tags: *special
Correct Solution:
```
f,i,t = map(int,input().split())
a = [0] * i
for b in range(f):
u = input().strip()
for q in range(i):
if u[q] == 'Y': a[q] += 1
print(len([_ for _ in a if _ >= t]))
# kitten
# meow~~
```
| 92,194 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Submitted Solution:
```
f, i, t = map(int, input().split())
q = [0 for x in range(i)]
for g in range(f):
s = input()
for j in range(i):
q[j] += s[j] == 'Y'
kitten = sum([x >= t for x in q])
print(kitten)
```
Yes
| 92,195 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Submitted Solution:
```
#kitten
f,i,t=map(int,input().split())
c=[0]*i
for x in range(f):
s=input()
for y in range(i):
if s[y]=='Y':
c[y]+=1
a = 0
for x in range(i):
if c[x]>=t:
a+=1
print(a)
```
Yes
| 92,196 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Submitted Solution:
```
#kitten
n,k,t=map(int,input().split())
r=range(n)
c=[]
for i in r:
c.append([])
c[-1]=input()
a=0
for j in range(k):
x=0
for i in r:x+=int(c[i][j] == 'Y')
if (x>=t):a+=1
print(a)
```
Yes
| 92,197 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Submitted Solution:
```
n,m,t=map(int,input().split())
k=[1 for i in range(m)]
for i in range(n):
S=input()
for j in range(m):
if S[j]=='Y':
k[j]+=1
x=0
for j in range(m):
if k[j]>t:
x+=1
print(x)
kitten=0
```
Yes
| 92,198 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
Input
The first line of the input will contain three space-separated integers: the number of friends F (1 β€ F β€ 10), the number of items I (1 β€ I β€ 10) and the threshold T (1 β€ T β€ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
Output
Output an integer β the number of items liked by at least T of user's friends.
Examples
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Submitted Solution:
```
n, m, e = map(int, input().split())
k = [0] * 10
for i in range(n) :
a = input()
for j in range(m) :
if(a[j] == 'Y') : k[j] += 1
ans = 0
for i in range(m) :
if(k[i] >= e) : ans += 1
print(ans)
```
No
| 92,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.