message stringlengths 2 43.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 853 107k | cluster float64 24 24 | __index_level_0__ int64 1.71k 214k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go). | instruction | 0 | 50,658 | 24 | 101,316 |
Tags: implementation
Correct Solution:
```
prev = ''
h = 0
n = 0
for ch in input():
if ch != prev or h == 5:
h = 1
n += 1
else:
h += 1
prev = ch
print(n)
``` | output | 1 | 50,658 | 24 | 101,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go). | instruction | 0 | 50,659 | 24 | 101,318 |
Tags: implementation
Correct Solution:
```
a = input()
ans = 0
i = 0
while i < len(a):
j = i + 1
while j < len(a) and a[j] == a[i] and j - i < 5: j+=1
ans+=1
i = j
print(ans)
``` | output | 1 | 50,659 | 24 | 101,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go). | instruction | 0 | 50,660 | 24 | 101,320 |
Tags: implementation
Correct Solution:
```
s=input()
count,a,t=0,0,s[0]
for i in s:
if i!=t or a==5:count,a=count+1,0
a,t=a+1,i
print(count+1)
``` | output | 1 | 50,660 | 24 | 101,321 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go). | instruction | 0 | 50,661 | 24 | 101,322 |
Tags: implementation
Correct Solution:
```
s = input()
a = 0
t = 1
for i in range(1,len(s)):
if s[i-1]==s[i]:
t = t+1
else:
a = a+ (t+4)//5
t = 1
a = a+ (t+4)//5
print(a)
``` | output | 1 | 50,661 | 24 | 101,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go). | instruction | 0 | 50,662 | 24 | 101,324 |
Tags: implementation
Correct Solution:
```
s = input()
t = s[0]
num = 1
res = 1
for i in s[1::]:
if num >=5 or not i == t:
num = 1
t = i
res += 1
else:
t = i
num += 1
print(res)
``` | output | 1 | 50,662 | 24 | 101,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
s = input()
count = 0
ans = 1
for i in range(1, len(s)):
if count == 4 or (count <= 4 and s[i] != s[i - 1]):
count = 0
ans += 1
elif s[i] == s[i - 1]:
count += 1
if s[i] != s[i - 1] and count != 0:
ans += 1
count = 0
print(ans)
``` | instruction | 0 | 50,663 | 24 | 101,326 |
Yes | output | 1 | 50,663 | 24 | 101,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
s = str(input())
i=0
count = 0
while len(s)>0:
if s[0]=='C':
temp = s.lstrip('C')
if len(s)-len(temp)>5:
s = s[5:]
else:
s = temp
count = count+1
else:
temp = s.lstrip('P')
if len(s)-len(temp)>5:
s = s[5:]
else:
s = temp
count = count+1
print(count)
``` | instruction | 0 | 50,664 | 24 | 101,328 |
Yes | output | 1 | 50,664 | 24 | 101,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
a = input()
m = len(a)
k = 1
answ = 0
if m == 1:
print(1)
exit()
for i in range(1,m):
if a[i] == a[i-1]:
k += 1
else:
answ+=k//5+int(k%5!=0)
k = 1
if i == m-1:
answ+=k//5+int(k%5!=0)
print(answ)
``` | instruction | 0 | 50,665 | 24 | 101,330 |
Yes | output | 1 | 50,665 | 24 | 101,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
X = input()
Count, i = 0, 0
while i < len(X):
temp, S = X[i], 0
while i < len(X) and X[i] == temp and S != 5:
i, S = i + 1, S + 1
Count += 1
print(Count)
# UB_CodeForces
# Advice: Never ever give up
# Location: Behind my desk in the midnight
# Caption: I Got a cold
``` | instruction | 0 | 50,666 | 24 | 101,332 |
Yes | output | 1 | 50,666 | 24 | 101,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
stena= input ()
vruke=0
pohodov=1
j=''
for i in stena:
if j=='':
j=i
else:
if i==j:
vruke+=1
else:
pohodov+=1
vruke=1
j=i
if vruke==5:
pohodov+=1
vruke=0
print (pohodov)
``` | instruction | 0 | 50,667 | 24 | 101,334 |
No | output | 1 | 50,667 | 24 | 101,335 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
a=input()
b=[i for i in a.split('P')]
c=[i for i in a.split('C')]
g=0
for i in range(len(b)):
if b[i]!='':
if len(b[i])<=5:
k=len(b[i])
if k<=5:
g+=1
else:
g+=len(b[i])//5
g+=1
for i in range(len(c)):
if c[i]!='':
if len(c[i])<=int(5):
j=len(c[i])
if j<=5:
g+=1
else:
g += len(c[i]) // 5
g += 1
print(g)
``` | instruction | 0 | 50,668 | 24 | 101,336 |
No | output | 1 | 50,668 | 24 | 101,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
s = input()
cur = s[0]
cnt = 1
ans = 0
for i in range(1, len(s)):
x = s[i]
if(cur != x):
ans = ans + 1
cnt = 1
cur = x
else:
if(cnt < 5):
cnt = cnt + 1
else:
ans = ans + 1
cnt = 1
cur = x
print (ans)
``` | instruction | 0 | 50,669 | 24 | 101,338 |
No | output | 1 | 50,669 | 24 | 101,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
s=input()
c=0
d=9
if(len(s)>1):
for i in range(len(s)-1):
if(s[i]!=s[i+1]):
c=c+1
d=0
else:
d=d+1
if(d==5):
d=0
c=c+1
if(s[-1]==s[-2] and d!=5):
c=c+1
elif(s[-1]!=s[-2]):
c=c+1
print(c)
else:
print(1)
``` | instruction | 0 | 50,670 | 24 | 101,340 |
No | output | 1 | 50,670 | 24 | 101,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The farmer Polycarp has a warehouse with hay, which can be represented as an n × m rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer ai, j and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1 × 1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.
Polycarp wants the following requirements to hold after the reorganization:
* the total amount of hay remaining in the warehouse must be equal to k,
* the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same,
* the height of at least one stack must remain the same as it was,
* for the stability of the remaining structure all the stacks should form one connected region.
The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.
Help Polycarp complete this challenging task or inform that it is impossible.
Input
The first line of the input contains three integers n, m (1 ≤ n, m ≤ 1000) and k (1 ≤ k ≤ 1018) — the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization.
Then n lines follow, each containing m positive integers ai, j (1 ≤ ai, j ≤ 109), where ai, j is equal to the number of cubic meters of hay making the hay stack on the i-th row and j-th column of the table.
Output
In the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next n lines print m numbers — the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered.
If there are multiple answers, print any of them.
Examples
Input
2 3 35
10 4 9
9 9 7
Output
YES
7 0 7
7 7 7
Input
4 4 50
5 9 1 1
5 1 1 5
5 1 5 5
5 5 7 1
Output
YES
5 5 0 0
5 0 0 5
5 0 5 5
5 5 5 0
Input
2 4 12
1 1 3 1
1 6 2 4
Output
NO
Note
In the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value k = 7·5 = 35. At that the stack that is on the second line and third row remained unaltered.
Submitted Solution:
```
#import primesieve as ps
import itertools as it
import functools as ft
import operator as op
import collections as cl
def iterate(f,x,recursion = 0):
if recursion == 0:
while True:
yield x
x = f(x)
else:
for _ in range(recursion + 1):
yield x
x = f(x)
def primes():
ps = [2]
yield 2
cand = 3
while True:
for p in ps:
if p*p > cand:
ps.append(cand)
yield cand
break
elif cand % p == 0:
break
cand += 2
def factorize(n):
pg = primes()
p = next(pg)
ret = []
while p*p <= n:
if n % p == 0:
ret.append(p)
n //= p
continue
p = next(pg)
return ret + [n]
def divisors(n):
fs = list(map(lambda x:list(x[1]), it.groupby(factorize(n))))
gs = list(map(lambda xs:list(iterate(lambda y:xs[0]*y, 1, len(xs))), fs))
return sorted(map(lambda xs:ft.reduce(op.mul, xs), it.product(*gs)))
n, m, k = map(int, input().split(' '))
inputs = [[] for _ in range(n)]
for i in range(n):
inputs[i] = list(map(int, input().split(' ')))
for d in reversed(list(it.takewhile(lambda x:x <= n*m, divisors(k)))):
e = k // d
vs = set()
paths = cl.defaultdict(list)
visited = set()
count = 0
ans = set()
result = 'NO'
for i in range(n):
for j in range(m):
if inputs[i][j] < e:
inputs[i][j] = 0
else:
vs.add((i,j))
if (i-1,j) in vs:
paths[(i-1,j)].append((i,j))
paths[(i,j)].append((i-1,j))
if (i,j-1) in vs:
paths[(i,j-1)].append((i,j))
paths[(i,j)].append((i,j-1))
if len(vs) < d:
continue
def search(v, n):
global count
if v in visited:
return False
count += 1
ans.add(v)
visited.add(v)
if count >= n:
return True
for u in paths[v]:
paths[u].remove(v)
if search(u, n):
return True
return False
for v in vs:
if v in visited:
continue
count = 0
ans.clear()
if search(v, d):
result = 'YES'
for i in range(n):
for j in range(m):
if (i,j) in ans:
inputs[i][j] = e
else:
inputs[i][j] = 0
break
if result == 'YES':
break
print(result)
if result == 'YES':
for i in range(n):
print(' '.join(map(str, inputs[i])))
``` | instruction | 0 | 51,754 | 24 | 103,508 |
No | output | 1 | 51,754 | 24 | 103,509 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The farmer Polycarp has a warehouse with hay, which can be represented as an n × m rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer ai, j and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1 × 1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.
Polycarp wants the following requirements to hold after the reorganization:
* the total amount of hay remaining in the warehouse must be equal to k,
* the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same,
* the height of at least one stack must remain the same as it was,
* for the stability of the remaining structure all the stacks should form one connected region.
The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.
Help Polycarp complete this challenging task or inform that it is impossible.
Input
The first line of the input contains three integers n, m (1 ≤ n, m ≤ 1000) and k (1 ≤ k ≤ 1018) — the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization.
Then n lines follow, each containing m positive integers ai, j (1 ≤ ai, j ≤ 109), where ai, j is equal to the number of cubic meters of hay making the hay stack on the i-th row and j-th column of the table.
Output
In the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next n lines print m numbers — the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered.
If there are multiple answers, print any of them.
Examples
Input
2 3 35
10 4 9
9 9 7
Output
YES
7 0 7
7 7 7
Input
4 4 50
5 9 1 1
5 1 1 5
5 1 5 5
5 5 7 1
Output
YES
5 5 0 0
5 0 0 5
5 0 5 5
5 5 5 0
Input
2 4 12
1 1 3 1
1 6 2 4
Output
NO
Note
In the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value k = 7·5 = 35. At that the stack that is on the second line and third row remained unaltered.
Submitted Solution:
```
class Stack(object):
def __init__(self):
self.items = []
def push(self,new):
self.items.append(new)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def empty(self):
return self.items == []
def size(self):
return len(self.items)
from bisect import bisect_left
(n,m,k) = map(int,input().split())
G = [None for i in range(n)]
all_number = []
for i in range(n):
line = list(map(int,input().split()))
G[i] = line
all_number.extend(line)
all_number.sort()
possible = []
for i in set(all_number):
if i > 0 and k % i == 0 and n*m - bisect_left(all_number,i) >= k // i:
possible.append(i)
visited = [[False for j in range(m)] for i in range(n)]
bool = False
print(possible)
for cand in possible:
L = []
for i in range(n):
if cand in G[i]:
j = G[i].index(cand)
break
Q = Stack()
Q.push((i,j))
L.append((i,j))
visited[i][j] = True
while not Q.empty():
r = Q.pop()
x,y = r[0],r[1]
for t in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]:
if abs(t[0]-(n-1)/2) <= (n-1)/2 and abs(t[1]-(m-1)/2) <= (m-1)/2 and G[t[0]][t[1]] >= cand and not visited[t[0]][t[1]]:
Q.push(t)
L.append(t)
visited[t[0]][t[1]] = True
print(L)
if len(L) >= k // cand:
answer = [["0" for j in range(m)] for i in range(n)]
for x in range(k // cand):
answer[L[x][0]][L[x][1]] = str(cand)
print("YES")
for i in answer:
print(' '.join(i))
bool = True
break
if not bool:
print("NO")
``` | instruction | 0 | 51,755 | 24 | 103,510 |
No | output | 1 | 51,755 | 24 | 103,511 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The farmer Polycarp has a warehouse with hay, which can be represented as an n × m rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer ai, j and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1 × 1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.
Polycarp wants the following requirements to hold after the reorganization:
* the total amount of hay remaining in the warehouse must be equal to k,
* the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same,
* the height of at least one stack must remain the same as it was,
* for the stability of the remaining structure all the stacks should form one connected region.
The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.
Help Polycarp complete this challenging task or inform that it is impossible.
Input
The first line of the input contains three integers n, m (1 ≤ n, m ≤ 1000) and k (1 ≤ k ≤ 1018) — the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization.
Then n lines follow, each containing m positive integers ai, j (1 ≤ ai, j ≤ 109), where ai, j is equal to the number of cubic meters of hay making the hay stack on the i-th row and j-th column of the table.
Output
In the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next n lines print m numbers — the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered.
If there are multiple answers, print any of them.
Examples
Input
2 3 35
10 4 9
9 9 7
Output
YES
7 0 7
7 7 7
Input
4 4 50
5 9 1 1
5 1 1 5
5 1 5 5
5 5 7 1
Output
YES
5 5 0 0
5 0 0 5
5 0 5 5
5 5 5 0
Input
2 4 12
1 1 3 1
1 6 2 4
Output
NO
Note
In the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value k = 7·5 = 35. At that the stack that is on the second line and third row remained unaltered.
Submitted Solution:
```
#import primesieve as ps
import itertools as it
import functools as ft
import operator as op
import collections as cl
def iterate(f,x,recursion = 0):
if recursion == 0:
while True:
yield x
x = f(x)
else:
for _ in range(recursion + 1):
yield x
x = f(x)
def primes():
ps = [2]
yield 2
cand = 3
while True:
for p in ps:
if p*p > cand:
ps.append(cand)
yield cand
break
elif cand % p == 0:
break
cand += 2
def factorize(n):
pg = primes()
p = next(pg)
ret = []
while p*p <= n:
if n % p == 0:
ret.append(p)
n //= p
continue
p = next(pg)
return ret + [n]
def divisors(n):
fs = list(map(lambda x:list(x[1]), it.groupby(factorize(n))))
gs = list(map(lambda xs:list(iterate(lambda y:xs[0]*y, 1, len(xs))), fs))
return sorted(map(lambda xs:ft.reduce(op.mul, xs), it.product(*gs)))
n, m, k = map(int, input().split(' '))
inputs = [[] for _ in range(n)]
for i in range(n):
inputs[i] = list(map(int, input().split(' ')))
for d in reversed(list(it.takewhile(lambda x:x <= n*m, divisors(k)))[1:]):
e = k // d
vs = set()
paths = cl.defaultdict(list)
visited = set()
count = 0
ans = set()
result = 'NO'
for i in range(n):
for j in range(m):
if inputs[i][j] < e:
inputs[i][j] = 0
else:
vs.add((i,j))
if (i-1,j) in vs:
paths[(i-1,j)].append((i,j))
paths[(i,j)].append((i-1,j))
if (i,j-1) in vs:
paths[(i,j-1)].append((i,j))
paths[(i,j)].append((i,j-1))
if len(vs) < d:
continue
def search(v, n):
global count
if v in visited:
return False
count += 1
ans.add(v)
visited.add(v)
if count >= n:
return True
for u in paths[v]:
paths[u].remove(v)
if search(u, n):
return True
return False
for v in vs:
if v in visited:
continue
count = 0
ans.clear()
if search(v, d):
result = 'YES'
for i in range(n):
for j in range(m):
if (i,j) in ans:
inputs[i][j] = e
else:
inputs[i][j] = 0
break
if result == 'YES':
break
print(result)
if result == 'YES':
for i in range(n):
print(' '.join(map(str, inputs[i])))
``` | instruction | 0 | 51,756 | 24 | 103,512 |
No | output | 1 | 51,756 | 24 | 103,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest. | instruction | 0 | 53,067 | 24 | 106,134 |
Tags: greedy, sortings
Correct Solution:
```
#
import collections, atexit, math, sys, bisect
sys.setrecursionlimit(1000000)
def getIntList():
return list(map(int, input().split()))
try :
#raise ModuleNotFoundError
import numpy
def dprint(*args, **kwargs):
#print(*args, **kwargs, file=sys.stderr)
# in python 3.4 **kwargs is invalid???
print(*args, file=sys.stderr)
dprint('debug mode')
except Exception:
def dprint(*args, **kwargs):
pass
inId = 0
outId = 0
if inId>0:
dprint('use input', inId)
sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件
if outId>0:
dprint('use output', outId)
sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件
atexit.register(lambda :sys.stdout.close()) #idle 中不会执行 atexit
N = getIntList()
za = getIntList()
cc = collections.Counter(za)
zt = []
for x in cc:
zt.append( cc[x] )
zt.sort( )
re = zt[-1]
def findmid(l,r, e):
if l>= len(zt):
return -1
if e<=zt[l]: return l;
if e>zt[r]: return -1
while l+1 <r:
mid = (l+r)//2
if zt[mid] < e:
l = mid
else:
r = mid
return r
for first in range(1, re//2 + 1):
nowr = 0
t = first
ind = -1
while 1:
ind = findmid(ind+1,len(zt)-1, t)
if ind<0:
break
nowr += t
t*=2
re = max(re, nowr)
print(re)
``` | output | 1 | 53,067 | 24 | 106,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest. | instruction | 0 | 53,068 | 24 | 106,136 |
Tags: greedy, sortings
Correct Solution:
```
p_line = [int(x) for x in input().strip().split(' ')]
size = p_line[0]
a = [int(x) for x in input().strip().split(' ')]
num_to_occ = {}
for x in a:
if x not in num_to_occ:
num_to_occ[x] = 0
num_to_occ[x] += 1
topics = []
for _, occ in num_to_occ.items():
topics.append(occ)
topics.sort(reverse = True)
ba = 0
for start in range(1, topics[0] + 1):
my_a = start
act = start
for i in range(1, len(topics)):
if act % 2 == 1:
break
act = act / 2
if act > 0 and topics[i] >= act:
my_a += act
else:
break
ba = max(ba, my_a)
print(int(ba))
``` | output | 1 | 53,068 | 24 | 106,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest. | instruction | 0 | 53,069 | 24 | 106,138 |
Tags: greedy, sortings
Correct Solution:
```
from collections import Counter
def GPSum(a,r,n):
return (a*(pow(r,n)-1))//(r-1)
n = int(input())
aa = [int(i) for i in input().split()]
c = Counter(aa)
ss = sorted([int(i) for i in c.values()])[::-1]
# print(ss)
minn = [ss[0]]
cur = ss[0]
ans = ss[0]
for i in range(0,len(ss)):
if i == 0:
ans = ss[0]
else:
cur = min(cur//2,ss[i])
if cur:
ans = max(ans,GPSum(cur,2,i+1))
# print(minn)
print(ans)
``` | output | 1 | 53,069 | 24 | 106,139 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest. | instruction | 0 | 53,070 | 24 | 106,140 |
Tags: greedy, sortings
Correct Solution:
```
def check(x):
ans=0
for i in range(len(fre)):
if fre[i]>=x:
ans+=x
else:
break
if x%2:
break
x=x//2
if x==0:
break
return ans
n = int(input())
lis = list(map(int,input().split()))
d={}
fre=[]
for i in lis:
if i in d:
d[i]+=1
else:
d[i]=1
for i in d:
fre.append(d[i])
fre.sort(reverse = True)
ans=0
for i in range(fre[0]+1):
ans=max(ans,check(i))
print(ans)
``` | output | 1 | 53,070 | 24 | 106,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest. | instruction | 0 | 53,071 | 24 | 106,142 |
Tags: greedy, sortings
Correct Solution:
```
def main():
buf = input()
n = int(buf)
buf = input()
buflist = buf.split()
a = list(map(int, buflist))
appearance = {}
for i in a:
if not i in appearance:
appearance.update({i : 1})
else:
appearance[i] += 1
appearance = [[k, v] for k ,v in dict(sorted(appearance.items(), key=lambda x:x[1])).items()]
max_num = appearance[-1][1]
pos = 0
for i in range(1, max_num + 1):
num = 0
prob = i
for j in range(pos, len(appearance)):
if appearance[j][1] >= prob:
num += prob
prob *= 2
if num > max_num:
max_num = num
while appearance[pos][1] == i and pos < len(appearance) - 1:
pos += 1
print(max_num)
if __name__ == '__main__':
main()
``` | output | 1 | 53,071 | 24 | 106,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest. | instruction | 0 | 53,072 | 24 | 106,144 |
Tags: greedy, sortings
Correct Solution:
```
# import sys
# input=sys.stdin.readline
n=int(input())
a=list(map(int,input().split()))
b={}
for i in range(n):
if a[i] not in b.keys():
b[a[i]]=0
b[a[i]]+=1
c=[]
for i in b:
c.append(b[i])
e=sorted(c,reverse=True)
d=[e[0]]
a=e[0]
for i in range(len(c)-1):
a=min(e[i+1],a//2)
d.append(a*(2**(i+2)-1))
if a==0:
break
print(max(d))
``` | output | 1 | 53,072 | 24 | 106,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest. | instruction | 0 | 53,073 | 24 | 106,146 |
Tags: greedy, sortings
Correct Solution:
```
import bisect
import sys
input=sys.stdin.readline
n=int(input())
ar=list(map(int,input().split()))
dic={}
for i in ar:
if(i in dic):
dic[i]+=1
else:
dic[i]=1
li=list(dic.values())
li.sort()
ans=max(li)
le=len(li)
for i in range(1,n+1):
l=0
r=le
po=0
st=i
while(l!=r):
xx=bisect.bisect(li,st,l,r)
if(xx==l):
l+=1
po+=1
st*=2
elif(xx==le):
if(st>li[-1]):
break
elif(st==li[-1]):
po+=1
break
else:
if(st==li[xx-1]):
l=xx
else:
l=xx+1
po+=1
st*=2
ans=max(ans,i*(2**po-1))
print(ans)
``` | output | 1 | 53,073 | 24 | 106,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest. | instruction | 0 | 53,074 | 24 | 106,148 |
Tags: greedy, sortings
Correct Solution:
```
from collections import Counter,defaultdict
n=int(input())
l=list(map(int,input().split()))
c=Counter(l)
l1=[]
for i in c:
l1.append(c[i])
l1.sort()
ans=l1[-1]
l2=[defaultdict(int) for i in range(len(l1))]
for i in range(len(l1)):
a=1
while a<=l1[i]:
if l2[i][a]==1:
a+=1
continue
c=a
j=i+1
x=a
while j<len(l1) and l1[j]>=2*x:
l2[j][2*x]=1
c+=2*x
x*=2
j+=1
ans=max(ans,c)
a+=1
print(ans)
``` | output | 1 | 53,074 | 24 | 106,149 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest. | instruction | 0 | 53,075 | 24 | 106,150 |
Tags: greedy, sortings
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
for i in arr:
stdout.write(str(i)+' ')
stdout.write('\n')
range = xrange # not for python 3.0+
n=input()
l=map(int,raw_input().split())
d=Counter(l)
l=d.values()
n=len(l)
l.sort()
ans=0
for i in range(1,l[-1]+1):
pos=n-1
cur=i
temp=i
while cur%2==0 and pos:
cur/=2
pos-=1
if l[pos]<cur:
break
temp+=cur
ans=max(ans,temp)
print ans
``` | output | 1 | 53,075 | 24 | 106,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from collections import Counter
n = int(input())
a = sorted(Counter(map(int, input().split())).values())
n = len(a)
ans = 0
for j in range(1, a[-1] + 1):
tt = j
i = n - 1
while not j & 1 and i > 0:
j //= 2
i -= 1
if a[i] < j:
break
tt += j
ans = max(ans, tt)
print(ans)
``` | instruction | 0 | 53,076 | 24 | 106,152 |
Yes | output | 1 | 53,076 | 24 | 106,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from collections import defaultdict
import bisect
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
cnt = defaultdict(lambda : 0)
for i in a:
cnt[i] += 1
x = [cnt[i] for i in cnt]
x.sort()
ans = 0
l = x[-1]
for i in range(1, l + 1):
y = bisect.bisect_left(x, i - 0.5)
j = 2 * i
cnt = i
while True:
z = bisect.bisect_left(x, j - 0.5)
if y >= z:
z = y + 1
if z == len(x):
ans = max(ans, cnt)
break
y = z
cnt += j
j *= 2
print(ans)
``` | instruction | 0 | 53,077 | 24 | 106,154 |
Yes | output | 1 | 53,077 | 24 | 106,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
def main():
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
dic = dict()
for i in a:
if dic.get(i) is None:
dic[i] = 1
else:
dic[i] += 1
b = list(dic.values())
b.sort()
def solve(first):
x = first
i = -1
m = len(b)
ret = 0
while i+1 < m:
l, r = i+1, m-1
while l <= r:
mid = (l + r) // 2
if b[mid] >= x:
i = mid
r = mid - 1
else:
l = mid + 1
if i < l:
break
ret += x
x *= 2
return ret
ans = 0
for i in range(1, n+1):
ans = max(ans, solve(i))
print(ans)
main()
``` | instruction | 0 | 53,078 | 24 | 106,156 |
Yes | output | 1 | 53,078 | 24 | 106,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from collections import *
from math import *
def ch(mx):
if(mx > n):
return 0
m = l[0]//(1<<(mx-1))
for i in range(mx):
m = min(m,l[i]//(1<<(mx-i-1)))
return m*((1<<mx)-1)
n = int(input())
mx = ceil(log(n,2))
a = list(map(int,input().split()))
c = Counter(a)
l = list(c.values())
l.sort(reverse = True)
n = len(l)
ans = 1
for i in range(1,mx+1):
ans = max(ans,ch(i))
print(ans)
``` | instruction | 0 | 53,079 | 24 | 106,158 |
Yes | output | 1 | 53,079 | 24 | 106,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
#------------------Sublime--------------------------------------#
sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(input()))
def In():return(map(int,input().split()))
else:
#------------------PYPY FAst I/o--------------------------------#
def I():return (int(stdin.readline()))
def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
def main():
try:
n=I()
l=list(In())
d=dict(l)
z=[]
for x in d:
z.append(d[x])
z.sort()
#print(z)
count=0
n1=len(z)
for i in range(1,(z[-1])+1):
ans=0
temp=i
j=0
while temp<=z[-1] and j<n1:
pos=find_gt(z,temp)
if pos==-1:
break
else:
ans+=temp
temp*=2
j+=1
if ans>count:
count=ans
#print(i)
print(count)
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
#for _ in range(I()):main()
for _ in range(1):main()
``` | instruction | 0 | 53,080 | 24 | 106,160 |
No | output | 1 | 53,080 | 24 | 106,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
n=int(input())
d=dict()
l=list(map(int,input().split()))
for i in range(n):
if l[i] not in d:
d.update({l[i]:1})
else:
d[l[i]]+=1
if len(d)==1:
for j in d:
print(d[j])
else:
ans1=0
if len(d)<=44:
a=[]
for j in sorted(d.values()):
a.append(j)
ans1=0
for i in range(len(a)):
e=a[i]
ans=0
for j in range(i+1,len(a)):
if e*2<=a[j]:
ans+=2*e
e*=2
else:
break
e=a[i]
for j in range(i,-1,-1):
if e%2!=0:
break
else:
ans+=e
e=e//2
ans1=max(ans1,ans)
e=a[i]-1
ans=0
for j in range(i+1,len(a)):
if e*2<=a[j]:
ans+=2*e
e*=2
else:
break
e=a[i]-1
for j in range(i,-1,-1):
if e%2!=0:
break
else:
ans+=e
e=e//2
ans1=max(ans1,ans)
t=0
ans=0
rt=1
for j in sorted(d.values(),reverse=True):
if t==0:
ans+=j
prev=j
t+=1
rt=1
else:
if t<=44:
rt=rt*2
e=prev//2
#print(e,rt)
if j>=e:
if e*2==prev:
ans+=e
prev=e
else:
if t<=28 and e>=rt-1:
ans+=e-rt+1
prev=e
else:
break
else:
if t>44 or (rt*2-1)*j>=ans:
ans=(rt*2-1)*j
prev=j
else:
break
t+=1
print(max(ans1,ans))
``` | instruction | 0 | 53,081 | 24 | 106,162 |
No | output | 1 | 53,081 | 24 | 106,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from collections import Counter
n = map(int,input().split())
arr = [int(x) for x in input().split()]
d = Counter(arr)
val = sorted(d.values(),reverse = True)
m = len(val)
ans = 0
fl = 0
for i in range(m-1):
if(val[i]//2<=val[i]+1):
ans+=2*val[i]//2
if(m==1):
print(*n)
else:
print(ans)
``` | instruction | 0 | 53,082 | 24 | 106,164 |
No | output | 1 | 53,082 | 24 | 106,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
n=int(input())
d=dict()
l=list(map(int,input().split()))
for i in range(n):
if l[i] not in d:
d.update({l[i]:1})
else:
d[l[i]]+=1
if len(d)==1:
for j in d:
print(d[j])
else:
t=0
ans=0
rt=1
for j in sorted(d.values(),reverse=True):
if t==0:
ans+=j
prev=j
t+=1
rt=1
else:
if t<=44:
rt=rt*2
e=prev//2
#print(e,rt)
if j>=e:
if e*2==prev:
ans+=e
prev=e
else:
if t<=28 and e>=rt-1:
ans+=e-rt+1
prev=e
else:
break
else:
if t>44 or (rt*2-1)*j>=ans:
ans=(rt*2-1)*j
prev=j
else:
break
t+=1
print(ans)
``` | instruction | 0 | 53,083 | 24 | 106,166 |
No | output | 1 | 53,083 | 24 | 106,167 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2 | instruction | 0 | 53,123 | 24 | 106,246 |
Tags: brute force, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
N, M = map(int, input().split())
mar = [-1] * 26
mir = [2000] * 26
mac = [-1] * 26
mic = [2000] * 26
X = [[-1 if a == "." else ord(a)-97 for a in input()] for i in range(N)]
# print(X)
ma = -1
for i in range(N):
for j in range(M):
k = X[i][j]
if k >= 0:
mar[k] = max(mar[k], i)
mir[k] = min(mir[k], i)
mac[k] = max(mac[k], j)
mic[k] = min(mic[k], j)
ma = max(ma, k)
f = 0
ans = 1
ANS = []
for k in range(ma+1)[::-1]:
if f and mar[k] == -1 and mir[k] == 2000:
ANS.append(ANS[-1])
elif mar[k] == mir[k]:
r = mar[k]
for c in range(mic[k], mac[k]+1):
if X[r][c] < k:
ans = 0
break
else:
ANS.append((r+1, mic[k]+1, r+1, mac[k]+1))
if ans == 0:
break
f = 1
elif mac[k] == mic[k]:
c = mac[k]
for r in range(mir[k], mar[k]+1):
if X[r][c] < k:
ans = 0
break
else:
ANS.append((mir[k]+1, c+1, mar[k]+1, c+1))
if ans == 0:
break
f = 1
else:
ans = 0
break
if ans == 0:
print("NO")
else:
print("YES")
print(len(ANS))
for a in ANS[::-1]:
print(*a)
``` | output | 1 | 53,123 | 24 | 106,247 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2 | instruction | 0 | 53,124 | 24 | 106,248 |
Tags: brute force, implementation
Correct Solution:
```
from collections import defaultdict as di
def solve():
n,m = map(int,input().split())
B = [input() for _ in range(n)]
pos = di(list)
for i in range(n):
b = B[i]
for j in range(m):
pos[b[j]].append((i,j))
if '.' in pos:
del pos['.']
C = [list('.'*m) for _ in range(n)]
moves = []
if pos:
mxx = max(pos)
for i in range(97,ord(mxx)+1):
c = chr(i)
if c not in pos:
pos[c] = pos[mxx]
P = pos[c]
if all(p[0] == P[0][0] for p in P):
mn = min(p[1] for p in P)
mx = max(p[1] for p in P)
i = P[0][0]
for j in range(mn,mx+1):
C[i][j] = c
moves.append((i+1,mn+1,i+1,mx+1))
elif all(p[1] == P[0][1] for p in P):
mn = min(p[0] for p in P)
mx = max(p[0] for p in P)
j = P[0][1]
for i in range(mn,mx+1):
C[i][j] = c
moves.append((mn+1,j+1,mx+1,j+1))
if [''.join(s) for s in C] == B:
print('YES')
print(len(moves))
for m in moves:
print(*m)
else:
print('NO')
def main():
t = int(input())
for _ in range(t):
solve()
######## Python 2 and 3 footer by Pajenegod and c1729
# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.
# So on cf, use PyPy2 for best string performance.
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
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, _ = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip()
bio = sys.stdout
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'0' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main()
``` | output | 1 | 53,124 | 24 | 106,249 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2 | instruction | 0 | 53,125 | 24 | 106,250 |
Tags: brute force, implementation
Correct Solution:
```
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations,groupby
import sys
import bisect
import string
import math
import time
import random
def S_():
return input()
def LS():
return [i for i in input().split()]
def I():
return int(input())
def MI():
return map(int,input().split())
def LI():
return [int(i) for i in input().split()]
def LI_():
return [int(i)-1 for i in input().split()]
def NI(n):
return [int(input()) for i in range(n)]
def NI_(n):
return [int(input())-1 for i in range(n)]
def StoI():
return [ord(i)-97 for i in input()]
def ItoS(nn):
return chr(nn+97)
def LtoS(ls):
return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
org_inp=[]
g=[[] for i in range(n)]
for i in range(E):
inp=LI()
org_inp.append(inp)
if index==0:
inp[0]-=1
inp[1]-=1
if len(inp)==2:
a,b=inp
g[a].append(b)
if not Directed:
g[b].append(a)
elif len(inp)==3:
a,b,c=inp
aa=(inp[0],inp[2])
bb=(inp[1],inp[2])
g[a].append(bb)
if not Directed:
g[b].append(aa)
return g,org_inp
def bit_combination(k,n=2):
rt=[]
for tb in range(n**k):
s=[tb//(n**bt)%n for bt in range(k)]
rt+=[s]
return rt
def show(*inp,end='\n'):
if show_flg:
print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()
def ran_input():
import random
n=random.randint(4,16)
rmin,rmax=1,10
a=[random.randint(rmin,rmax) for _ in range(n)]
return n,a
show_flg=False
show_flg=True
ans=0
t=I()
for _ in range(t):
h,w=LI()
ans=[]
t=[]
ng=False
rs=[[inf,-inf] for i in range(26)]
cs=[[inf,-inf] for i in range(26)]
for i in range(h):
s=input()
t.append(s)
for j in range(w):
if s[j]!='.':
k=ord(s[j])-97
rs[k][0]=min(rs[k][0],i+1)
rs[k][1]=max(rs[k][1],i+1)
cs[k][0]=min(cs[k][0],j+1)
cs[k][1]=max(cs[k][1],j+1)
ll=-1
for i in range(26):
if rs[i][0]!=inf:
ll=i
if ll==-1:
print('YES')
print(0)
continue
for i in range(ll+1)[::-1]:
if (rs[i][0]!=inf and rs[i][0]!=rs[i][1]) and (cs[i][0]!=inf and cs[i][0]!=cs[i][1]):
ng=True
break
else:
if rs[i][0]==inf:
ans.append(lsn)
else:
lsn=[rs[i][0],cs[i][0],rs[i][1],cs[i][1]]
ans.append(lsn)
for r in range(rs[i][0],rs[i][1]+1):
for c in range(cs[i][0],cs[i][1]+1):
#show(i,(r-1,c-1),t[r-1][c-1])
if ord(t[r-1][c-1])-97<i:
ng=True
#show(i,*rs[i],*cs[i])
if ng:
print('NO')
continue
else:
print('YES')
print(len(ans))
for i in ans[::-1]:
print(*i)
``` | output | 1 | 53,125 | 24 | 106,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2 | instruction | 0 | 53,126 | 24 | 106,252 |
Tags: brute force, implementation
Correct Solution:
```
# I stole this code from a stupid birb
from collections import defaultdict as di
def solve():
n,m = map(int,input().split())
B = [input().rstrip() for _ in range(n)]
pos = di(list)
for i in range(n):
b = B[i]
for j in range(m):
pos[b[j]].append((i,j))
if '.' in pos:
del pos['.']
C = [list('.'*m) for _ in range(n)]
moves = []
if pos:
mxx = max(pos)
for i in range(97,ord(mxx)+1):
c = chr(i)
if c not in pos:
pos[c] = pos[mxx]
P = pos[c]
if all(p[0] == P[0][0] for p in P):
mn = min(p[1] for p in P)
mx = max(p[1] for p in P)
i = P[0][0]
for j in range(mn,mx+1):
C[i][j] = c
moves.append((i+1,mn+1,i+1,mx+1))
elif all(p[1] == P[0][1] for p in P):
mn = min(p[0] for p in P)
mx = max(p[0] for p in P)
j = P[0][1]
for i in range(mn,mx+1):
C[i][j] = c
moves.append((mn+1,j+1,mx+1,j+1))
if [''.join(s) for s in C] == B:
print('YES')
print(len(moves))
for m in moves:
print(*m)
else:
print('NO')
def main():
t = int(input())
for _ in range(t):
solve()
######## Python 2 and 3 footer by Pajenegod and c1729
# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.
# So on cf, use PyPy2 for best string performance.
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
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()
bio = sys.stdout
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'0' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main()
``` | output | 1 | 53,126 | 24 | 106,253 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2 | instruction | 0 | 53,127 | 24 | 106,254 |
Tags: brute force, implementation
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, 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)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(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)
MOD=10**9+7
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
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
for _ in range (int(input())):
n,m=map(int,input().split())
a=[]
for i in range (n):
a.append(list(input()))
d=defaultdict(list)
check=[[0 for j in range (m)]for i in range (n)]
fake=[0,0,0,0]
mx=96
for ch in range (122,96,-1):
c=0
for i in range (n):
for j in range (m):
if a[i][j]==chr(ch):
#print(i,j,ch)
s=[i+1,j+1,i+1,j+1]
mx=max(mx,ch)
if fake[0]==0:
fake=s.copy()
check[i][j]=1
x=0
if i<n-1 and ord(a[i+1][j])>=ch:
k=i
while k<n-1 and ord(a[k+1][j])>=ch:
if ord(a[k+1][j])>ch and check[k+1][j]==0:
break
if ord(a[k+1][j])==ch:
x=1
k+=1
if x:
k=i
while k<n-1 and ord(a[k+1][j])>=ch:
if ord(a[k+1][j])>ch and check[k+1][j]==0:
break
k+=1
check[k][j]=1
s[2]=k+1
s[3]=j+1
if x==0 and j<m-1 and ord(a[i][j+1])>=ch:
k=j
while k<m-1 and ord(a[i][k+1])>=ch:
if ord(a[i][k+1])>ch and check[i][k+1]==0:
break
k+=1
check[i][k]=1
s[2]=i+1
s[3]=k+1
c=1
d[ch]=s
break
if c:
break
#print(check)
#print(d)
res=[]
c=1
for i in range (n):
for j in range (m):
if a[i][j]!='.' and check[i][j]==0:
c=0
break
if c==0:
break
for i in range (97,mx+1):
if len(d[i])==0:
res.append(fake)
elif len(d[i])==4:
res.append(d[i])
if c:
print("YES")
print(len(res))
for i in res:
print(*i)
else:
print("NO")
``` | output | 1 | 53,127 | 24 | 106,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2 | instruction | 0 | 53,128 | 24 | 106,256 |
Tags: brute force, implementation
Correct Solution:
```
import sys, io
inp = io.BytesIO(sys.stdin.buffer.read())
input = lambda: inp.readline().rstrip().decode('ascii')
from collections import defaultdict as di
def solve():
n,m = map(int,input().split())
B = [input() for _ in range(n)]
pos = di(list)
for i in range(n):
b = B[i]
for j in range(m):
pos[b[j]].append((i,j))
if '.' in pos:
del pos['.']
C = [list('.'*m) for _ in range(n)]
moves = []
if pos:
mxx = max(pos)
for i in range(97,ord(mxx)+1):
c = chr(i)
if c not in pos:
pos[c] = pos[mxx]
P = pos[c]
if all(p[0] == P[0][0] for p in P):
mn = min(p[1] for p in P)
mx = max(p[1] for p in P)
i = P[0][0]
for j in range(mn,mx+1):
C[i][j] = c
moves.append((i+1,mn+1,i+1,mx+1))
elif all(p[1] == P[0][1] for p in P):
mn = min(p[0] for p in P)
mx = max(p[0] for p in P)
j = P[0][1]
for i in range(mn,mx+1):
C[i][j] = c
moves.append((mn+1,j+1,mx+1,j+1))
if [''.join(s) for s in C] == B:
print('YES')
print(len(moves))
for m in moves:
print(*m)
else:
print('NO')
def main():
t = int(input())
for _ in range(t):
solve()
main()
``` | output | 1 | 53,128 | 24 | 106,257 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2 | instruction | 0 | 53,129 | 24 | 106,258 |
Tags: brute force, implementation
Correct Solution:
```
import sys
#sys.stdin = open('inE', 'r')
t = int(input())
for ti in range(t):
n,m = map(int, input().split())
a = []
for i in range(n):
a.append(input())
top = {}
bot = {}
l = {}
r = {}
res = True
for y in range(n):
for x in range(m):
c = a[y][x]
if c != '.':
if c not in top:
top[c] = y
bot[c] = y
l[c] = x
r[c] = x
else:
if top[c] == y:
r[c] = x
xi = x - 1
while xi >= 0 and a[y][xi] != c:
if a[y][xi] == '.' or a[y][xi] < c:
res = False
xi -= 1
elif l[c] == x and r[c] == x:
bot[c] = y
yi = y - 1
while yi >= 0 and a[yi][x] != c:
if a[yi][x] == '.' or a[yi][x] < c:
res = False
yi -= 1
else:
res = False
if len(top) == 0:
sys.stdout.write('YES\n')
sys.stdout.write('0\n')
elif res:
mxc = max(top)
cnt = ord(mxc) & 31
sys.stdout.write('YES\n')
sys.stdout.write(str(cnt)+'\n')
for i in range(cnt):
ci = chr(ord('a') + i)
if ci not in top:
ci = mxc
sys.stdout.write(f'{top[ci]+1} {l[ci]+1} {bot[ci]+1} {r[ci]+1}\n')
else:
sys.stdout.write('NO\n')
``` | output | 1 | 53,129 | 24 | 106,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2 | instruction | 0 | 53,130 | 24 | 106,260 |
Tags: brute force, implementation
Correct Solution:
```
import sys
def solve():
H, W = map(int, sys.stdin.readline().split())
G = [[ord(s) - 46 for s in sys.stdin.readline().strip()] for _ in range(H)]
k = 0
inf = 10**9
Stbw = [-inf]*77
Stsw = [inf]*77
Stbh = [-inf]*77
Stsh = [inf]*77
for h, G1 in enumerate(G, 1):
k = max(k, max(G1))
for w, g in enumerate(G1, 1):
if not g:
continue
Stbw[g] = max(Stbw[g], w)
Stsw[g] = min(Stsw[g], w)
Stbh[g] = max(Stbh[g], h)
Stsh[g] = min(Stsh[g], h)
if k == 0:
return []
A = []
for j in range(k, 50, -1):
if Stbw[j] == -inf and Stbh[j] == -inf:
A.append(A[-1])
continue
bw = (Stbw[j] == Stsw[j])
bh = (Stbh[j] == Stsh[j])
if not bw and not bh:
return False
if bw:
w = Stbw[j]- 1
for h in range(Stsh[j]-1, Stbh[j]):
if G[h][w] < j:
return False
elif bh:
h = Stbh[j]- 1
for w in range(Stsw[j]-1, Stbw[j]):
if G[h][w] < j:
return False
A.append((Stsh[j], Stsw[j], Stbh[j], Stbw[j]))
return A[::-1]
if __name__ == '__main__':
T = int(input())
for _ in range(T):
ans = solve()
if ans is False:
print('NO')
continue
print('YES')
print(len(ans))
for a in ans:
print(*a)
``` | output | 1 | 53,130 | 24 | 106,261 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
import sys
input = sys.stdin.readline
def solve():
H, W = map(int, input().split())
G = [[ord(s) - 46 for s in input().strip()] for _ in range(H)]
Gy = list(map(list, zip(*G)))
k = 0
St = [None]*77
for h, G1 in enumerate(G, 1):
k = max(k, max(G1))
for w, g in enumerate(G1, 1):
if not g:
continue
if St[g] is None:
St[g] = (h, w)
elif type(St[g]) == tuple:
h1, w1 = St[g]
if h == h1:
St[g] = h
elif w == w1:
St[g] = -w
else:
return False
else:
if St[g] == h or St[g] == -w:
continue
return False
if k == 0:
return []
A = []
for j in range(k, 50, -1):
if St[j] is None:
A.append(A[-1])
continue
if type(St[j]) == tuple:
A.append(St[j]*2)
continue
x = St[j]
if x > 0:
Gh = G[x-1]
p = None
e = None
for ig, g in enumerate(Gh):
if g == j:
p = ig
break
for ig, g in enumerate(Gh[::-1]):
ig = W - 1 - ig
if g == j:
e = ig
break
for ig in range(p, e + 1):
if Gh[ig] < j:
return False
A.append((x, p+1, x, e+1))
else:
Gw = Gy[-x-1]
p = None
e = None
for ig, g in enumerate(Gw):
if g == j:
p = ig
break
for ig, g in enumerate(Gw[::-1]):
ig = H - 1 - ig
if g == j:
e = ig
break
for ig in range(p, e + 1):
if Gw[ig] < j:
return False
A.append((p+1, -x, e+1, -x))
return A[::-1]
if __name__ == '__main__':
T = int(input())
for _ in range(T):
ans = solve()
if ans is False:
print('NO')
continue
print('YES')
print(len(ans))
for a in ans:
print(*a)
``` | instruction | 0 | 53,131 | 24 | 106,262 |
Yes | output | 1 | 53,131 | 24 | 106,263 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
def naiveSolve():
return
from collections import defaultdict
def main():
t=int(input())
allans=[]
for _ in range(t):
# n=2000
# m=2000
# grid=['a'*m]*m
n,m=readIntArr()
grid=[]
for __ in range(n):
grid.append(input())
ok=True
snakes=defaultdict(lambda:[]) # {'a':[coords]}
for i in range(n):
for j in range(m):
if grid[i][j]!='.':
snakes[grid[i][j]].append([i,j])
l=len(snakes[grid[i][j]])
if l>max(n,m): # to prevent MLE
ok=False
break
if ok==False:
break
if ok==False:
allans.append(['NO'])
continue
startEnd=dict() # {'a':[start coord, end coord]}
# check that snake is straight
for letter,coords in snakes.items():
if len(coords)>=2:
if coords[0][0]==coords[1][0]: # horizontal
for i in range(2,len(coords)):
if coords[0][0]!=coords[i][0]:
ok=False
break
elif coords[0][1]==coords[1][1]: # vertical
for i in range(2,len(coords)):
if coords[0][1]!=coords[i][1]:
ok=False
break
else: # diagonal. wrong
ok=False
if ok==False: break
startEnd[letter]=[coords[0],coords[-1]]
if ok==False:
allans.append(['NO'])
continue
# created adjacency dict for topological sort
adj=defaultdict(lambda:[])
for letter,[start,end] in startEnd.items():
if start[0]==end[0]: # horizontal
for col in range(start[1],end[1]+1):
letter2=grid[start[0]][col]
if letter!=letter2:
if letter2=='.': # broken snake
ok=False
else:
adj[letter].append(letter2)
else: # vertical
for row in range(start[0],end[0]+1):
letter2=grid[row][start[1]]
if letter!=letter2:
if letter2=='.': # broken snake
ok=False
else:
adj[letter].append(letter2)
if ok==False:
allans.append(['NO'])
continue
# # check adj for cycles
chars=startEnd.keys()
# v=set()
# for c in chars:
# if c in v: continue
# v.add(c)
# path={c}
# stack=[c]
# while stack:
# c=stack.pop()
# for nex in adj[c]:
# if nex in path: # has cycle
# ok=False
# break
# else:
# path.add(c)
# if c not in v:
# v.add(c)
# stack.append(c)
# if ok==False: # cycle detected
# allans.append(['NO'])
# continue
# # run topological sort
# order=[]
# v=set()
# def dfs(c):
# for nex in adj[c]:
# if nex not in v:
# v.add(nex)
# dfs(nex)
# order.append(c)
# for c in chars:
# if c not in v:
# v.add(c)
# dfs(c)
# order.reverse()
# I just realised that he has to write in order a,b,c...
# check that adj does not contradict order
for u in chars:
for v in adj[u]:
if v<u:
ok=False
if ok==False: # cycle detected
allans.append(['NO'])
continue
order=sorted(chars)
allans.append(['YES'])
if len(order)==0:
allans.append([0])
else:
allC='abcdefghijklmnopqrstuvwxyz'
maxChar=order[-1]
maxCharIdx=allC.index(maxChar)
allans.append([maxCharIdx+1])
dr,dc=startEnd[order[-1]][0] # dummy row and column to put other snakes
dr+=1; dc+=1
for i in range(maxCharIdx+1):
if allC[i] not in order: # the other chars < maxChar that are not in grid
allans.append([dr,dc,dr,dc])
else:
[r1,c1],[r2,c2]=startEnd[allC[i]]
r1+=1; c1+=1; r2+=1; c2+=1
allans.append([r1,c1,r2,c2])
multiLineArrayOfArraysPrint(allans)
return
import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(l,r):
print('? {} {}'.format(l,r))
sys.stdout.flush()
return int(input())
def answerInteractive(x):
print('! {}'.format(x))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
``` | instruction | 0 | 53,132 | 24 | 106,264 |
Yes | output | 1 | 53,132 | 24 | 106,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
from collections import defaultdict as di
def solve():
n,m = map(int,input().split())
B = [input() for _ in range(n)]
pos = di(list)
for i in range(n):
b = B[i]
for j in range(m):
pos[b[j]].append((i,j))
if '.' in pos:
del pos['.']
C = [list('.'*m) for _ in range(n)]
moves = []
if pos:
mxx = max(pos)
for i in range(97,ord(mxx)+1):
c = chr(i)
if c not in pos:
pos[c] = pos[mxx]
P = pos[c]
if all(p[0] == P[0][0] for p in P):
mn = min(p[1] for p in P)
mx = max(p[1] for p in P)
i = P[0][0]
for j in range(mn,mx+1):
C[i][j] = c
moves.append((i+1,mn+1,i+1,mx+1))
elif all(p[1] == P[0][1] for p in P):
mn = min(p[0] for p in P)
mx = max(p[0] for p in P)
j = P[0][1]
for i in range(mn,mx+1):
C[i][j] = c
moves.append((mn+1,j+1,mx+1,j+1))
if [''.join(s) for s in C] == B:
print('YES')
print(len(moves))
for m in moves:
print(*m)
else:
print('NO')
def main():
t = int(input())
for _ in range(t):
solve()
######## Python 2 and 3 footer by Pajenegod and c1729
# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.
# So on cf, use PyPy2 for best string performance.
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(object):
newlines = 0
def __init__(self, file):
self.stream = BytesIO()
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = self.stream.write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.stream.seek((self.stream.tell(), self.stream.seek(0,2), self.stream.write(s))[0])
return s
def read(self):
while self._fill(): pass
return self.stream.read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return self.stream.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.stream.getvalue())
self.stream.truncate(0), self.stream.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()
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'0' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main()
``` | instruction | 0 | 53,133 | 24 | 106,266 |
Yes | output | 1 | 53,133 | 24 | 106,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
from sys import stdin, stdout
from collections import defaultdict
def process():
let_to_squares = defaultdict(list)
square_to_lets = defaultdict(list)
n, m = map(int, stdin.readline().split())
grid = []
for i in range(n):
row = stdin.readline().strip()
grid.append([c for c in row])
max_let = 0
for i in range(n):
for j in range(m):
let = grid[i][j]
if let == '.':
continue
max_let = max(ord(let), max_let)
let_to_squares[let].append((i, j))
# print(let_to_squares)
if max_let == 0:
stdout.write("YES\n0\n")
return
for i in range(n):
for j in range(m):
if ord(grid[i][j]) == max_let:
any_square = [i+1, j+1, i+1, j+1]
remaining = defaultdict(int)
coords = {}
for let in let_to_squares.keys():
row_min = n+1
col_min = m+1
row_max = -1
col_max = -1
for i, j in let_to_squares[let]:
row_min = min(row_min, i)
row_max = max(row_max, i)
col_min = min(col_min, j)
col_max = max(col_max, j)
coords[let] = [row_min+1, col_min+1, row_max+1, col_max+1]
if row_min != row_max and col_min != col_max:
stdout.write("NO\n")
return
for i in range(row_min, row_max+1):
for j in range(col_min, col_max+1):
if grid[i][j] != let:
if grid[i][j] == '.':
stdout.write("NO\n")
return
remaining[let] += 1
square_to_lets[(i, j)].append(let)
for let in range(max_let, ord('a')-1, -1):
if remaining[chr(let)] != 0:
stdout.write("NO\n")
return
for i,j in let_to_squares[chr(let)]:
for new_let in square_to_lets[(i, j)]:
remaining[new_let] -= 1
stdout.write("YES\n")
stdout.write(str(max_let-ord('a')+1) + "\n")
for let in range(ord('a'), max_let+1):
if chr(let) in coords:
t = coords[chr(let)]
else:
t = any_square
stdout.write(' '.join(map(str, t)) + "\n")
t = int(stdin.readline())
for it in range(t):
process()
``` | instruction | 0 | 53,134 | 24 | 106,268 |
Yes | output | 1 | 53,134 | 24 | 106,269 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
mat=[]
final_mat=[]
for i in range(n):
l=list(input())
w=['.']*m
final_mat.append(w)
mat.append(l)
dic=dict()
flag=False
for i in range(n):
for j in range(m):
if mat[i][j]!='.':
flag=True
if mat[i][j] in dic:
dic[mat[i][j]].append([i,j])
else:
dic[mat[i][j]]=[[i,j]]
for k in dic.keys():
dic[k]=sorted(dic[k])
if flag:
# print(dic)
flag=True
for k in dic.keys():
setx=set()
sety=set()
for w in dic[k]:
setx.add(w[0])
sety.add(w[1])
if len(setx)==1 or len(sety)==1:
flag=True
else:
flag=False
break
final_mat[dic[k][0][0]][dic[k][0][1]]=k
final_mat[dic[k][-1][0]][dic[k][-1][1]]=k
if flag==False:
print('NO')
else:
ans=dict()
li=['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a']
f=1
main='-1'
count=0
for i in li:
if i in dic:
if f==1:
f=0
main=i
x=dic[i][0][0]
y=dic[i][0][1]
xend=dic[i][-1][0]
yend=dic[i][-1][1]
if x==xend:
for j in range(y,yend+1):
if final_mat[x][j]=='.':
final_mat[x][j]=i
elif y==yend:
for j in range(x,xend+1):
if final_mat[j][y]=='.':
final_mat[j][y]=i
ans[i]=i
else:
if main!='-1':
ans[i]=main
#print(final_mat)
flag=True
for i in range(n):
for j in range(m):
if mat[i][j]==final_mat[i][j]:
pass
else:
flag=False
if flag==False:
break
if flag==False:
print('NO')
else:
print('YES')
print(26-li.index(main))
for i in li[::-1]:
# print('in',i)
if i in ans:
print(dic[ans[i]][0][0]+1,dic[ans[i]][0][1]+1,dic[ans[i]][-1][0]+1,dic[ans[i]][-1][1]+1)
else:
break
else:
print('YES')
print('0')
``` | instruction | 0 | 53,135 | 24 | 106,270 |
No | output | 1 | 53,135 | 24 | 106,271 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
import bisect
import decimal
from decimal import Decimal
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
# sys.setrecursionlimit(200000)
# mod = 10**9+7
# mod = 998244353
decimal.getcontext().prec = 46
def primeFactors(n):
prime = set()
while n % 2 == 0:
prime.add(2)
n = n//2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
prime.add(i)
n = n//i
if n > 2:
prime.add(n)
return list(prime)
def getFactors(n) :
factors = []
i = 1
while i <= math.sqrt(n):
if (n % i == 0) :
if (n // i == i) :
factors.append(i)
else :
factors.append(i)
factors.append(n//i)
i = i + 1
return factors
def modefiedSieve():
mx=10**7+1
sieve=[-1]*mx
for i in range(2,mx):
if sieve[i]==-1:
sieve[i]=i
for j in range(i*i,mx,i):
if sieve[j]==-1:
sieve[j]=i
return sieve
def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
num = []
for p in range(2, n+1):
if prime[p]:
num.append(p)
return num
def lcm(a,b):
return (a*b)//math.gcd(a,b)
def sort_dict(key_value):
return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]))
def list_input():
return list(map(int,input().split()))
def num_input():
return map(int,input().split())
def string_list():
return list(input())
def decimalToBinary(n):
return bin(n).replace("0b", "")
def binaryToDecimal(n):
return int(n,2)
def DFS(n,s,adj):
visited = [False for i in range(n+1)]
stack = []
stack.append(s)
while (len(stack)):
s = stack[-1]
stack.pop()
if (not visited[s]):
visited[s] = True
for node in adj[s]:
if (not visited[node]):
stack.append(node)
def maxSubArraySum(a,size):
maxint = 10**10
max_so_far = -maxint - 1
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
def find_snake(i,j,mat,n,m):
symbol = mat[i][j]
mat[i][j] = '.'
col = j+1
flag = False
while col < m:
if mat[i][col] == '.' or ord(mat[i][col]) < ord(symbol):
break
elif mat[i][col] == symbol:
flag = True
mat[i][col] = '.'
col += 1
if not(flag):
row = i+1
while row < n:
if mat[row][j] == '.' or ord(mat[row][j]) < ord(symbol):
break
elif mat[row][j] == symbol:
if j-1 >= 0 and j+1 < m and (mat[row][j-1] != '.' and mat[row][j+1] != '.'):
if mat[row][j-1] == mat[row][j+1] and ord(mat[row][j-1]) < ord(symbol):
mat[row][j] = mat[row][j-1]
else:
left_elements = set(mat[row][:j])
right_elements = set(mat[row][j+1:])
both_side_present = sorted(list(left_elements.intersection(right_elements)))
if '.' in both_side_present:
both_side_present.pop(0)
if both_side_present == []:
mat[row][j] = '.'
else:
mat[row][j] = both_side_present[0]
else:
mat[row][j] = '.'
row += 1
if flag:
return (i+1,col)
return (row,j+1)
def solve():
n,m = num_input()
mat = []
for _ in range(n):
mat.append(list(input()))
visited = []
ans = {}
for i in range(n):
for j in range(m):
if mat[i][j] != '.':
if mat[i][j] in visited:
print('NO')
return
else:
visited.append(mat[i][j])
symbol = mat[i][j]
start = (i+1,j+1)
end = find_snake(i,j,mat,n,m)
if end == -1:
print('NO')
return
ans[symbol] = (start,end)
print('YES')
final = []
arr = sorted(list(ans.keys()))
for i in range(26):
if arr == []:
break
if chr(ord('a')+i) == arr[0]:
(x,y),(u,v) = ans[arr[0]]
final.append([x,y,u,v])
arr.pop(0)
else:
(x,y),(u,v) = ans[arr[-1]]
final.append([x,y,u,v])
print(len(final))
for i in final:
print(*i)
t = 1
t = int(input())
for _ in range(t):
solve()
``` | instruction | 0 | 53,136 | 24 | 106,272 |
No | output | 1 | 53,136 | 24 | 106,273 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
def mp():
return map(int, input().split())
t = int(input())
for tt in range(t):
n, m = mp()
s = [[j for j in input()] for i in range(n)]
ver = [[0] * 26 for i in range(m + 1)]
hor = [[0] * 26 for i in range(n + 1)]
max_hor = [-1] * 26
max_ver = [-1] * 26
for i in range(n):
for j in range(m):
if s[i][j] != '.':
c = ord(s[i][j]) - 97
hor[i][c] += 1
ver[j][c] += 1
if hor[i][c] > hor[max_hor[c]][c]:
max_hor[c] = i
if ver[j][c] > ver[max_ver[c]][c]:
max_ver[c] = j
ans = [0] * 26
qi = qj = -1
for k in range(25, -1, -1):
if max_hor[k] != -1 and max_ver[k] != -1:
i, j = max_hor[k], max_ver[k]
old_i, old_j = i, j
while i < n and j < m and (ord(s[i][j]) == 97 + k or s[i][j] == '?'):
s[i][j] = '?'
qi, qj = i, j
if hor[i][k] > ver[j][k]:
j += 1
else:
i += 1
if i == old_i:
ans[k] = (old_i + 1, old_j + 1, i + 1, j)
else:
ans[k] = (old_i + 1, old_j + 1, i, j + 1)
fail = False
for i in range(n):
for j in range(m):
if not s[i][j] in ['.', '?']:
fail = True
if fail:
print('NO')
else:
print('YES')
print(len(ans) - ans.count(0))
before = (ans.count(0) != 26)
for i in range(26):
if ans[i] != 0:
print(*ans[i])
before = False
elif before:
print(qi + 1, qj + 1, qi + 1, qj + 1)
``` | instruction | 0 | 53,137 | 24 | 106,274 |
No | output | 1 | 53,137 | 24 | 106,275 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
import string
t = int(input())
for test_case in range(t):
n, m = [int(_) for _ in input().split()]
board = [input() for _ in range(n)]
snakes = {}
for i, row in enumerate(board):
for j, l in enumerate(row):
if l != '.':
if l not in snakes:
snakes[l] = (i, i, j, j)
else:
snakes[l] = (min(snakes[l][0], i), max(snakes[l][1], i), min(snakes[l][2], j), max(snakes[l][3], j))
valid = True
for _, (r1, r2, c1, c2) in snakes.items():
if r1 != r2 and c1 != c2:
valid = False
if not valid:
print('NO')
continue
for i, row in enumerate(board):
for j, l in enumerate(row):
if l != '.':
for s, (r1, r2, c1, c2) in snakes.items():
if r1 <= i and i <= r2 and c1 <= j and j <= c2:
if l < s:
valid = False
if valid:
print('YES')
if snakes:
max_letter = max(snakes.keys())
k = string.ascii_lowercase.find(max_letter) + 1
print(k)
for i in range(k):
l = string.ascii_lowercase[i]
if l in snakes:
print(' '.join([str(snakes[l][0] + 1), str(snakes[l][2] + 1), str(snakes[l][1] + 1), str(snakes[l][3] + 1)]))
else:
print(' '.join([str(snakes[max_letter][0] + 1), str(snakes[max_letter][2] + 1), str(snakes[max_letter][1] + 1), str(snakes[max_letter][3] + 1)]))
else:
print(0)
else:
print('NO')
``` | instruction | 0 | 53,138 | 24 | 106,276 |
No | output | 1 | 53,138 | 24 | 106,277 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter.
He sent to the coordinator a set of n problems. Each problem has it's quality, the quality of the i-th problem is ai (ai can be positive, negative or equal to zero). The problems are ordered by expected difficulty, but the difficulty is not related to the quality in any way. The easiest problem has index 1, the hardest problem has index n.
The coordinator's mood is equal to q now. After reading a problem, the mood changes by it's quality. It means that after the coordinator reads a problem with quality b, the value b is added to his mood. The coordinator always reads problems one by one from the easiest to the hardest, it's impossible to change the order of the problems.
If after reading some problem the coordinator's mood becomes negative, he immediately stops reading and rejects the problemset.
Polycarp wants to remove the minimum number of problems from his problemset to make the coordinator's mood non-negative at any moment of time. Polycarp is not sure about the current coordinator's mood, but he has m guesses "the current coordinator's mood q = bi".
For each of m guesses, find the minimum number of problems Polycarp needs to remove so that the coordinator's mood will always be greater or equal to 0 while he reads problems from the easiest of the remaining problems to the hardest.
Input
The first line of input contains two integers n and m (1 ≤ n ≤ 750, 1 ≤ m ≤ 200 000) — the number of problems in the problemset and the number of guesses about the current coordinator's mood.
The second line of input contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the qualities of the problems in order of increasing difficulty.
The third line of input contains m integers b1, b2, ..., bm (0 ≤ bi ≤ 1015) — the guesses of the current coordinator's mood q.
Output
Print m lines, in i-th line print single integer — the answer to the problem with q = bi.
Example
Input
6 3
8 -5 -4 1 -7 4
0 7 3
Output
2
0
1
Submitted Solution:
```
#!/usr/bin/env python3
import sys
from collections import namedtuple
from itertools import accumulate
#Rango = namedtuple('Rango', ['desde', 'hasta'])
n,m= tuple(map(int, input().split()))
lista = list(map(int, input().split()))
mood = list(map(int, input().split()))
acumulada = list(accumulate(lista))
#rangos =[Rango(desde= - min(acumulada),hasta=sys.maxsize)]
#print("acumulada=",acumulada)
rangos=[]
minimau =0
for i in acumulada:
if (i<0 and i<minimau):
minimau=i
rangos.append(-i)
rangos.append(sys.maxsize)
#print("rangos=",rangos)
tam = len(rangos)-1
#print(mood)
for i in mood:
for k,j in enumerate(rangos):
if i<j:
print(tam-k)
break
``` | instruction | 0 | 53,535 | 24 | 107,070 |
No | output | 1 | 53,535 | 24 | 107,071 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.