message stringlengths 2 23.4k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 129 108k | cluster float64 6 6 | __index_level_0__ int64 258 216k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.
You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.
Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.
Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below:
* A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process.
* A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive.
* A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit.
Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.
During the minification process words are renamed in a systematic fashion using the following algorithm:
1. Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list.
2. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on.
The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules.
Input
The first line of the input contains a single integer n (0 β€ n β€ 40) β the number of reserved tokens.
The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35).
The third line of the input contains a single integer m (1 β€ m β€ 40) β the number of lines in the input source code.
Next m lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens.
Output
Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way.
Examples
Input
16
fun while return var { } ( ) , ; > = + ++ - --
9
fun fib(num) { # compute fibs
var return_value = 1, prev = 0, temp;
while (num > 0) {
temp = return_value; return_value = return_value + prev;
prev = temp;
num--;
}
return return_value;
}
Output
fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}
Input
10
( ) + ++ : -> >> >>: b c)
2
($val1++ + +4 kb) >> :out
b-> + 10 >>: t # using >>:
Output
(a+++ +4c )>> :d b->+10>>:e
Submitted Solution:
```
from collections import defaultdict
n = int(input())
reserved = set(input().split())
m = int(input())
lines = [ input().split('#')[0].split() for _ in range(m) ]
tokens = sum(lines, [])
def isword(t):
return not t[0].isdigit() and all(c.isalnum() or c == '_' or c == '$' for c in t)
def ok(t):
return t in reserved or t.isdigit() or isword(t)
def tokenize(t):
res = []
i = 0
n = len(t)
while i < n:
for j in range(n, i, -1):
if ok(t[i:j]):
res.append(t[i:j])
i = j
break
return res
tokens = sum(map(tokenize, tokens), [])
dig = 1
k = 0
limit = 26
def next_token():
global dig, k, limit
if k == limit:
k = 0
dig += 1
limit = 26 ** dig
w = []
l = k
for _ in range(dig):
w += chr(ord('a') + l % 26)
l //= 26
w = ''.join(reversed(w))
k += 1
if w in reserved:
return next_token()
return w
dc = defaultdict(next_token)
def replace(t):
if t in reserved or t.isdigit():
return t
return dc[t]
def can_append(a, b, bg):
if len(a) == 0:
return True
#if a not in reserved and b not in reserved:
# return False
for s in bg:
if len(a) - s > 21:
continue
for i in range(len(b)):
if ok(a[s:] + b[:i+1]):
#print(a, b, a[s:] + b[:i+1])
return False
#print('can append', a, b)
return True
res = ['']
begin = []
for t in map(replace, tokens):
if not can_append(res[-1], t, begin):
res.append('')
begin = []
begin.append(len(res[-1]))
res[-1] += t
print(' '.join(res))
``` | instruction | 0 | 67,290 | 6 | 134,580 |
No | output | 1 | 67,290 | 6 | 134,581 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example. | instruction | 0 | 67,307 | 6 | 134,614 |
Tags: dfs and similar, greedy, implementation, sortings, strings
Correct Solution:
```
def construct(uniq):
cst = []
for i in range(1, len(uniq), 2):
cst.append(uniq[i])
for i in range(0, len(uniq), 2):
cst.append(uniq[i])
return cst
T = int(input())
for t in range(T):
s = input()
uniq = []
dc = {}
for c in s:
num = ord(c)
if ord(c) in dc:
dc[num] += 1
else:
dc[num] = 1
uniq.append(num)
uniq.sort()
cst = construct(uniq)
uniq.reverse()
cst_rev = construct(uniq)
ans = "No answer"
# validate
i = 1
while i < len(cst):
if abs(cst[i] - cst[i-1]) == 1:
break
i += 1
if i == len(cst):
ans = "cst"
i = 1
while i < len(cst_rev):
if abs(cst_rev[i] - cst_rev[i-1]) == 1:
break
i += 1
if i == len(cst_rev):
ans = "cst_rev"
if ans != "No answer":
if ans == "cst":
temp = cst
else:
temp = cst_rev
ans = ""
for i in temp:
for j in range(dc[i]):
ans += chr(i)
print(ans)
``` | output | 1 | 67,307 | 6 | 134,615 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example. | instruction | 0 | 67,308 | 6 | 134,616 |
Tags: dfs and similar, greedy, implementation, sortings, strings
Correct Solution:
```
def check(odd,even):
count=0
arr=odd+even
for i in range(len(arr)-1):
if abs(ord(arr[i])-ord(arr[i+1]))==1:
count+=1
return(count)
q=int(input())
for i in range(q):
arr1=[]
arr2=[]
a=input()
for h in a:
if ord(h)%2==0:
arr1.append(h)
else:
arr2.append(h)
arr1.sort()
arr2.sort()
a1=check(arr1,arr2)
a2=check(arr2,arr1)
if a1==0:
print(''.join(arr1+arr2))
elif a2==0:
print(''.join(arr2+arr1))
else:
print('No answer')
``` | output | 1 | 67,308 | 6 | 134,617 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example. | instruction | 0 | 67,309 | 6 | 134,618 |
Tags: dfs and similar, greedy, implementation, sortings, strings
Correct Solution:
```
t=int(input())
while t>0:
s=input()
l1=[]
l2=[]
l3=[]
for i in range(len(s)):
if ord(s[i])%2==0:
l1.append(s[i])
else:
l2.append(s[i])
l1.sort()
l2.sort()
l3=l2+l1
l1=l1+l2
# print(l1)
flag=0
for i in range(1,len(l1)):
if abs(ord(l1[i])-ord(l1[i-1]))==1:
flag=1
else:
continue
flag1=0
for i in range(1,len(l3)):
if abs(ord(l3[i])-ord(l3[i-1]))==1:
flag1=1
else:
continue
s1=""
if flag==1 and flag1==1:
print("No answer")
else:
if flag==0:
for i in range(len(l1)):
s1+=l1[i]
print(s1)
else:
for i in range(len(l3)):
s1+=l3[i]
print(s1)
t-=1
``` | output | 1 | 67,309 | 6 | 134,619 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example. | instruction | 0 | 67,310 | 6 | 134,620 |
Tags: dfs and similar, greedy, implementation, sortings, strings
Correct Solution:
```
def solve(s):
ans=[]
c_count=[0] * 26
for c in s:
c_count[ord(c)-ord('a')] += 1
conflicts = [c_count[i-1] + c_count[(i+1)%len(c_count)] for i in range(len(c_count))]
conflicts[0] -= c_count[-1]
conflicts[-1] -= c_count[0]
# print(conflicts)
last = max(range(len(conflicts)), key=lambda i: 200*conflicts[i] + c_count[i] if c_count[i] else 0)
# print(last)
ans.append(chr(ord('a') + last))
c_count[last] -= 1
if last > 0:
conflicts[last-1] -= 1
if last < len(conflicts) - 1:
conflicts[last+1] -= 1
while any(c_count):
new = max(range(len(conflicts)), key=lambda i: 200*conflicts[i] + c_count[i] if c_count[i] and abs(i-last) != 1 else 0)
if not c_count[new] or abs(new-last) == 1:
print('No answer')
return
last = new
c_count[last] -= 1
if last > 0:
conflicts[last-1] -= 1
if last < len(conflicts) - 1:
conflicts[last+1] -= 1
ans.append(chr(ord('a') + last))
print(''.join(ans))
t=int(input())
for _ in range(t):
solve(input())
# s=list(input())
# s.sort()
# n=len(s)
# for i in range(n):
# if abs()
# ans.append(s[(i+i)%n])
``` | output | 1 | 67,310 | 6 | 134,621 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example. | instruction | 0 | 67,311 | 6 | 134,622 |
Tags: dfs and similar, greedy, implementation, sortings, strings
Correct Solution:
```
def solve(s):
odd = ''
even = ''
x = []
y = []
for char in s:
if ord(char) % 2 == 1:
x.append(char)
else:
y.append(char)
x = sorted(x)
y = sorted(y)
x.reverse()
y.reverse()
odd = ''.join(x)
even = ''.join(y)
if (len(x) == 0):
return(even)
if len(y) == 0:
return(odd)
if abs(ord(x[len(x)-1]) - ord(y[0])) == 1 and abs(ord(y[len(y)-1]) - ord(x[0])) == 1:
return "No answer"
elif abs(ord(y[len(y) - 1]) - ord(x[0])) == 1:
return(odd + even)
else:
return(even + odd)
n = int(input())
for i in range(n):
print(solve(input()))
``` | output | 1 | 67,311 | 6 | 134,623 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example. | instruction | 0 | 67,312 | 6 | 134,624 |
Tags: dfs and similar, greedy, implementation, sortings, strings
Correct Solution:
```
t = int(input())
for i in range(t):
string = input()
odd = []
even = []
a = ord('a')
for j in range(len(string)):
if (ord(string[j]) - a) % 2 == 0:
even.append(string[j])
else:
odd.append(string[j])
even = sorted(even)
odd = sorted(odd)
if len(even) == 0:
s = ''
for j in range(len(odd)):
s = s + odd[j]
print(s)
elif len(odd) == 0:
s = ''
for j in range(len(even)):
s = s + even[j]
print(s)
elif abs(ord(even[0]) - ord(odd[-1])) != 1:
s = ''
for j in range(len(odd)):
s = s + odd[j]
for j in range(len(even)):
s = s + even[j]
print(s)
elif abs(ord(even[-1]) - ord(odd[0])) != 1:
s = ''
for j in range(len(even)):
s = s + even[j]
for j in range(len(odd)):
s = s + odd[j]
print(s)
else:
print("No answer")
``` | output | 1 | 67,312 | 6 | 134,625 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example. | instruction | 0 | 67,313 | 6 | 134,626 |
Tags: dfs and similar, greedy, implementation, sortings, strings
Correct Solution:
```
t = int(input())
for i in range(t):
s = input()
s = sorted(s)
t = s[0]
k = len(s)-1
j=0
cnt=0
k=0
asd = len(s)
while(cnt<(asd)):
# print(j,cnt,t,s)
if(j+1>=len(s)):
break
# print("hi", s[j+1], t[j])
if(s[j+1]==t[-1]):
t = t+s[j+1]
j+=1
k=0
# print("cont")
cnt+=1
continue
if k%2==0:
t = t + s[-1]
s = s[:-1]
while(t[-1]==s[-1]):
t = t + s[-1]
s = s[:-1]
cnt+=1
# print(s)
k+=1
else:
t = t + s[1+j]
j+=1
k+=1
cnt+=1
# print("final",j,s,t,cnt)
l = list(t)
cnt = 0
while abs(ord(t[0])-ord(t[-1]))!=1 and cnt<len(t):
t = t[-1] + t
t = t[:-1]
cnt+=1
ch=0
l = list(t)
for i in range(1,len(t)):
if abs(ord(l[i])-ord(l[i-1]))==1:
ch=1
if(ch==1):
print("No answer")
else:
print(t)
``` | output | 1 | 67,313 | 6 | 134,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example. | instruction | 0 | 67,314 | 6 | 134,628 |
Tags: dfs and similar, greedy, implementation, sortings, strings
Correct Solution:
```
t = int(input())
al = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
hash = {}
for i in range(26):
hash[al[i]] = i
for i in range(t):
s = list(input())
s.sort()
ans = ''
ans1= ''
for i in range(len(s)):
if hash[s[i]]%2 == 0:
ans+=s[i]
else:
ans1+=s[i]
c1 = ''.join(sorted(list(ans)))
c2 = ''.join(sorted(list(ans1)))
k = c1+c2
k1 = c2+c1
flag = 0
flag1 = 0
for i in range(len(s)-1):
if abs(hash[k[i]] - hash[k[i+1]]) == 1:
flag = 1
if abs(hash[k1[i]] - hash[k1[i+1]]) == 1:
flag1 = 1
if flag == 0:
print(k)
elif flag1 == 0:
print(k1)
else:
print("No answer")
``` | output | 1 | 67,314 | 6 | 134,629 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
Submitted Solution:
```
def check_condition(string):
flag = 0
for i in range(len(string)-1):
diff = abs(ord(string[i])-ord(string[i+1]))
if diff == 1:
flag = 1
break
return flag
t = int(input())
for i in range(t):
even = ""
odd = ""
string = input()
for c in string:
if ord(c)%2 == 0:
even = even+c
else:
odd = odd+c
even = ''.join(sorted(even))
odd = ''.join(sorted(odd))
ans1 = even+odd
ans2 = odd+even
flag1 = check_condition(ans1)
flag2 = check_condition(ans2)
if flag1 == 0:
print(ans1)
elif flag2 == 0:
print(ans2)
else:
print("No answer")
``` | instruction | 0 | 67,315 | 6 | 134,630 |
Yes | output | 1 | 67,315 | 6 | 134,631 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
Submitted Solution:
```
T = int(input())
for i in range(T):
counter = {}
string = input().strip()
for char in string:
counter[char] = counter.get(char, 0) + 1
chars = list(counter.keys())
chars.sort()
if len(chars) == 2 and abs(ord(chars[0]) - ord(chars[1])) == 1:
print("No answer")
elif len(chars) == 3 and abs(ord(chars[0]) - ord(chars[1])) == 1 \
and abs(ord(chars[1]) - ord(chars[2])) == 1:
print("No answer")
elif len(chars) == 3:
if abs(ord(chars[0]) - ord(chars[1])) == 1:
print(counter[chars[0]] * chars[0] +
counter[chars[2]] * chars[2] +
counter[chars[1]] * chars[1])
else:
print(counter[chars[2]] * chars[2] +
counter[chars[0]] * chars[0] +
counter[chars[1]] * chars[1])
else:
ans = []
if len(chars) > 1:
for idx in range(1, len(chars), 2):
ans.append(chars[idx]*counter[chars[idx]])
for idx in range(0, len(chars), 2):
ans.append(chars[idx]*counter[chars[idx]])
print("".join(ans))
``` | instruction | 0 | 67,316 | 6 | 134,632 |
Yes | output | 1 | 67,316 | 6 | 134,633 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
Submitted Solution:
```
# Author : raj1307 - Raj Singh
# Date : 05.07.2020
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def msi(): return map(str,input().strip().split(" "))
def li(): return list(mi())
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import log,sqrt,factorial,cos,tan,sin,radians
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *
#import threading
#from itertools import permutations
#Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[1]
def sort2(l):return sorted(l, key=getKey,reverse=True)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def ceil(x,y):
if x%y==0:
return x//y
else:
return x//y+1
def powerMod(x,y,p):
res = 1
x %= p
while y > 0:
if y&1:
res = (res*x)%p
y = y>>1
x = (x*x)%p
return res
def gcd(x, y):
while y:
x, y = y, x % y
return x
def isPrime(n) : # Check Prime Number or not
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def main():
for _ in range(ii()):
s=si()
n=len(s)
p=0
ff=0
while p<n:
ans=[s[p]]
f=[0]*n
f[p]=1
while True:
g=f[:]
for i in range(n):
if f[i]:
continue
if abs(abd[ans[-1]]-abd[s[i]])!=1:
f[i]=1
ans.append(s[i])
elif abs(abd[ans[0]]-abd[s[i]])!=1:
f[i]=1
ans.insert(0,s[i])
if g==f:
break
flag=1
for i in range(n):
if f[i]==0:
flag=0
break
p+=1
if flag:
ff=1
print(''.join(ans))
break
if ff==0:
print('No answer')
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
#dmain()
# Comment Read()
``` | instruction | 0 | 67,317 | 6 | 134,634 |
Yes | output | 1 | 67,317 | 6 | 134,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
Submitted Solution:
```
import sys
T=int(input())
for t in range(T):
q=True
s=input()
n=len(s)
a=[]
b=[]
x=[]
for i in range(n):
o=ord(s[i])
if o%2==0:
a.append(o)
else:
b.append(o)
if len(a)==0 or len(b)==0:
print(s)
q=False
if q:
a.sort()
b.sort()
if abs(a[-1]-b[0])!=1:
q=False
x=a+b
if abs(b[-1]-a[0])!=1:
q=False
x=b+a
if q:
print('No answer')
else:
s=''
for i in range(n):
s+=chr(x[i])
print(s)
``` | instruction | 0 | 67,318 | 6 | 134,636 |
Yes | output | 1 | 67,318 | 6 | 134,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
Submitted Solution:
```
t = int(input())
for i in range(t):
cc = sorted(list(input()))
n=len(cc)
ccc = ['']*n
j=0
k=1-n%2
while(k<n):
ccc[k] = cc[j]
j+=1
k+=2
j=n-1
k=n-2
while(k>=0):
ccc[k] = cc[j]
j-=1
k-=2
ye = True
for i in range(1,n):
if ord(ccc[j])==ord(ccc[j-1])-1 or ord(ccc[j])==ord(ccc[j-1])+1:
print("No answer")
ye = False
break
if(ye==True):
print(''.join(ccc))
``` | instruction | 0 | 67,319 | 6 | 134,638 |
No | output | 1 | 67,319 | 6 | 134,639 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import Counter
T=int(input())
Q=[input().strip() for i in range(T)]
for S in Q:
C=Counter(S)
ANS=[]
if len(C)==1:
print(S)
continue
LI=list(C.keys())
LI.sort()
L=len(LI)
#print(LI)
i=0
while max(C.values()):
NOW=LI[i]
for j in range(1,L):
if abs(ord(LI[i])-ord(LI[(i+j)%L]))>1 and C[LI[(i+j)%L]]>0:
i=(i+j)%L
break
else:
print("No answer")
break
while C[LI[i]]>0:
ANS.append(LI[i])
C[LI[i]]-=1
else:
print("".join(ANS))
``` | instruction | 0 | 67,320 | 6 | 134,640 |
No | output | 1 | 67,320 | 6 | 134,641 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
Submitted Solution:
```
for _ in range(int(input())):
no_ans = False
ans = []
s = input()
c = list(sorted(set(s)))
if len(c) == 1:
ans = [c[0]]
elif len(c) == 2:
if ord(c[1]) - ord(c[1]) == 1:
no_ans = True
else:
ans = [c[0], c[1]]
elif len(c) == 3:
if ord(c[-1]) - ord(c[0]) == 2:
no_ans = True
elif ord(c[1]) - ord(c[0]) > 1:
ans = [c[2], c[0], c[1]]
else:
ans = [c[0], c[2], c[1]]
else:
ans = list(reversed(c[0:-1:2])) + [c[-1]] + c[1:-1:2]
res = ''.join([ch * s.count(ch) for ch in ans])
print("No answer" if no_ans else res)
``` | instruction | 0 | 67,321 | 6 | 134,642 |
No | output | 1 | 67,321 | 6 | 134,643 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=300006, 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)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:max(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <=key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
for ik in range(int(input())):
s=input()
f=0
for i in range(len(s)):
if abs(ord(s[i])-ord(s[i-1]))==1:
f=1
break
if f==0:
print(s)
continue
d=defaultdict(int)
n=len(s)
for i in range(n):
d[s[i]]+=1
l=[]
cou=[]
for i in sorted(d):
l.append(i)
cou.append(d[i])
if len(l)==2:
if ord(l[0])-ord(l[1])==-1:
print("No answer")
else:
print(s)
elif len(l)==3:
if ord(l[0])-ord(l[1])==-1 and ord(l[1])-ord(l[2])==-1:
print("No answer")
else:
if ord(l[0])-ord(l[1])==-1:
print(l[0]*cou[0]+l[2]*cou[2]+l[1]*cou[1])
elif ord(l[1])-ord(l[2])==-1:
print(l[2]*cou[2]+l[0]*cou[0]+l[1]*cou[1])
else:
print(s)
elif len(l)==1:
print(s)
else:
ans=""
#print(l)
t=int(math.ceil(len(l)/2))
#print(t)
for i in range(len(l)//2):
ans+=l[t]*cou[t]+l[i]*cou[i]
t+=1
if len(l)%2==1:
if abs(ord(ans[-1])-ord(l[len(l)//2]))==1:
ans=l[len(l)//2]*cou[len(l)//2]+ans
else:
ans+=l[len(l)//2]*cou[len(l)//2]
print(ans)
``` | instruction | 0 | 67,322 | 6 | 134,644 |
No | output | 1 | 67,322 | 6 | 134,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 67,832 | 6 | 135,664 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
from collections import defaultdict, deque
def main():
n,m = map(int, input().split())
cap = [None]*(m+1)
same_cap = defaultdict(list)
q = deque()
def apply_cap(a, c):
if cap[a] is not None:
return cap[a] == c
q.append((a,c))
while q:
b = q.pop()
if b[1] == c:
if cap[b[0]] is None:
cap[b[0]] = c
q.extend(same_cap[b[0]])
same_cap[b[0]] = []
elif cap[b[0]]!=c:
return False
return True
def same(a,b):
same_cap[b].append((a,True))
same_cap[a].append((b,False))
if cap[a] == False:
return apply_cap(b, False)
if cap[b] == True:
return apply_cap(a, True)
return True
def process(p,c):
lp = p[0]
lc = c[0]
for i in range(1, min(lp,lc)+1):
if p[i]>c[i]:
return apply_cap(p[i], True) and apply_cap(c[i], False)
if p[i]<c[i]:
return same(p[i], c[i])
return lp<=lc
p = list(map(int, input().split()))
for i in range(n-1):
c = list(map(int, input().split()))
if not process(p, c):
print ('No')
break
p = c
else:
print ('Yes')
res = []
for i,b in enumerate(cap):
if b:
res.append(i)
print(len(res))
print(' '.join(map(str,res)))
main()
``` | output | 1 | 67,832 | 6 | 135,665 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 67,833 | 6 | 135,666 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
import os,io,sys
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,m=map(int,input().split())
a=[-1]*m
p=[]
for i in range(n):
r=list(map(int,input().split()))
p.append(r)
flag=0
graph0=[]
graph1=[]
for i in range(m):
graph0.append([])
graph1.append([])
for i in range(n-2,-1,-1):
st=0
for j in range(1,min(p[i][0],p[i+1][0])+1):
let1=p[i][j]
let2=p[i+1][j]
if let1==let2:
continue
if let1<let2:
graph0[let1-1].append(let2-1)
graph1[let2-1].append(let1-1)
st=1
break
else:
if a[let1-1]==0 or a[let2-1]==1:
flag=1
a[let1-1]=1
a[let2-1]=0
st=1
break
if st==0:
if p[i][0]>p[i+1][0]:
flag=1
if flag:
break
if flag:
print('No')
sys.exit()
set0=set()
stack=[]
for i in range(m):
if a[i]==0:
stack.append(i)
while stack:
i=stack.pop()
if i in set0:
continue
set0.add(i)
for j in graph0[i]:
stack.append(j)
set1=set()
for i in range(m):
if a[i]==1:
stack.append(i)
while stack:
i=stack.pop()
if i in set0:
print('No')
sys.exit()
if i in set1:
continue
set1.add(i)
for j in graph1[i]:
stack.append(j)
print('Yes')
print(len(set1))
ans=[]
for i in set1:
ans.append(str(i+1))
print(' '.join(ans))
``` | output | 1 | 67,833 | 6 | 135,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 67,834 | 6 | 135,668 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n,m = LI()
a = [LI()[1:] for _ in range(n)]
d = collections.defaultdict(set)
m = set()
p = set()
for i in range(n-1):
b = a[i]
c = a[i+1]
bl = len(b)
cl = len(c)
f = False
for j in range(min(bl,cl)):
if b[j] == c[j]:
continue
if b[j] < c[j]:
d[c[j]].add(b[j])
else:
m.add(b[j])
p.add(c[j])
f = True
break
if not f and bl > cl:
return 'No'
if p & m:
return 'No'
ds = set(d.keys())
t = ds & m
mm = set()
mm |= m
while t:
mm |= t
m -= t
for c in t:
ds.remove(c)
for k in d[c]:
if k not in mm:
m.add(k)
if p & m:
return 'No'
t = ds & m
print('Yes')
m |= mm
if len(m) == 0:
return 0
print(len(m))
return ' '.join(map(str, list(m)))
print(main())
``` | output | 1 | 67,834 | 6 | 135,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 67,835 | 6 | 135,670 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
"""
created by shhuan at 2017/10/18 16:22
"""
M, N = map(int, input().split())
words = []
for i in range(M):
words.append([int(x) for x in input().split()][1:])
# all elements in C should be capitalized
C = set()
# E[u][v] means if we capitalize u, we must capitalize v
E = collections.defaultdict(list)
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
if len(w1) > len(w2) and w1[:len(w2)] == w2:
print('No')
exit(0)
for j in range(min(len(w1), len(w2))):
if w1[j] < w2[j]:
E[w2[j]].append(w1[j])
break
elif w1[j] > w2[j]:
C.add(w1[j])
break
# add all letters should be capitalized based on E
A = {u for u in C}
while A:
B = set(itertools.chain.from_iterable([E[u] for u in A]))
A = B - C
C |= B
# check
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
for j in range(min(len(w1), len(w2))):
a, b = w1[j], w2[j]
d = [a in C, b in C]
if a < b:
if d == [False, True]:
print('No')
exit(0)
break
elif a > b:
if d != [True, False]:
print('No')
exit(0)
break
print('Yes')
print(len(C))
if C:
print(" ".join(map(str, sorted(C))))
``` | output | 1 | 67,835 | 6 | 135,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 67,836 | 6 | 135,672 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
"""
created by shhuan at 2017/10/18 16:22
"""
M, N = map(int, input().split())
words = []
for i in range(M):
words.append([int(x) for x in input().split()][1:])
# all elements in C should be capitalized
C = set()
# E[u][v] means if we capitalize u, we must capitalize v
E = collections.defaultdict(list)
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
if len(w1) > len(w2) and w1[:len(w2)] == w2:
print('No')
exit(0)
for j in range(min(len(w1), len(w2))):
if w1[j] < w2[j]:
E[w2[j]].append(w1[j])
break
elif w1[j] > w2[j]:
C.add(w1[j])
break
# add all letters should be capitalized based on E
A = {u for u in C}
while A:
B = set(itertools.chain.from_iterable([E[u] for u in A]))
A = B - C
C |= B
# check
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
for j in range(min(len(w1), len(w2))):
a, b = w1[j], w2[j]
d = [a in C, b in C]
if a < b:
if d == [False, True]:
print('No')
exit(0)
break
elif a > b:
if d != [True, False]:
print('No')
exit(0)
break
print('Yes')
print(len(C))
if C:
print(" ".join(map(str, sorted(C))))
# Made By Mostafa_Khaled
``` | output | 1 | 67,836 | 6 | 135,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 67,837 | 6 | 135,674 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
import math
import collections
import bisect
import heapq
import time
import random
import itertools
M, N = map(int, input().split())
words = []
for i in range(M):
words.append([int(x) for x in input().split()][1:])
C = set()
E = collections.defaultdict(list)
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
if len(w1) > len(w2) and w1[:len(w2)] == w2:
print('No')
exit(0)
for j in range(min(len(w1), len(w2))):
if w1[j] < w2[j]:
E[w2[j]].append(w1[j])
break
elif w1[j] > w2[j]:
C.add(w1[j])
break
A = {u for u in C}
while A:
B = set(itertools.chain.from_iterable([E[u] for u in A]))
A = B - C
C |= B
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
for j in range(min(len(w1), len(w2))):
a, b = w1[j], w2[j]
d = [a in C, b in C]
if a < b:
if d == [False, True]:
print('No')
exit(0)
break
elif a > b:
if d != [True, False]:
print('No')
exit(0)
break
print('Yes')
print(len(C))
if C:
print(" ".join(map(str, sorted(C))))
``` | output | 1 | 67,837 | 6 | 135,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | instruction | 0 | 67,838 | 6 | 135,676 |
Tags: 2-sat, dfs and similar, graphs, implementation
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=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)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m=map(int,input().split())
l=[]
for i in range(n):
l.append(list(map(int,input().split())))
c=[0]*(m+1)
ans=[]
f=0
graph=defaultdict(list)
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j==int(l[i+1][0]) and int(l[i+1][0])<int(l[i][0]):
if c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
c[l[i][j]] = 1
break
else:
f = 1
break
if l[i][j] >=l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
if c[l[i][j]] == 0:
c[l[i][j]] = 1
break
else:
f = 1
break
else:
graph[l[i + 1][j]].append(l[i][j])
break
elif c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
c[l[i][j]] = 1
break
else:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
if c[l[i][j]]==0:
c[l[i][j]]=1
break
else:
f=1
break
elif l[i][j]<l[i+1][j] or c[l[i][j]]>c[l[i+1][j]]:
graph[l[i+1][j]].append(l[i][j])
break
if f==1:
break
if f==1:
print("No")
sys.exit(0)
f=0
visited=[False]*(m+1)
def dfs(v,t):
stack=[]
stack.append((v,t))
while(len(stack)>0):
v,t=stack.pop()
c[v] = max(t, c[v])
visited[v] = True
for i in graph[v]:
c[i]=max(c[i],c[v])
if visited[i]==False:
stack.append((i,c[v]))
for i in range(1,m+1):
if visited[i]==False and c[i]==1:
dfs(i,c[i])
for i in range(1,m+1):
if c[i]==1:
ans.append(i)
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j == int(l[i + 1][0]) and int(l[i+1][0])<int(l[i][0]):
if c[l[i+1][j]]>c[l[i][j]]:
f=1
break
if l[i][j] >=l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
f=1
break
else:
break
if c[l[i + 1][j]] > c[l[i][j]]:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
f=1
break
elif l[i][j] < l[i + 1][j] or c[l[i][j]]>c[l[i+1][j]]:
break
if f==1:
print("No")
else:
print("Yes")
print(len(ans))
print(*ans)
``` | output | 1 | 67,838 | 6 | 135,677 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
Submitted Solution:
```
import os,io,sys
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,m=map(int,input().split())
a=[-1]*m
p=[]
for i in range(n):
r=list(map(int,input().split()))
p.append(r)
flag=0
graph0=[]
graph1=[]
for i in range(m):
graph0.append([])
graph1.append([])
for i in range(n-2,-1,-1):
p1=[]
p2=[]
st=0
for j in range(1,min(p[i][0],p[i+1][0])+1):
let1=p[i][j]
let2=p[i+1][j]
if let1==let2:
continue
if let1<let2:
graph0[let1-1].append(let2-1)
graph1[let2-1].append(let1-1)
st=1
break
else:
if a[let1-1]==0 or a[let1-1]==1:
flag=1
a[let1-1]=1
a[let2-1]=0
st=1
break
if st==0:
if p[i][0]>p[i+1][0]:
flag=1
if flag:
break
if flag:
print('No')
sys.exit()
set0=set()
stack=[]
for i in range(m):
if a[i]==0:
stack.append(i)
while stack:
i=stack.pop()
if i in set0:
continue
set0.add(i)
for j in graph0[i]:
stack.append(j)
set1=set()
for i in range(m):
if a[i]==1:
stack.append(i)
while stack:
i=stack.pop()
if i in set0:
print('No')
sys.exit()
if i in set1:
continue
set1.add(i)
for j in graph1[i]:
stack.append(j)
print('Yes')
print(len(set1))
ans=[]
for i in set1:
ans.append(str(i+1))
print(' '.join(ans))
``` | instruction | 0 | 67,839 | 6 | 135,678 |
No | output | 1 | 67,839 | 6 | 135,679 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
Submitted Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
"""
created by shhuan at 2017/10/18 16:22
"""
M, N = map(int, input().split())
words = []
for i in range(M):
words.append([int(x) for x in input().split()][1:])
C = set()
E = collections.defaultdict(list)
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
for j in range(min(len(w1), len(w2))):
if w1[j] < w2[j]:
E[w2[j]].append(w1[j])
break
elif w1[j] > w2[j]:
C.add(w1[j])
break
A = {u for u in C}
while A:
B = set(itertools.chain.from_iterable([E[u] for u in A]))
A = B - C
C |= B
# check
for i in range(M-1):
w1 = words[i]
w2 = words[i+1]
for j in range(min(len(w1), len(w2))):
a, b = w1[j], w2[j]
d = [a in C, b in C]
if a < b:
if d == [False, True]:
print('No')
exit(0)
break
elif a > b:
if d != [True, False]:
print('No')
exit(0)
break
print('Yes')
print(len(C))
if C:
print(" ".join(map(str, sorted(C))))
``` | instruction | 0 | 67,840 | 6 | 135,680 |
No | output | 1 | 67,840 | 6 | 135,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=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)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m=map(int,input().split())
l=[]
for i in range(n):
l.append(list(map(int,input().split())))
c=defaultdict(int)
ans=[]
f=0
while(sum(c)!=10):
su=0
for i in range(10):
su+=c[i]
f=0
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j==int(l[i+1][0]):
if c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
ans.append(l[i][j])
c[l[i][j]] = 1
break
else:
f = 1
break
if l[i][j] > l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
if c[l[i][j]] == 0:
ans.append(l[i][j])
c[l[i][j]] = 1
break
else:
f = 1
break
else:
break
elif c[l[i+1][j]]>c[l[i][j]]:
if c[l[i][j]] == 0:
ans.append(l[i][j])
c[l[i][j]] = 1
break
else:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
if c[l[i][j]]==0:
ans.append(l[i][j])
c[l[i][j]]=1
break
else:
f=1
break
elif l[i][j]<l[i+1][j] or c[l[i][j]]>c[l[i+1][j]]:
break
if f==1:
break
if f==1:
break
su1 = 0
for i in range(10):
su1 += c[i]
if su==su1:
break
if f==1:
print("No")
sys.exit(0)
f=0
for i in range(n-1):
for j in range(1,int(l[i][0])+1):
if j == int(l[i + 1][0]):
if l[i][j] > l[i + 1][j] and c[l[i][j]] <= c[l[i + 1][j]]:
f=1
break
else:
break
if c[l[i + 1][j]] > c[l[i][j]]:
f = 1
break
elif l[i][j]>l[i+1][j] and c[l[i][j]]<=c[l[i+1][j]]:
f=1
break
elif l[i][j] < l[i + 1][j] or c[l[i][j]]>c[l[i+1][j]]:
break
if f==1:
print("No")
else:
print("Yes")
print(len(ans))
print(*ans)
``` | instruction | 0 | 67,841 | 6 | 135,682 |
No | output | 1 | 67,841 | 6 | 135,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
Submitted Solution:
```
from collections import defaultdict, deque
def main():
n,m = map(int, input().split())
cap = [None]*(m+1)
same_cap = defaultdict(list)
q = deque()
def apply_cap(a, c):
if cap[a] is not None:
return cap[a] == c
q.append(a)
while q:
b = q.pop()
if cap[b] is None:
cap[b] = c
q.extend(same_cap[b])
same_cap[b] = []
elif cap[b]!=c:
return False
return True
def same(a,b):
if cap[a] is None and cap[b] is None:
same_cap[b].append(a)
return True
elif cap[a] is None:
apply_cap(b, cap[a])
cap[a] = cap[b]
return True
elif cap[b] is None:
apply_cap(a, cap[b])
cap[b] = cap[a]
return True
else:
return cap[a] == cap[b]
def process(p,c):
lp = p[0]
lc = c[0]
for i in range(1, min(lp,lc)+1):
if p[i]>c[i]:
return apply_cap(p[i], True) and apply_cap(c[i], False)
if p[i]<c[i]:
return same(p[i], c[i])
return lp<=lc
p = list(map(int, input().split()))
for i in range(n-1):
c = list(map(int, input().split()))
if not process(p, c):
print ('No')
break
p = c
else:
print ('Yes')
res = []
for i,b in enumerate(cap):
if b:
res.append(i)
print(len(res))
print(' '.join(map(str,res)))
main()
``` | instruction | 0 | 67,842 | 6 | 135,684 |
No | output | 1 | 67,842 | 6 | 135,685 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and <image> and <image>.
The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.
Help Imp to find the maximum noise he can achieve by changing the order of the strings.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of strings in robot's memory.
Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Output
Print a single integer β the maxumum possible noise Imp can achieve by changing the order of the strings.
Examples
Input
4
ssh
hs
s
hhhs
Output
18
Input
2
h
s
Output
1
Note
The optimal concatenation in the first sample is ssshhshhhs. | instruction | 0 | 67,846 | 6 | 135,692 |
Tags: greedy, sortings
Correct Solution:
```
import functools
li=[]
def cmp(a,b):
if (a.count('s')/len(a))<(b.count('s')/len(b)) :
return 1
else:
return -1
for _ in range(int(input())):
s = input()
li.append(s)
li = sorted(li,key = functools.cmp_to_key(cmp))
li = ''.join(li)
c=ans=0
for i in li:
if i=='s':
c+=1
else:
ans+=c
print(ans)
``` | output | 1 | 67,846 | 6 | 135,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and <image> and <image>.
The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.
Help Imp to find the maximum noise he can achieve by changing the order of the strings.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of strings in robot's memory.
Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Output
Print a single integer β the maxumum possible noise Imp can achieve by changing the order of the strings.
Examples
Input
4
ssh
hs
s
hhhs
Output
18
Input
2
h
s
Output
1
Note
The optimal concatenation in the first sample is ssshhshhhs. | instruction | 0 | 67,848 | 6 | 135,696 |
Tags: greedy, sortings
Correct Solution:
```
def key(x):
try:
return x.count('h') / x.count('s')
except ZeroDivisionError:
return 10**9
n = int(input())
t = ''.join(sorted((input() for _ in range(n)), key=key))
res, cnt = 0, 0
for ti in t:
if ti == 's':
cnt += 1
if ti == 'h':
res += cnt
print(res)
``` | output | 1 | 67,848 | 6 | 135,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and <image> and <image>.
The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.
Help Imp to find the maximum noise he can achieve by changing the order of the strings.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of strings in robot's memory.
Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Output
Print a single integer β the maxumum possible noise Imp can achieve by changing the order of the strings.
Examples
Input
4
ssh
hs
s
hhhs
Output
18
Input
2
h
s
Output
1
Note
The optimal concatenation in the first sample is ssshhshhhs. | instruction | 0 | 67,849 | 6 | 135,698 |
Tags: greedy, sortings
Correct Solution:
```
import sys
def input():
return sys.stdin.readline().rstrip()
class STR():
def __init__(self, x, y):
self.s = x
self.h = y
def __gt__(self, other):
ss, sh = self.s, self.h
os, oh = other.s, other.h
return oh*ss <= os*sh
n = int(input())
ans = 0
que = []
for i in range(n):
S = list(input())
L = len(S)
ccnt = 0
hcnt = 0
for j in range(L - 1, -1, -1):
if S[j] == "h":
hcnt += 1
else:
ccnt += 1
ans += hcnt
que.append(STR(ccnt, hcnt))
que.sort(reverse=True)
ccnt, hcnt = 0, 0
for v in que:
nows, nowh = v.s, v.h
ans += nows*hcnt
hcnt += nowh
print(ans)
``` | output | 1 | 67,849 | 6 | 135,699 |
Provide a correct Python 3 solution for this coding contest problem.
Taro, a junior high school student, is working on his homework. Today's homework is to read Chinese classic texts.
As you know, Japanese language shares the (mostly) same Chinese characters but the order of words is a bit different. Therefore the notation called "returning marks" was invented in order to read Chinese classic texts in the order similar to Japanese language.
There are two major types of returning marks: 'Re' mark and jump marks. Also there are a couple of jump marks such as one-two-three marks, top-middle-bottom marks. The marks are attached to letters to describe the reading order of each letter in the Chinese classic text. Figure 1 is an example of a Chinese classic text annotated with returning marks, which are the small letters at the bottom-left of the big Chinese letters.
<image>
Figure 1: a Chinese classic text
Taro generalized the concept of jump marks, and summarized the rules to read Chinese classic texts with returning marks as below. Your task is to help Taro by writing a program that interprets Chinese classic texts with returning marks following his rules, and outputs the order of reading of each letter.
When two (or more) rules are applicable in each step, the latter in the list below is applied first, then the former.
1. Basically letters are read downwards from top to bottom, i.e. the first letter should be read (or skipped) first, and after the i-th letter is read or skipped, (i + 1)-th letter is read next.
2. Each jump mark has a type (represented with a string consisting of lower-case letters) and a number (represented with a positive integer). A letter with a jump mark whose number is 2 or larger must be skipped.
3. When the i-th letter with a jump mark of type t, number n is read, and when there exists an unread letter L at position less than i that has a jump mark of type t, number n + 1, then L must be read next. If there is no such letter L, the (k + 1)-th letter is read, where k is the index of the most recently read letter with a jump mark of type t, number 1.
4. A letter with a 'Re' mark must be skipped.
5. When the i-th letter is read and (i - 1)-th letter has a 'Re' mark, then (i - 1)-th letter must be read next.
6. No letter may be read twice or more. Once a letter is read, the letter must be skipped in the subsequent steps.
7. If no letter can be read next, finish reading.
Let's see the first case of the sample input. We begin reading with the first letter because of the rule 1. However, since the first letter has a jump mark 'onetwo2', we must follow the rule 2 and skip the letter. Therefore the second letter, which has no returning mark, will be read first.
Then the third letter will be read. The third letter has a jump mark 'onetwo1', so we must follow rule 3 and read a letter with a jump mark `onetwo2' next, if exists. The first letter has the exact jump mark, so it will be read third. Similarly, the fifth letter is read fourth, and then the sixth letter is read.
Although we have two letters which have the same jump mark 'onetwo2', we must not take into account the first letter, which has already been read, and must read the fourth letter. Now we have read all six letters and no letter can be read next, so we finish reading. We have read the second, third, first, fifth, sixth, and fourth letter in this order, so the output is 2 3 1 5 6 4.
Input
The input contains multiple datasets. Each dataset is given in the following format:
N
mark1
...
markN
N, a positive integer (1 β€ N β€ 10,000), means the number of letters in a Chinese classic text. marki denotes returning marks attached to the i-th letter.
A 'Re' mark is represented by a single letter, namely, 'v' (quotes for clarity). The description of a jump mark is the simple concatenation of its type, specified by one or more lowercase letter, and a positive integer. Note that each letter has at most one jump mark and at most one 'Re' mark. When the same letter has both types of returning marks, the description of the jump mark comes first, followed by 'v' for the 'Re' mark. You can assume this happens only on the jump marks with the number 1.
If the i-th letter has no returning mark, marki is '-' (quotes for clarity). The length of marki never exceeds 20.
You may assume that input is well-formed, that is, there is exactly one reading order that follows the rules above. And in the ordering, every letter is read exactly once.
You may also assume that the N-th letter does not have 'Re' mark.
The input ends when N = 0. Your program must not output anything for this case.
Output
For each dataset, you should output N lines. The first line should contain the index of the letter which is to be read first, the second line for the letter which is to be read second, and so on. All the indices are 1-based.
Example
Input
6
onetwo2
-
onetwo1
onetwo2
-
onetwo1
7
v
topbottom2
onetwo2
-
onetwo1
topbottom1
-
6
baz2
foo2
baz1v
bar2
foo1
bar1
0
Output
2
3
1
5
6
4
4
5
3
6
2
1
7
5
2
6
4
3
1 | instruction | 0 | 68,092 | 6 | 136,184 |
"Correct Solution:
```
import re
num = re.compile(r'\d+$')
def testcase_ends():
n = int(input())
if n == 0:
return 1
marks = [input().replace('-', '') for i in range(n)]
links = {}
bares = []
labels = {}
for i, mark in enumerate(marks, 1):
if not mark:
bares.append(i)
continue
v = False
if mark.endswith('v'):
mark = mark[:-1]
links[i+1] = i
v = True
m = num.search(mark)
if m is None:
continue
m = int(m.group())
mark = num.sub('', mark)
if m == 1:
if mark in labels:
links[i] = labels[mark]
del labels[mark]
if not v:
bares.append(i)
else:
if mark in labels:
links[i] = labels[mark]
labels[mark] = i
for w in bares:
print(w)
while w in links:
w = links[w]
print(w)
return 0
def main():
while not testcase_ends():
pass
if __name__ == '__main__':
main()
``` | output | 1 | 68,092 | 6 | 136,185 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110 | instruction | 0 | 68,429 | 6 | 136,858 |
Tags: constructive algorithms
Correct Solution:
```
def maxConsecutive(a):
i = 1
curr = 0
if a[0] == '1':
curr += 1
ans = curr
for i in range(len(a)):
if a[i] == '1':
curr += 1
else:
curr = 1
ans = max(ans, curr)
return ans
def countOne(a):
ans = 0
for i in range(len(a)):
if a[i] == '1':
ans += 1
return ans
a = input()
b = input()
if countOne(a) + countOne(a)%2 >= countOne(b):
print("YES")
else:
print("NO")
# 101101
# 01111
``` | output | 1 | 68,429 | 6 | 136,859 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110 | instruction | 0 | 68,430 | 6 | 136,860 |
Tags: constructive algorithms
Correct Solution:
```
a=input()
b=input()
coa=0
cob=0
for i in a:
if i=='1': coa+=1
for i in b:
if i=='1': cob+=1
if coa+(coa&1)>=cob:print('YES')
else:print('NO')
``` | output | 1 | 68,430 | 6 | 136,861 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110 | instruction | 0 | 68,431 | 6 | 136,862 |
Tags: constructive algorithms
Correct Solution:
```
def main():
a, b = (input().count('1') for _ in "ab")
print(("NO", "YES")[a + (a & 1) >= b])
if __name__ == '__main__':
main()
``` | output | 1 | 68,431 | 6 | 136,863 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110 | instruction | 0 | 68,432 | 6 | 136,864 |
Tags: constructive algorithms
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
a,b = input().strip(),input().strip()
x,y = a.count('1'),b.count('1')
if y > x+(x&1):
print('NO')
else:
print('YES')
# Fast IO Region
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")
if __name__ == "__main__":
main()
``` | output | 1 | 68,432 | 6 | 136,865 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110 | instruction | 0 | 68,433 | 6 | 136,866 |
Tags: constructive algorithms
Correct Solution:
```
a, b = input(), input()
x, y = a.count('1'), b.count('1')
print('YNEOS'[x + (x & 1) < y :: 2])
``` | output | 1 | 68,433 | 6 | 136,867 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110 | instruction | 0 | 68,434 | 6 | 136,868 |
Tags: constructive algorithms
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
def check(start):
if(a[-start:].count('1')%2): ch=1
else: ch=0
if(start==0):ch=0
# print(b[start],ch)
for i in b[start:]:
if(int(i)!=ch):
return False
ch^=1
return True
a=input()
b=input()
need_1=b.count('1')
have_1=a.count('1')
have_1+=have_1%2
if(need_1<=have_1): print("YES")
else: print("NO")
``` | output | 1 | 68,434 | 6 | 136,869 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110 | instruction | 0 | 68,435 | 6 | 136,870 |
Tags: constructive algorithms
Correct Solution:
```
a = input()
b = input()
na = 0
nb = 0
for i in a:
if i == '1':
na = na + 1
for i in b:
if i == '1':
nb = nb + 1
if na < nb and na % 2 == 0:
print("NO")
elif na < nb and nb - na > 1:
print("NO")
else:
print("YES")
``` | output | 1 | 68,435 | 6 | 136,871 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110 | instruction | 0 | 68,436 | 6 | 136,872 |
Tags: constructive algorithms
Correct Solution:
```
a = input()
b = input()
print('YES' if b.count('1') <= a.count('1') + (a.count('1') & 1) else 'NO')
``` | output | 1 | 68,436 | 6 | 136,873 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:
1. a1 is equivalent to b1, and a2 is equivalent to b2
2. a1 is equivalent to b2, and a2 is equivalent to b1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
Input
The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.
Output
Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.
Examples
Input
aaba
abaa
Output
YES
Input
aabb
abab
Output
NO
Note
In the first sample you should split the first string into strings "aa" and "ba", the second one β into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".
In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa". | instruction | 0 | 68,547 | 6 | 137,094 |
Tags: divide and conquer, hashing, sortings, strings
Correct Solution:
```
from collections import Counter
s = input().strip()
t = input().strip()
def solution(a, b):
def simulate(s, t, l):
if s == t:
return True
if l%2 == 0:
l //= 2
return ((simulate(s[:l], t[:l], l) and
simulate(s[l:], t[l:], l)) or
(simulate(s[:l], t[l:], l) and
simulate(s[l:], t[:l], l)))
return False
l = len(s)
if Counter(a) != Counter(b):
return False
return simulate(a, b, l)
print("YES" if solution(s, t) else "NO")
``` | output | 1 | 68,547 | 6 | 137,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:
1. a1 is equivalent to b1, and a2 is equivalent to b2
2. a1 is equivalent to b2, and a2 is equivalent to b1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
Input
The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.
Output
Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.
Examples
Input
aaba
abaa
Output
YES
Input
aabb
abab
Output
NO
Note
In the first sample you should split the first string into strings "aa" and "ba", the second one β into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".
In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa". | instruction | 0 | 68,548 | 6 | 137,096 |
Tags: divide and conquer, hashing, sortings, strings
Correct Solution:
```
def isEqual(a, b):
for i in range(0, len(a)):
if (a[i] != b[i]):
return False
return True
def lexicographic_minimal_string(s):
if (len(s) % 2 == 1):
return s
half = int(len(s) /2)
s1 = lexicographic_minimal_string(s[:half])
s2 = lexicographic_minimal_string(s[half:])
if s1 < s2:
return s1 + s2
return s2 + s1
a = input()
b = input()
a = lexicographic_minimal_string(a)
b = lexicographic_minimal_string(b)
if(isEqual(a,b)):
print("YES")
else:
print("NO")
'''
def isEqual(AS,BS,size):
for i in range(0, size):
if (a[AS+i] != b[BS+i]):
return False
return True
def equivalent(AS,BS,size):
global a
global b
if isEqual(AS,BS,size):
return True
half = int(size / 2)
if 2*half != size:
return False
if (equivalent(AS,BS+half,half) and equivalent(AS+half,BS,half)):
return True
if (equivalent(AS,BS,half) and equivalent(AS+half,BS+half,half)):
return True
return False
a = input()
b = input()
if equivalent(0,0,len(a)):
print("YES")
else:
print("NO")
'''
'''
a = input()
b = input()
def isEqual(a, b):
for i in range(0, len(a)):
if (a[i] != b[i]):
return False
return True
def equivalent(a, b):
if a == "":
return True
if isEqual(a, b):
return True
half = int(len(a) / 2)
if 2*half != len(a):
return False
if (equivalent(a[:half], b[:half]) and equivalent(a[half:], b[half:])):
return True
if (equivalent(a[:half], b[half:]) and equivalent(a[half:], b[:half])):
return True
return False
if equivalent(a,b):
print("YES")
else:
print("NO")
'''
``` | output | 1 | 68,548 | 6 | 137,097 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:
1. a1 is equivalent to b1, and a2 is equivalent to b2
2. a1 is equivalent to b2, and a2 is equivalent to b1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
Input
The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.
Output
Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.
Examples
Input
aaba
abaa
Output
YES
Input
aabb
abab
Output
NO
Note
In the first sample you should split the first string into strings "aa" and "ba", the second one β into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".
In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa". | instruction | 0 | 68,549 | 6 | 137,098 |
Tags: divide and conquer, hashing, sortings, strings
Correct Solution:
```
def isEq(a,b,la,lb):
if (la + lb ==2) or la%2 == 1 or lb%2 == 1:
if a == b:
return True
else:
return False
else:
a1 = a[:la//2]
a2 = a[la//2:]
b1 = b[:lb//2]
b2 = b[lb//2:]
res1 = isEq(a1,b1,la//2,lb//2)
res2 = isEq(a2,b2,la-la//2,lb-lb//2)
if (res1 and res2):
return True
else:
return False
def merge(s):
if len(s)%2 == 1:
return s
else:
left = merge(s[:len(s)//2])
right = merge(s[len(s)//2:])
if left < right:
return left + right
else:
return right+left
a = input()
b = input()
a = merge(a)
b = merge(b)
c = isEq(a,b,len(a),len(b))
if c:
print("YES")
else:
print("NO")
``` | output | 1 | 68,549 | 6 | 137,099 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:
1. a1 is equivalent to b1, and a2 is equivalent to b2
2. a1 is equivalent to b2, and a2 is equivalent to b1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
Input
The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.
Output
Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.
Examples
Input
aaba
abaa
Output
YES
Input
aabb
abab
Output
NO
Note
In the first sample you should split the first string into strings "aa" and "ba", the second one β into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".
In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa". | instruction | 0 | 68,551 | 6 | 137,102 |
Tags: divide and conquer, hashing, sortings, strings
Correct Solution:
```
first_string = input()
second_string = input()
def prepare_string(s):
if(len(s) % 2 != 0):
return s
str1 = prepare_string(s[0:int(len(s)/2)])
str2 = prepare_string(s[int(len(s)/2):len(s)])
if(str1 < str2):
return str1+str2
else:
return str2+str1
if(prepare_string(first_string) == prepare_string(second_string)):
print("YES")
else:
print("NO")
``` | output | 1 | 68,551 | 6 | 137,103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:
1. a1 is equivalent to b1, and a2 is equivalent to b2
2. a1 is equivalent to b2, and a2 is equivalent to b1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
Input
The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.
Output
Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.
Examples
Input
aaba
abaa
Output
YES
Input
aabb
abab
Output
NO
Note
In the first sample you should split the first string into strings "aa" and "ba", the second one β into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".
In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa". | instruction | 0 | 68,552 | 6 | 137,104 |
Tags: divide and conquer, hashing, sortings, strings
Correct Solution:
```
def equivalent(lhs, rhs):
if lhs == rhs:
return True
if len(lhs) % 2 == 1:
return lhs == rhs
length = len(lhs)
mid = length // 2
lhs1 = lhs[:mid]
lhs2 = lhs[mid:]
rhs1 = rhs[:mid]
rhs2 = rhs[mid:]
if equivalent(lhs1, rhs2) and equivalent(lhs2, rhs1):
return True
else:
return equivalent(lhs1,rhs1) and equivalent(rhs2, lhs2)
s1 = input()
s2 = input()
if equivalent(s1, s2):
print('YES')
else:
print('NO')
"""def igual(cadena1, cadena2, l):
if cadena1 == cadena2:
return True
hl = int(l / 2)
if l % 2 == 1: # Verificar longitud de la cadena
return cadena1 == cadena2 # Si es una cadena de una letra regresa la comparacion
else:
# Se parten las cadenas a la mitad para poder analizarlas
a1 = cadena1[0:hl]
b1 = cadena2[0:hl]
a2 = cadena1[hl:l]
b2 = cadena2[hl:l]
# Se llama de nuevo a la funcion para que realice la comparacion con las divisiones (Comparacion curzada)
if (igual(a1, b2, hl) and igual(a2, b1, hl)):
return True
else:
# Se hace la comparacion de partes
return (igual(a1, b1, hl) and igual(a2, b2, hl))
# Inputs
cadena1 = input()
cadena2 = input()
# If para imprimir
if igual(cadena1, cadena2, len(cadena1)):
print('YES')
else:
print('NO')"""
``` | output | 1 | 68,552 | 6 | 137,105 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:
1. a1 is equivalent to b1, and a2 is equivalent to b2
2. a1 is equivalent to b2, and a2 is equivalent to b1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
Input
The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.
Output
Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.
Examples
Input
aaba
abaa
Output
YES
Input
aabb
abab
Output
NO
Note
In the first sample you should split the first string into strings "aa" and "ba", the second one β into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".
In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa". | instruction | 0 | 68,554 | 6 | 137,108 |
Tags: divide and conquer, hashing, sortings, strings
Correct Solution:
```
def pairSort(s):
l = len(s)
if l%2:
return s
left = pairSort(s[:l//2])
right = pairSort(s[l//2:])
s = left + right if left>right else right+left
return s
s = input().strip()
t = input().strip()
s = pairSort(s)
t = pairSort(t)
print("YES") if s==t else print("NO")
``` | output | 1 | 68,554 | 6 | 137,109 |
Provide a correct Python 3 solution for this coding contest problem.
Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.
A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, `atcoder`, `zscoder` and `agc` are diverse words while `gotou` and `connect` aren't diverse words.
Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.
Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.
Constraints
* 1 \leq |S| \leq 26
* S is a diverse word.
Input
Input is given from Standard Input in the following format:
S
Output
Print the next word that appears after S in the dictionary, or `-1` if it doesn't exist.
Examples
Input
atcoder
Output
atcoderb
Input
abc
Output
abcd
Input
zyxwvutsrqponmlkjihgfedcba
Output
-1
Input
abcdefghijklmnopqrstuvwzyx
Output
abcdefghijklmnopqrstuvx | instruction | 0 | 68,765 | 6 | 137,530 |
"Correct Solution:
```
A=input()
l=set(chr(ord('a') + i) for i in range(26))
l2=list(l-set(A))
l2.sort()
if len(A)!=26:
print(A+l2[0])
else:
for i in reversed(range(25)):
for j in reversed(range(i+1,26)):
if A[i] < A[j]:
print(A[:i]+A[j])
exit()
else:
print(-1)
``` | output | 1 | 68,765 | 6 | 137,531 |
Provide a correct Python 3 solution for this coding contest problem.
Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.
A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, `atcoder`, `zscoder` and `agc` are diverse words while `gotou` and `connect` aren't diverse words.
Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.
Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.
Constraints
* 1 \leq |S| \leq 26
* S is a diverse word.
Input
Input is given from Standard Input in the following format:
S
Output
Print the next word that appears after S in the dictionary, or `-1` if it doesn't exist.
Examples
Input
atcoder
Output
atcoderb
Input
abc
Output
abcd
Input
zyxwvutsrqponmlkjihgfedcba
Output
-1
Input
abcdefghijklmnopqrstuvwzyx
Output
abcdefghijklmnopqrstuvx | instruction | 0 | 68,766 | 6 | 137,532 |
"Correct Solution:
```
S = input()
a = [chr(ord('a') + i) for i in range(26)]
for l in S:
a.remove(l)
if a != []:
print(S+a[0])
else:
b = []
k = 1
for l in reversed(S):
b.append(l)
b.sort()
if b[-1] != l:
print(S[0:-k]+b[b.index(l)+1])
break
k+=1
else:
print(-1)
``` | output | 1 | 68,766 | 6 | 137,533 |
Provide a correct Python 3 solution for this coding contest problem.
Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.
A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, `atcoder`, `zscoder` and `agc` are diverse words while `gotou` and `connect` aren't diverse words.
Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.
Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.
Constraints
* 1 \leq |S| \leq 26
* S is a diverse word.
Input
Input is given from Standard Input in the following format:
S
Output
Print the next word that appears after S in the dictionary, or `-1` if it doesn't exist.
Examples
Input
atcoder
Output
atcoderb
Input
abc
Output
abcd
Input
zyxwvutsrqponmlkjihgfedcba
Output
-1
Input
abcdefghijklmnopqrstuvwzyx
Output
abcdefghijklmnopqrstuvx | instruction | 0 | 68,767 | 6 | 137,534 |
"Correct Solution:
```
s = s0 = input()
d = {chr(c) for c in range(97, 123)}
for c in s:
d.remove(c)
if d:
s += min(d)
else:
for c in reversed(s):
s = s[:-1]
if d and any(c < e for e in d):
s += min(e for e in d if c < e)
break
d.add(c)
print(s if s else -1)
if s:
assert s0 < s
``` | output | 1 | 68,767 | 6 | 137,535 |
Provide a correct Python 3 solution for this coding contest problem.
Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.
A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, `atcoder`, `zscoder` and `agc` are diverse words while `gotou` and `connect` aren't diverse words.
Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.
Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.
Constraints
* 1 \leq |S| \leq 26
* S is a diverse word.
Input
Input is given from Standard Input in the following format:
S
Output
Print the next word that appears after S in the dictionary, or `-1` if it doesn't exist.
Examples
Input
atcoder
Output
atcoderb
Input
abc
Output
abcd
Input
zyxwvutsrqponmlkjihgfedcba
Output
-1
Input
abcdefghijklmnopqrstuvwzyx
Output
abcdefghijklmnopqrstuvx | instruction | 0 | 68,768 | 6 | 137,536 |
"Correct Solution:
```
import string
S = input()
abc = string.ascii_lowercase
if len(S) == 26:
for i in range(24, -1, -1):
cand = list(S[i+1:])
cand.sort()
for c in cand:
if ord(c) > ord(S[i]):
print(S[:i]+c)
exit(0)
print(-1)
else:
for l in abc:
if l not in S:
print(S+l)
exit()
``` | output | 1 | 68,768 | 6 | 137,537 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.