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
Provide tags and a correct Python 3 solution for this coding contest problem. Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol). For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo". Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result. For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him. You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard. Input The first line of the input contains one integer n (1 ≀ n ≀ 10^5) β€” the number of pairs to check. Further input contains n descriptions of pairs. The first line of each description contains a single non-empty word s consisting of lowercase Latin letters. The second line of the description contains a single non-empty word t consisting of lowercase Latin letters. The lengths of both strings are not greater than 10^6. It is guaranteed that the total length of all words s in the input is not greater than 10^6. Also, it is guaranteed that the total length of all words t in the input is not greater than 10^6. Output Output n lines. In the i-th line for the i-th pair of words s and t print YES if the word t could be printed by typing the word s. Otherwise, print NO. Examples Input 4 hello hello hello helloo hello hlllloo hello helo Output YES YES NO NO Input 5 aa bb codeforces codeforce polycarp poolycarpp aaaa aaaab abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxyz Output NO NO YES NO NO
instruction
0
76,784
6
153,568
Tags: implementation, strings Correct Solution: ``` for _ in range(int(input())): a=input() b=input() flag=True l1=[] c=1 s=a[0] for i in a[1:]: if i==s: c+=1 else: l1.append([s,c]) c=1 s=i l1.append([s,c]) l2=[] c=1 s=b[0] for i in b[1:]: if i==s: c+=1 else: l2.append([s,c]) c=1 s=i l2.append([s,c]) #print(l1,l2) j=0 for i in l1: if j==len(l2) or i[0]!=l2[j][0]: flag=False break else: if l2[j][1]<i[1]: flag=False break else: j+=1 if j==len(l2) and flag: print("YES") else: print("NO") ```
output
1
76,784
6
153,569
Provide tags and a correct Python 3 solution for this coding contest problem. Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol). For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo". Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result. For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him. You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard. Input The first line of the input contains one integer n (1 ≀ n ≀ 10^5) β€” the number of pairs to check. Further input contains n descriptions of pairs. The first line of each description contains a single non-empty word s consisting of lowercase Latin letters. The second line of the description contains a single non-empty word t consisting of lowercase Latin letters. The lengths of both strings are not greater than 10^6. It is guaranteed that the total length of all words s in the input is not greater than 10^6. Also, it is guaranteed that the total length of all words t in the input is not greater than 10^6. Output Output n lines. In the i-th line for the i-th pair of words s and t print YES if the word t could be printed by typing the word s. Otherwise, print NO. Examples Input 4 hello hello hello helloo hello hlllloo hello helo Output YES YES NO NO Input 5 aa bb codeforces codeforce polycarp poolycarpp aaaa aaaab abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxyz Output NO NO YES NO NO
instruction
0
76,785
6
153,570
Tags: implementation, strings Correct Solution: ``` n=int(input()) for i in range(n): a=input() b=input() if(len(b)<len(a)): print("NO") continue ans1=[] c=1 for i in range(len(a)-1): if(a[i]!=a[i+1]): ans1.append([a[i],c]) c=1 else: c=c+1 ans1.append([a[-1],c]) ans2=[] c=1 for i in range(len(b)-1): if(b[i]!=b[i+1]): ans2.append([b[i],c]) c=1 else: c=c+1 ans2.append([b[-1],c]) if(len(ans1)!=len(ans2)): print("NO") continue c=0 for i in range(len(ans1)): if(ans1[i][0]==ans2[i][0] and ans1[i][1]<=ans2[i][1]): c=c+1 if(c==len(ans1)): print("YES") else: print("NO") ```
output
1
76,785
6
153,571
Provide tags and a correct Python 3 solution for this coding contest problem. Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol). For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo". Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result. For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him. You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard. Input The first line of the input contains one integer n (1 ≀ n ≀ 10^5) β€” the number of pairs to check. Further input contains n descriptions of pairs. The first line of each description contains a single non-empty word s consisting of lowercase Latin letters. The second line of the description contains a single non-empty word t consisting of lowercase Latin letters. The lengths of both strings are not greater than 10^6. It is guaranteed that the total length of all words s in the input is not greater than 10^6. Also, it is guaranteed that the total length of all words t in the input is not greater than 10^6. Output Output n lines. In the i-th line for the i-th pair of words s and t print YES if the word t could be printed by typing the word s. Otherwise, print NO. Examples Input 4 hello hello hello helloo hello hlllloo hello helo Output YES YES NO NO Input 5 aa bb codeforces codeforce polycarp poolycarpp aaaa aaaab abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxyz Output NO NO YES NO NO
instruction
0
76,786
6
153,572
Tags: implementation, strings Correct Solution: ``` def initialChar(x): past = x[0] num = [] y = [] count = 0 for i in x: if i != past: y.append(past) num.append(count) count = 0 count += 1 past = i y.append(past) num.append(count) return num,y n = int(input()) for i in range(n): check = False s = [i for i in input()] t = [i for i in input()] a,b = initialChar(s) p,q = initialChar(t) # print(a,p) # print(b,q) if(b != q): print("NO") continue if(a != p): for i,j in zip(a,p): if j < i: print("NO") check = True break if check: continue print("YES") continue ```
output
1
76,786
6
153,573
Provide tags and a correct Python 3 solution for this coding contest problem. Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol). For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo". Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result. For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him. You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard. Input The first line of the input contains one integer n (1 ≀ n ≀ 10^5) β€” the number of pairs to check. Further input contains n descriptions of pairs. The first line of each description contains a single non-empty word s consisting of lowercase Latin letters. The second line of the description contains a single non-empty word t consisting of lowercase Latin letters. The lengths of both strings are not greater than 10^6. It is guaranteed that the total length of all words s in the input is not greater than 10^6. Also, it is guaranteed that the total length of all words t in the input is not greater than 10^6. Output Output n lines. In the i-th line for the i-th pair of words s and t print YES if the word t could be printed by typing the word s. Otherwise, print NO. Examples Input 4 hello hello hello helloo hello hlllloo hello helo Output YES YES NO NO Input 5 aa bb codeforces codeforce polycarp poolycarpp aaaa aaaab abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxyz Output NO NO YES NO NO
instruction
0
76,787
6
153,574
Tags: implementation, strings Correct Solution: ``` n=int(input()) for _ in range(n): scorrect=input() sreal=input() if len(scorrect)>len(sreal): print('NO') continue ic=0 ir=0 f=1 while ic<len(scorrect) and ir<len(sreal): current=scorrect[ic] if sreal[ir]!=current: if ir>0 and sreal[ir]==sreal[ir-1]: while ir<len(sreal) and sreal[ir]==sreal[ir-1]: ir+=1 else: f=0 break else: ir+=1 ic+=1 if ic<len(scorrect) and ir==len(sreal): print('NO') continue last=scorrect[-1] while ir<len(sreal): if sreal[ir]!=last: f=0 break ir+=1 if f==1: print('YES') else: print('NO') ```
output
1
76,787
6
153,575
Provide tags and a correct Python 3 solution for this coding contest problem. Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol). For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo". Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result. For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him. You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard. Input The first line of the input contains one integer n (1 ≀ n ≀ 10^5) β€” the number of pairs to check. Further input contains n descriptions of pairs. The first line of each description contains a single non-empty word s consisting of lowercase Latin letters. The second line of the description contains a single non-empty word t consisting of lowercase Latin letters. The lengths of both strings are not greater than 10^6. It is guaranteed that the total length of all words s in the input is not greater than 10^6. Also, it is guaranteed that the total length of all words t in the input is not greater than 10^6. Output Output n lines. In the i-th line for the i-th pair of words s and t print YES if the word t could be printed by typing the word s. Otherwise, print NO. Examples Input 4 hello hello hello helloo hello hlllloo hello helo Output YES YES NO NO Input 5 aa bb codeforces codeforce polycarp poolycarpp aaaa aaaab abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxyz Output NO NO YES NO NO
instruction
0
76,788
6
153,576
Tags: implementation, strings Correct Solution: ``` import sys n=int(input()) for _ in range(n): s=sys.stdin.readline().split("\n")[0] t=sys.stdin.readline().split("\n")[0] ss='$' c=1 if s[0]!=t[0] or len(s)>len(t): print("NO") else: ss=s[0] tt=t[0] i=1 j=1 while i<=len(s) and j<len(t): if i==len(s) or s[i]!=t[j]: if t[j]==ss[-1]: tt+=t[j] j+=1 else: c=0 break else: ss+=s[i] tt+=t[j] i+=1 j+=1 # print(i,j) if j!=len(t) or i!=len(s): c=0 # print(ss,tt) if c: print("YES") else: print("NO") ```
output
1
76,788
6
153,577
Provide tags and a correct Python 3 solution for this coding contest problem. Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol). For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo". Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result. For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him. You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard. Input The first line of the input contains one integer n (1 ≀ n ≀ 10^5) β€” the number of pairs to check. Further input contains n descriptions of pairs. The first line of each description contains a single non-empty word s consisting of lowercase Latin letters. The second line of the description contains a single non-empty word t consisting of lowercase Latin letters. The lengths of both strings are not greater than 10^6. It is guaranteed that the total length of all words s in the input is not greater than 10^6. Also, it is guaranteed that the total length of all words t in the input is not greater than 10^6. Output Output n lines. In the i-th line for the i-th pair of words s and t print YES if the word t could be printed by typing the word s. Otherwise, print NO. Examples Input 4 hello hello hello helloo hello hlllloo hello helo Output YES YES NO NO Input 5 aa bb codeforces codeforce polycarp poolycarpp aaaa aaaab abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxyz Output NO NO YES NO NO
instruction
0
76,789
6
153,578
Tags: implementation, strings Correct Solution: ``` n=int(input()) for _ in range(n): s=input()+"@" l=len(s) s1=input()+"$" l1=len(s1) ans="YES" i=0 j=0 while(ans=="YES"): if(s1[j]=="$"): if(s[i]=="@"):break ans="NO" break if s[i] == s1[j]: i+=1 j+=1 elif s[i] != s1[j] and s1[j] == s[i-1]: j+=1 else: ans = "NO" break print(ans) ```
output
1
76,789
6
153,579
Provide tags and a correct Python 3 solution for this coding contest problem. Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol). For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo". Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result. For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him. You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard. Input The first line of the input contains one integer n (1 ≀ n ≀ 10^5) β€” the number of pairs to check. Further input contains n descriptions of pairs. The first line of each description contains a single non-empty word s consisting of lowercase Latin letters. The second line of the description contains a single non-empty word t consisting of lowercase Latin letters. The lengths of both strings are not greater than 10^6. It is guaranteed that the total length of all words s in the input is not greater than 10^6. Also, it is guaranteed that the total length of all words t in the input is not greater than 10^6. Output Output n lines. In the i-th line for the i-th pair of words s and t print YES if the word t could be printed by typing the word s. Otherwise, print NO. Examples Input 4 hello hello hello helloo hello hlllloo hello helo Output YES YES NO NO Input 5 aa bb codeforces codeforce polycarp poolycarpp aaaa aaaab abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxyz Output NO NO YES NO NO
instruction
0
76,790
6
153,580
Tags: implementation, strings Correct Solution: ``` # def gns(): # return list(map(int,input().split())) # a,b,c,d=gns() # abc=[a,b,c] # abc.sort() # d1=abc[1]-abc[0] # d2=abc[2]-abc[1] # d1=max(d-d1,0) # d2=max(d-d2,0) # print(d1+d2) t=int(input()) for ti in range(t): a=input() b=input() def g(s): ans1=[] ans2=[] last=None for i in range(len(s)): c=s[i] if c!=last: ans1.append(c) ans2.append(1) else: ans2[-1]+=1 last=c return ans1,ans2 a1,a2=g(a) b1,b2=g(b) y='YES' n='NO' ans=True if len(a1)!=len(b1): print(n) continue l=len(a1) for i in range(l): if a1[i]!=b1[i] or a2[i]>b2[i]: ans=False break if ans: print(y) else: print(n) ```
output
1
76,790
6
153,581
Provide tags and a correct Python 3 solution for this coding contest problem. Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol). For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo". Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result. For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him. You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard. Input The first line of the input contains one integer n (1 ≀ n ≀ 10^5) β€” the number of pairs to check. Further input contains n descriptions of pairs. The first line of each description contains a single non-empty word s consisting of lowercase Latin letters. The second line of the description contains a single non-empty word t consisting of lowercase Latin letters. The lengths of both strings are not greater than 10^6. It is guaranteed that the total length of all words s in the input is not greater than 10^6. Also, it is guaranteed that the total length of all words t in the input is not greater than 10^6. Output Output n lines. In the i-th line for the i-th pair of words s and t print YES if the word t could be printed by typing the word s. Otherwise, print NO. Examples Input 4 hello hello hello helloo hello hlllloo hello helo Output YES YES NO NO Input 5 aa bb codeforces codeforce polycarp poolycarpp aaaa aaaab abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxyz Output NO NO YES NO NO
instruction
0
76,791
6
153,582
Tags: implementation, strings Correct Solution: ``` def solve(src, tgt): si = 0 ti = 0 ans = "YES" while si < len(src) and ti < len(tgt): if src[si] == tgt[ti]: si += 1 ti += 1 else: if ti >= 1: if tgt[ti] == tgt[ti-1]: ti += 1 continue else: ans = "NO" break ans = "NO" break #print(si, ti) if si < len(src): ans = "NO" else: if ti < len(tgt): while ti < len(tgt): if tgt[ti] == tgt[ti - 1]: ti +=1 else: ans = "NO" break if ti < len(tgt):ans = "NO" return ans nb_Test = int(input()) for _ in range(nb_Test): src = input() tgt = input() print(solve(src, tgt)) ```
output
1
76,791
6
153,583
Provide tags and a correct Python 3 solution for this coding contest problem. Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner. Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t. On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that. The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct: * n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"), * p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≀ k ≀ min(n, m)), here characters in strings are numbered starting from 1. Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum. Input The first line contains a non-empty string s (1 ≀ |s| ≀ 5000), where |s| is its length. The second line contains a non-empty string t (1 ≀ |t| ≀ 5000), where |t| is its length. Both strings consist of lowercase Latin letters. Output Print the sought name or -1 if it doesn't exist. Examples Input aad aac Output aad Input abad bob Output daab Input abc defg Output -1 Input czaaab abcdef Output abczaa Note In the first sample the given string s is the sought one, consequently, we do not need to change the letter order there.
instruction
0
77,762
6
155,524
Tags: greedy, strings Correct Solution: ``` from sys import stdin, stdout words = ['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'] s = stdin.readline().strip() f = stdin.readline().strip() ans = -1 d = {} for v in s: if v in d: d[v] += 1 else: d[v] = 1 for i in range(min(len(s), len(f))): if f[i] in d and d[f[i]]: d[f[i]] -= 1 else: break for v in words: if v in d and d[v] and (i == len(f) - 1 or v > f[i + 1]): ans = i break if ans == -1 and max(list(s)) > f[0]: s = sorted(list(s)) first = '' for i in range(len(s)): if s[i] > f[0]: first += s[i] s[i] = '_' break first += ''.join(sorted(list(s))[1:]) elif ans == -1: first = '-1' else: s = sorted(list(s)) d = {} first = '' for i in range(ans + 1): first += f[i] if f[i] in d: d[f[i]] += 1 else: d[f[i]] = 1 for i in range(len(s)): if s[i] in d and d[s[i]]: d[s[i]] -= 1 s[i] = '_' for i in range(len(s)): if s[i] != '_' and (ans + 1 == len(f) or s[i] > f[ans + 1]): first += s[i] s[i] = '_' break for i in range(len(s)): if s[i] != '_': first += s[i] stdout.write(first) ```
output
1
77,762
6
155,525
Provide tags and a correct Python 3 solution for this coding contest problem. Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner. Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t. On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that. The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct: * n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"), * p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≀ k ≀ min(n, m)), here characters in strings are numbered starting from 1. Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum. Input The first line contains a non-empty string s (1 ≀ |s| ≀ 5000), where |s| is its length. The second line contains a non-empty string t (1 ≀ |t| ≀ 5000), where |t| is its length. Both strings consist of lowercase Latin letters. Output Print the sought name or -1 if it doesn't exist. Examples Input aad aac Output aad Input abad bob Output daab Input abc defg Output -1 Input czaaab abcdef Output abczaa Note In the first sample the given string s is the sought one, consequently, we do not need to change the letter order there.
instruction
0
77,763
6
155,526
Tags: greedy, strings Correct Solution: ``` def findmin(lcopy, toexceed): toex = ord(toexceed) - 97 for each in lcopy[(toex+1):]: if each > 0: return True return False def arrange(lcopy, toexceed = None): if toexceed is None: ans = "" for i in range(26): ans += chr(i+97)*lcopy[i] return ans ans = "" for i in range(ord(toexceed)-97+1, 26): if lcopy[i] > 0: ans += chr(i+97) lcopy[i] -= 1 break return ans + arrange(lcopy) def operation(s1, s2): first_count = [0]*26 for letter in s1: first_count[ord(letter)-97] += 1 common = 0 lcopy = list(first_count) for i in range(len(s2)): letter = s2[i] num = ord(letter) - 97 if lcopy[num] > 0: lcopy[num] -= 1 common += 1 else: break found = False ans = "" #print(common) for cval in range(common, -1, -1): #print(cval) if cval >= len(s1): lcopy[ord(s2[cval-1])-97] += 1 continue else: if cval == len(s2): found = True ans = s2[:cval] + arrange(lcopy) break else: #print("yo", s2[cval]) if findmin(lcopy, s2[cval]): found = True ans = s2[:cval] + arrange(lcopy, s2[cval]) break else: lcopy[ord(s2[cval-1])-97] += 1 if not found: return -1 else: return ans s1 = input() s2 = input() print(operation(s1, s2)) ```
output
1
77,763
6
155,527
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner. Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t. On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that. The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct: * n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"), * p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≀ k ≀ min(n, m)), here characters in strings are numbered starting from 1. Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum. Input The first line contains a non-empty string s (1 ≀ |s| ≀ 5000), where |s| is its length. The second line contains a non-empty string t (1 ≀ |t| ≀ 5000), where |t| is its length. Both strings consist of lowercase Latin letters. Output Print the sought name or -1 if it doesn't exist. Examples Input aad aac Output aad Input abad bob Output daab Input abc defg Output -1 Input czaaab abcdef Output abczaa Note In the first sample the given string s is the sought one, consequently, we do not need to change the letter order there. Submitted Solution: ``` def findmin(lcopy, toexceed): toex = ord(toexceed) - 97 for each in lcopy[(toex+1):]: if each > 0: return True return False def arrange(lcopy, toexceed = None): if toexceed is None: ans = "" for i in range(26): ans += chr(i+97)*lcopy[i] return ans ans = "" for i in range(ord(toexceed)-97+1, 26): if lcopy[i] > 0: ans += chr(i+97) lcopy[i] -= 1 return ans + arrange(lcopy) def operation(s1, s2): first_count = [0]*26 for letter in s1: first_count[ord(letter)-97] += 1 common = 0 lcopy = list(first_count) for i in range(len(s2)): letter = s2[i] num = ord(letter) - 97 if lcopy[num] > 0: lcopy[num] -= 1 common += 1 else: break found = False ans = "" #print(common) for cval in range(common, -1, -1): #print(cval) if cval >= len(s1): lcopy[ord(s2[cval-1])-97] += 1 continue else: if cval == len(s2): found = True ans = s2[:cval] + arrange(lcopy) break else: if findmin(lcopy, s2[cval]): found = True ans = s2[:cval] + arrange(lcopy, s2[cval]) break else: lcopy[ord(s2[cval-1])-97] += 1 if not found: return -1 else: return ans s1 = input() s2 = input() print(operation(s1, s2)) ```
instruction
0
77,764
6
155,528
No
output
1
77,764
6
155,529
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
77,856
6
155,712
Tags: divide and conquer, hashing, sortings, strings Correct Solution: ``` A, B = '', '' def process(string): if len(string) % 2 != 1: m = int(len(string)/2) l = process(string[:m]) r = process(string[m:]) if l < r: return l + r return r + l return string def entrypoint(): global A, B A = input() B = input() def main(): entrypoint() retA = process(A) retB = process(B) if retA == retB: print('YES') else: print('NO') if __name__ == '__main__': main() ```
output
1
77,856
6
155,713
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
77,857
6
155,714
Tags: divide and conquer, hashing, sortings, strings Correct Solution: ``` def divide_letras(palavra): tamanho = len(palavra) if (tamanho % 2 == 1): return palavra tamanho = tamanho // 2 esquerda = divide_letras(palavra[:tamanho]) direita = divide_letras(palavra[tamanho:]) if (esquerda < direita): return (esquerda + direita) else: return (direita + esquerda) a = input() b = input() if(divide_letras(a) == divide_letras(b)): print('YES ') else: print('NO') ```
output
1
77,857
6
155,715
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
77,858
6
155,716
Tags: divide and conquer, hashing, sortings, strings Correct Solution: ``` def sim(x): if len(x) % 2: return x x1 = sim(x[:len(x)//2]) x2 = sim(x[len(x)//2:]) return x1 + x2 if x1 < x2 else x2 + x1 print("YES" if sim(input()) == sim(input()) else "NO") ```
output
1
77,858
6
155,717
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
77,859
6
155,718
Tags: divide and conquer, hashing, sortings, strings Correct Solution: ``` def equivalentStrings(string): if len(string) & 1: return string a = equivalentStrings(string[ : len(string) >> 1]) b = equivalentStrings(string[len(string) >> 1 : ]) return a + b if a < b else b + a print('YES' if equivalentStrings(input()) == equivalentStrings(input()) else 'NO') ```
output
1
77,859
6
155,719
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
77,862
6
155,724
Tags: divide and conquer, hashing, sortings, strings Correct Solution: ``` def main(): def f(lo, hi): if not ((hi - lo) & 1): mi = (hi + lo) // 2 f(lo, mi) f(mi, hi) if a[mi:hi] < a[lo:mi]: a[lo:mi], a[mi:hi] = a[mi:hi], a[lo:mi] if b[mi:hi] < b[lo:mi]: b[lo:mi], b[mi:hi] = b[mi:hi], b[lo:mi] a, b = list(input()), list(input()) f(0, len(a)) print(("NO", "YES")[a == b]) if __name__ == '__main__': main() ```
output
1
77,862
6
155,725
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
77,863
6
155,726
Tags: divide and conquer, hashing, sortings, strings Correct Solution: ``` def solve(s): sz = len(s) if(sz % 2 == 1): return s a = solve(s[:int(sz / 2)]) b = solve(s[int(sz / 2):]) if a < b: return a + b else: return b + a def main(): a = input() b = input() resa = solve(a) resb = solve(b) if resa == resb: print("YES") else: print("NO") main() ```
output
1
77,863
6
155,727
Provide a correct Python 3 solution for this coding contest problem. Problem Statement We found a dictionary of the Ancient Civilization Mayo (ACM) during excavation of the ruins. After analysis of the dictionary, we revealed they used a language that had not more than 26 letters. So one of us mapped each letter to a different English alphabet and typed all the words in the dictionary into a computer. How the words are ordered in the dictionary, especially whether they are ordered lexicographically, is an interesting topic to many people. As a good programmer, you are requested to write a program to judge whether we can consider the words to be sorted in a lexicographical order. Note: In a lexicographical order, a word always precedes other words it is a prefix of. For example, `ab` precedes `abc`, `abde`, and so on. Input The input consists of multiple datasets. Each dataset is formatted as follows: n string_1 ... string_n Each dataset consists of n+1 lines. The first line of each dataset contains an integer that indicates n (1 \leq n \leq 500). The i-th line of the following n lines contains string_i, which consists of up to 10 English lowercase letters. The end of the input is `0`, and this should not be processed. Output Print either `yes` or `no` in a line for each dataset, in the order of the input. If all words in the dataset can be considered to be ordered lexicographically, print `yes`. Otherwise, print `no`. Example Input 4 cba cab b a 3 bca ab a 5 abc acb b c c 5 abc acb c b b 0 Output yes no yes no
instruction
0
78,245
6
156,490
"Correct Solution: ``` def add_edge(node, adj_lst, s1, s2): ind = 0 max_len = min(len(s1), len(s2)) while ind < max_len and s1[ind] == s2[ind]: ind += 1 if ind == max_len: return max_len < len(s1) c1 = ord(s1[ind]) - ord("a") c2 = ord(s2[ind]) - ord("a") adj_lst[c1].add(c2) node.add(c1) node.add(c2) return False def visit(n, visited, adj_lst): ret = False if visited[n] == 2: return True elif visited[n] == 0: visited[n] = 2 for to in adj_lst[n]: ret = ret or visit(to, visited, adj_lst) visited[n] = 1 return ret def main(): while True: n = int(input()) if n == 0: break lst = [input() for _ in range(n)] node = set() adj_lst = [set() for _ in range(26)] blank_flag = False for i in range(n): for j in range(i + 1, n): blank_flag = blank_flag or add_edge(node, adj_lst, lst[i], lst[j]) if blank_flag: print("no") continue visited = [0] * 26 cycle_flag = False for n in node: cycle_flag = cycle_flag or visit(n, visited, adj_lst) if cycle_flag: print("no") else: print("yes") main() ```
output
1
78,245
6
156,491
Provide a correct Python 3 solution for this coding contest problem. Problem Statement We found a dictionary of the Ancient Civilization Mayo (ACM) during excavation of the ruins. After analysis of the dictionary, we revealed they used a language that had not more than 26 letters. So one of us mapped each letter to a different English alphabet and typed all the words in the dictionary into a computer. How the words are ordered in the dictionary, especially whether they are ordered lexicographically, is an interesting topic to many people. As a good programmer, you are requested to write a program to judge whether we can consider the words to be sorted in a lexicographical order. Note: In a lexicographical order, a word always precedes other words it is a prefix of. For example, `ab` precedes `abc`, `abde`, and so on. Input The input consists of multiple datasets. Each dataset is formatted as follows: n string_1 ... string_n Each dataset consists of n+1 lines. The first line of each dataset contains an integer that indicates n (1 \leq n \leq 500). The i-th line of the following n lines contains string_i, which consists of up to 10 English lowercase letters. The end of the input is `0`, and this should not be processed. Output Print either `yes` or `no` in a line for each dataset, in the order of the input. If all words in the dataset can be considered to be ordered lexicographically, print `yes`. Otherwise, print `no`. Example Input 4 cba cab b a 3 bca ab a 5 abc acb b c c 5 abc acb c b b 0 Output yes no yes no
instruction
0
78,246
6
156,492
"Correct Solution: ``` def add_edge(node, adj_lst, adj_rev, s1, s2): ind = 0 max_len = min(len(s1), len(s2)) while ind < max_len and s1[ind] == s2[ind]: ind += 1 if ind == max_len: if max_len < len(s1): return True return False c1 = ord(s1[ind]) - ord("a") c2 = ord(s2[ind]) - ord("a") adj_lst[c1].add(c2) adj_rev[c2].add(c1) node.add(c1) node.add(c2) return False """ def dfs(x, visited, adj_lst, order): visited[x] = True for to in adj_lst[x]: if not visited[to]: dfs(to, visited, adj_lst, order) order.append(x) def dfs_rev(x, used, adj_rev): used.append(x) for to in adj_rev[x]: if not to in used: dfs_rev(x, used, adj_rev) """ while True: n = int(input()) if n == 0: break lst = [input() for _ in range(n)] node = set() adj_lst = [set() for _ in range(26)] adj_rev = [set() for _ in range(26)] brunk_flag = False for i in range(n): for j in range(i + 1, n): brunk_flag = brunk_flag or add_edge(node, adj_lst, adj_rev, lst[i], lst[j]) L = [] visited = [False] * 26 cycle_flag = False def visit(n): global cycle_flag if cycle_flag: return if visited[n] == 2: cycle_flag = True elif visited[n] == 0: visited[n] = 2 for to in adj_lst[n]: visit(to) visited[n] = 1 L.append(n) L = [] for n in node: visit(n) if cycle_flag or brunk_flag: print("no") else: print("yes") ```
output
1
78,246
6
156,493
Provide a correct Python 3 solution for this coding contest problem. Problem Statement We found a dictionary of the Ancient Civilization Mayo (ACM) during excavation of the ruins. After analysis of the dictionary, we revealed they used a language that had not more than 26 letters. So one of us mapped each letter to a different English alphabet and typed all the words in the dictionary into a computer. How the words are ordered in the dictionary, especially whether they are ordered lexicographically, is an interesting topic to many people. As a good programmer, you are requested to write a program to judge whether we can consider the words to be sorted in a lexicographical order. Note: In a lexicographical order, a word always precedes other words it is a prefix of. For example, `ab` precedes `abc`, `abde`, and so on. Input The input consists of multiple datasets. Each dataset is formatted as follows: n string_1 ... string_n Each dataset consists of n+1 lines. The first line of each dataset contains an integer that indicates n (1 \leq n \leq 500). The i-th line of the following n lines contains string_i, which consists of up to 10 English lowercase letters. The end of the input is `0`, and this should not be processed. Output Print either `yes` or `no` in a line for each dataset, in the order of the input. If all words in the dataset can be considered to be ordered lexicographically, print `yes`. Otherwise, print `no`. Example Input 4 cba cab b a 3 bca ab a 5 abc acb b c c 5 abc acb c b b 0 Output yes no yes no
instruction
0
78,247
6
156,494
"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**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] 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(): rr = [] while True: n = I() if n == 0: break a = [S() for _ in range(n)] e = collections.defaultdict(set) for c in string.ascii_lowercase: e[''].add(c) f = True for i in range(n): ai = a[i] for j in range(i+1,n): aj = a[j] for k in range(len(ai)): if len(aj) <= k: f = False break if ai[k] == aj[k]: continue e[ai[k]].add(aj[k]) break if not f: rr.append('no') continue v = collections.defaultdict(bool) v[''] = True def g(c): if v[c] == 2: return True if v[c] == 1: return False v[c] = 1 for nc in e[c]: if not g(nc): return False v[c] = 2 return True for c in list(e.keys()): if v[c]: continue if not g(c): f = False break if f: rr.append('yes') else: rr.append('no') return '\n'.join(map(str,rr)) print(main()) ```
output
1
78,247
6
156,495
Provide a correct Python 3 solution for this coding contest problem. Problem Statement We found a dictionary of the Ancient Civilization Mayo (ACM) during excavation of the ruins. After analysis of the dictionary, we revealed they used a language that had not more than 26 letters. So one of us mapped each letter to a different English alphabet and typed all the words in the dictionary into a computer. How the words are ordered in the dictionary, especially whether they are ordered lexicographically, is an interesting topic to many people. As a good programmer, you are requested to write a program to judge whether we can consider the words to be sorted in a lexicographical order. Note: In a lexicographical order, a word always precedes other words it is a prefix of. For example, `ab` precedes `abc`, `abde`, and so on. Input The input consists of multiple datasets. Each dataset is formatted as follows: n string_1 ... string_n Each dataset consists of n+1 lines. The first line of each dataset contains an integer that indicates n (1 \leq n \leq 500). The i-th line of the following n lines contains string_i, which consists of up to 10 English lowercase letters. The end of the input is `0`, and this should not be processed. Output Print either `yes` or `no` in a line for each dataset, in the order of the input. If all words in the dataset can be considered to be ordered lexicographically, print `yes`. Otherwise, print `no`. Example Input 4 cba cab b a 3 bca ab a 5 abc acb b c c 5 abc acb c b b 0 Output yes no yes no
instruction
0
78,248
6
156,496
"Correct Solution: ``` def add_edge(node, adj_lst, adj_rev, s1, s2): ind = 0 max_len = min(len(s1), len(s2)) while ind < max_len and s1[ind] == s2[ind]: ind += 1 if ind == max_len: if max_len < len(s1): return True return False c1 = ord(s1[ind]) - ord("a") c2 = ord(s2[ind]) - ord("a") adj_lst[c1].add(c2) adj_rev[c2].add(c1) node.add(c1) node.add(c2) return False def main(): while True: n = int(input()) if n == 0: break lst = [input() for _ in range(n)] node = set() adj_lst = [set() for _ in range(26)] adj_rev = [set() for _ in range(26)] blank_flag = False for i in range(n): for j in range(i + 1, n): blank_flag = blank_flag or add_edge(node, adj_lst, adj_rev, lst[i], lst[j]) visited = [False] * 26 cycle_flag = False def visit(n): ret = False if visited[n] == 2: return True elif visited[n] == 0: visited[n] = 2 for to in adj_lst[n]: ret = ret or visit(to) visited[n] = 1 return ret for n in node: cycle_flag = cycle_flag or visit(n) if cycle_flag or blank_flag: print("no") else: print("yes") main() ```
output
1
78,248
6
156,497
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Problem Statement We found a dictionary of the Ancient Civilization Mayo (ACM) during excavation of the ruins. After analysis of the dictionary, we revealed they used a language that had not more than 26 letters. So one of us mapped each letter to a different English alphabet and typed all the words in the dictionary into a computer. How the words are ordered in the dictionary, especially whether they are ordered lexicographically, is an interesting topic to many people. As a good programmer, you are requested to write a program to judge whether we can consider the words to be sorted in a lexicographical order. Note: In a lexicographical order, a word always precedes other words it is a prefix of. For example, `ab` precedes `abc`, `abde`, and so on. Input The input consists of multiple datasets. Each dataset is formatted as follows: n string_1 ... string_n Each dataset consists of n+1 lines. The first line of each dataset contains an integer that indicates n (1 \leq n \leq 500). The i-th line of the following n lines contains string_i, which consists of up to 10 English lowercase letters. The end of the input is `0`, and this should not be processed. Output Print either `yes` or `no` in a line for each dataset, in the order of the input. If all words in the dataset can be considered to be ordered lexicographically, print `yes`. Otherwise, print `no`. Example Input 4 cba cab b a 3 bca ab a 5 abc acb b c c 5 abc acb c b b 0 Output yes no yes no Submitted Solution: ``` def add_edge(node, adj_lst, adj_rev, s1, s2): ind = 0 max_len = min(len(s1), len(s2)) while ind < max_len and s1[ind] == s2[ind]: ind += 1 if ind == max_len: if max_len < len(s1): return True return False c1 = ord(s1[ind]) - ord("a") c2 = ord(s2[ind]) - ord("a") adj_lst[c1].add(c2) adj_rev[c2].add(c1) node.add(c1) node.add(c2) return False def main(): while True: n = int(input()) if n == 0: break lst = [input() for _ in range(n)] node = set() adj_lst = [set() for _ in range(26)] adj_rev = [set() for _ in range(26)] blank_flag = False for i in range(n): for j in range(i + 1, n): blank_flag = blank_flag or add_edge(node, adj_lst, adj_rev, lst[i], lst[j]) L = [] visited = [False] * 26 cycle_flag = False def visit(n): global cycle_flag if cycle_flag: return if visited[n] == 2: cycle_flag = True elif visited[n] == 0: visited[n] = 2 for to in adj_lst[n]: visit(to) visited[n] = 1 L.append(n) L = [] for n in node: visit(n) if cycle_flag or blank_flag: print("no") else: print("yes") main() ```
instruction
0
78,249
6
156,498
No
output
1
78,249
6
156,499
Provide tags and a correct Python 3 solution for this coding contest problem. There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot. A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color. For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z'). Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible. Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair. Input The first line contains n (1 ≀ n ≀ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot. The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot. Output Print k β€” the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following k lines should contain pairs a_j, b_j (1 ≀ a_j, b_j ≀ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique). If there are many optimal answers, print any of them. Examples Input 10 codeforces dodivthree Output 5 7 8 4 9 2 2 9 10 3 1 Input 7 abaca?b zabbbcc Output 5 6 5 2 3 4 6 7 4 1 2 Input 9 bambarbia hellocode Output 0 Input 10 code?????? ??????test Output 10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
instruction
0
78,339
6
156,678
Tags: greedy, implementation Correct Solution: ``` import sys sys.setrecursionlimit(20000000) input = sys.stdin.readline n = int(input()) a = input() b = input() al = [[] for i in range(27)] bl = [[] for i in range(27)] for i in range(n): if a[i] == "?": al[26].append(i+1) else: al[ord(a[i])-ord("a")].append(i+1) if b[i] == "?": bl[26].append(i+1) else: bl[ord(b[i])-ord("a")].append(i+1) ans = [] for i in range(26): while al[i] and bl[i]: ans.append([al[i].pop(),bl[i].pop()]) alz = [] blz = [] for i in range(26): while al[i]: alz.append(al[i].pop()) while bl[i]: blz.append(bl[i].pop()) while al[26] and blz: ans.append([al[26].pop(),blz.pop()]) while bl[26] and alz: ans.append([alz.pop(),bl[26].pop()]) while al[26] and bl[26]: ans.append([al[26].pop(),bl[26].pop()]) print(len(ans)) for i in range(len(ans)): print(ans[i][0],ans[i][1]) ```
output
1
78,339
6
156,679
Provide tags and a correct Python 3 solution for this coding contest problem. There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot. A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color. For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z'). Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible. Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair. Input The first line contains n (1 ≀ n ≀ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot. The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot. Output Print k β€” the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following k lines should contain pairs a_j, b_j (1 ≀ a_j, b_j ≀ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique). If there are many optimal answers, print any of them. Examples Input 10 codeforces dodivthree Output 5 7 8 4 9 2 2 9 10 3 1 Input 7 abaca?b zabbbcc Output 5 6 5 2 3 4 6 7 4 1 2 Input 9 bambarbia hellocode Output 0 Input 10 code?????? ??????test Output 10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
instruction
0
78,340
6
156,680
Tags: greedy, implementation Correct Solution: ``` n = int(input()) l = input() r = input() rr = {'?':[]} for i in range(n): if r[i] in rr: rr[r[i]].append(i) else: rr[r[i]] = [i] ll = [] for i in range(n): if l[i] == '?': ll.append(i) q = [] res = [] for i in range(n): c = l[i] if c != '?': if c in rr and len(rr[c]): res.append([i, rr[c].pop()]) else: if len(rr['?']): res.append([i, rr['?'].pop()]) for i in rr: for j in rr[i]: if len(ll): res.append([ll.pop(), j]) print(len(res)) for i in res: a, b = i print(a + 1, b + 1) ```
output
1
78,340
6
156,681
Provide tags and a correct Python 3 solution for this coding contest problem. There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot. A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color. For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z'). Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible. Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair. Input The first line contains n (1 ≀ n ≀ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot. The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot. Output Print k β€” the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following k lines should contain pairs a_j, b_j (1 ≀ a_j, b_j ≀ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique). If there are many optimal answers, print any of them. Examples Input 10 codeforces dodivthree Output 5 7 8 4 9 2 2 9 10 3 1 Input 7 abaca?b zabbbcc Output 5 6 5 2 3 4 6 7 4 1 2 Input 9 bambarbia hellocode Output 0 Input 10 code?????? ??????test Output 10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
instruction
0
78,341
6
156,682
Tags: greedy, implementation Correct Solution: ``` from collections import defaultdict n = int(input()) l = input() r = input() dl = defaultdict(list) dr = defaultdict(list) for i in range(n): dl[l[i]].append(1+i) for i in range(n): dr[r[i]].append(1+i) ans = [] s='abcdefghijklmnopqrstuvwxyz' for i in s: while dl[i] and dr[i]: ans.append((dl[i].pop(), dr[i].pop())) for i in s: while dl['?'] and dr[i]: ans.append((dl['?'].pop(), dr[i].pop())) for i in s: while dr['?'] and dl[i]: ans.append((dl[i].pop() , dr['?'].pop())) while dr['?'] and dl['?']: ans.append((dl['?'].pop(), dr['?'].pop())) print(len(ans)) for i in ans: print(*i) ```
output
1
78,341
6
156,683
Provide tags and a correct Python 3 solution for this coding contest problem. There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot. A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color. For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z'). Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible. Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair. Input The first line contains n (1 ≀ n ≀ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot. The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot. Output Print k β€” the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following k lines should contain pairs a_j, b_j (1 ≀ a_j, b_j ≀ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique). If there are many optimal answers, print any of them. Examples Input 10 codeforces dodivthree Output 5 7 8 4 9 2 2 9 10 3 1 Input 7 abaca?b zabbbcc Output 5 6 5 2 3 4 6 7 4 1 2 Input 9 bambarbia hellocode Output 0 Input 10 code?????? ??????test Output 10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
instruction
0
78,342
6
156,684
Tags: greedy, implementation Correct Solution: ``` n = int(input()) la, ra = {}, {} lq, rq = [], [] s = input() for i in range(len(s)): if s[i] != "?": if s[i] not in la: la[s[i]] = [] la[s[i]].append(i) else: lq.append(i) s = input() for i in range(len(s)): if s[i] != "?": if s[i] not in ra: ra[s[i]] = [] ra[s[i]].append(i) else: rq.append(i) ansa = [] for i in la: if i in ra: while len(la[i]) and len(ra[i]): ansa.append((la[i].pop(), ra[i].pop())) lr = [] for i in la: lr.extend(la[i]) rr = [] for i in ra: rr.extend(ra[i]) while len(lq) and len(rr): ansa.append((lq.pop(), rr.pop())) while len(lr) and len(rq): ansa.append((lr.pop(), rq.pop())) while len(lq) and len(rq): ansa.append((lq.pop(), rq.pop())) print(len(ansa)) for i, j in ansa: print(i + 1, j + 1) ```
output
1
78,342
6
156,685
Provide tags and a correct Python 3 solution for this coding contest problem. There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot. A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color. For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z'). Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible. Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair. Input The first line contains n (1 ≀ n ≀ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot. The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot. Output Print k β€” the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following k lines should contain pairs a_j, b_j (1 ≀ a_j, b_j ≀ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique). If there are many optimal answers, print any of them. Examples Input 10 codeforces dodivthree Output 5 7 8 4 9 2 2 9 10 3 1 Input 7 abaca?b zabbbcc Output 5 6 5 2 3 4 6 7 4 1 2 Input 9 bambarbia hellocode Output 0 Input 10 code?????? ??????test Output 10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
instruction
0
78,343
6
156,686
Tags: greedy, implementation Correct Solution: ``` n = int(input()) s1 = input() s2 = input() a1 = [] a2 = [] mas = [] ch = 0 q1 = 0 q2 = 0 for i in range(n): a1.append([s1[i], i + 1]) a2.append([s2[i], i + 1]) if s1[i] == '?': q1 += 1 if s2[i] == '?': q2 += 1 a1.sort() a2.sort() i = n - 1 j = n - 1 arr1 = [] arr2 = [] while i >= 0 and j >= 0: if ord(a1[i][0]) > ord(a2[j][0]): arr1.append(a1[i][1]) i -= 1 if ord(a1[i][0]) < ord(a2[j][0]): arr2.append(a2[j][1]) j -= 1 if ord(a1[i][0]) == ord(a2[j][0]): if a1[i][0] != '?': mas.append([a1[i][1], a2[j][1]]) ch += 1 i -= 1 j -= 1 else: break f1 = 0 f2 = 0 for k in range(len(arr1)): if q2 != 0: ch += 1 mas.append([arr1[k], a2[k][1]]) q2 -= 1 f1 += 1 else: break for k in range(len(arr2)): if q1 != 0: ch += 1 mas.append([a1[k][1], arr2[k]]) q1 -= 1 f2 += 1 else: break g = min(q1, q2) for k in range(g): mas.append([a1[f1][1], a2[f2][1]]) ch += 1 f1 += 1 f2 += 1 print(ch) for i in range(len(mas)): print(mas[i][0], mas[i][1]) ```
output
1
78,343
6
156,687
Provide tags and a correct Python 3 solution for this coding contest problem. There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot. A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color. For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z'). Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible. Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair. Input The first line contains n (1 ≀ n ≀ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot. The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot. Output Print k β€” the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following k lines should contain pairs a_j, b_j (1 ≀ a_j, b_j ≀ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique). If there are many optimal answers, print any of them. Examples Input 10 codeforces dodivthree Output 5 7 8 4 9 2 2 9 10 3 1 Input 7 abaca?b zabbbcc Output 5 6 5 2 3 4 6 7 4 1 2 Input 9 bambarbia hellocode Output 0 Input 10 code?????? ??????test Output 10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
instruction
0
78,344
6
156,688
Tags: greedy, implementation Correct Solution: ``` from sys import stdin from collections import defaultdict input = stdin.readline n = int(input()) l = input().rstrip() r = input().rstrip() ll = defaultdict(list) rr = defaultdict(list) for i in range(n): ll[l[i]].append(i) rr[r[i]].append(i) ans = [] for k in ll: if k == "?": continue while len(ll[k]) > 0 and len(rr[k]) > 0: ans.append((ll[k].pop()+1, rr[k].pop()+1)) for k in ll: if len(rr["?"]) == 0: break if k == "?": continue while len(ll[k]) > 0 and len(rr["?"]) > 0: ans.append((ll[k].pop()+1, rr["?"].pop()+1)) for k in rr: if len(ll["?"]) == 0: break if k == "?": continue while len(rr[k]) > 0 and len(ll["?"]) > 0: ans.append((ll["?"].pop()+1, rr[k].pop()+1)) while len(rr["?"]) > 0 and len(ll["?"]) > 0: ans.append((ll["?"].pop()+1, rr["?"].pop()+1)) print(len(ans)) for i in ans: print(*i) ```
output
1
78,344
6
156,689
Provide tags and a correct Python 3 solution for this coding contest problem. There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot. A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color. For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z'). Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible. Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair. Input The first line contains n (1 ≀ n ≀ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot. The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot. Output Print k β€” the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following k lines should contain pairs a_j, b_j (1 ≀ a_j, b_j ≀ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique). If there are many optimal answers, print any of them. Examples Input 10 codeforces dodivthree Output 5 7 8 4 9 2 2 9 10 3 1 Input 7 abaca?b zabbbcc Output 5 6 5 2 3 4 6 7 4 1 2 Input 9 bambarbia hellocode Output 0 Input 10 code?????? ??????test Output 10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
instruction
0
78,345
6
156,690
Tags: greedy, implementation Correct Solution: ``` n, s1, s2 = int(input()), input(), input() dl, dr = {'?':0}, {'?':0} indl ,indr = {'?':[]}, {'?':[]} for i in range(n): if s1[i] not in dl: dl[s1[i]] = dr[s1[i]] = 0 indl[s1[i]], indr[s1[i]] = [], [] if s2[i] not in dl: dl[s2[i]] = dr[s2[i]] = 0 indl[s2[i]], indr[s2[i]] = [], [] dl[s1[i]] +=1 dr[s2[i]] +=1 indl[s1[i]].append(i+1) indr[s2[i]].append(i+1) pairs = 0 printv = [] for k in dl: if k == "?": continue new = min(dl[k], dr[k]) pairs+= new dl[k] -= new dr[k] -= new printv.extend([(k, k)]*new) v = dr["?"] # print(dr, dl) for k in dl: if k == "?": continue if v <= 0: break new = min(v, dl[k]) pairs += new v-= new dl[k] -= new printv.extend([(k, '?')]*new) dr['?'] =v # print(dr, dl) v = dl["?"] for k in dr: if k == "?": continue if v <= 0: break new = min(v, dr[k]) pairs += new v -= new dr[k] -= new printv.extend([('?', k)]*new) dl['?'] = v new = min(dr['?'], dl['?']) pairs+=new printv.extend([('?', '?')]*new) print(pairs) # print(printv) print("\n".join([str(indl[s[0]].pop())+" "+str(indr[s[1]].pop()) for s in printv])) ```
output
1
78,345
6
156,691
Provide tags and a correct Python 3 solution for this coding contest problem. There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot. A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color. For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z'). Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible. Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair. Input The first line contains n (1 ≀ n ≀ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot. The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot. Output Print k β€” the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following k lines should contain pairs a_j, b_j (1 ≀ a_j, b_j ≀ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique). If there are many optimal answers, print any of them. Examples Input 10 codeforces dodivthree Output 5 7 8 4 9 2 2 9 10 3 1 Input 7 abaca?b zabbbcc Output 5 6 5 2 3 4 6 7 4 1 2 Input 9 bambarbia hellocode Output 0 Input 10 code?????? ??????test Output 10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
instruction
0
78,346
6
156,692
Tags: greedy, implementation Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ####################################### from collections import * from operator import itemgetter , attrgetter from decimal import * import bisect import math import heapq as hq MOD=10**9 +7 def pow(a,b,m): ans=1 while b: if b&1: ans=(ans*a)%m b//=2 a=(a*a)%m return ans vis=[] graph=[] def dfs(v): if vis[v]: return 0 vis[v]=True temp=0 for vv in graph[v]: temp+=dfs(vv) return 1+temp def ispalindrome(s): if s[:]==s[::-1]: return 1 return 0 def f(n): if n<5: return max(1,n-1) if n%2 or n%4==0: return n-f(n-1) return n-f(n//2) n=int(input()) q1=0 q2=0 s1=input() s2=input() l1=[] l2=[] for i in range(n): if s1[i]=="?": q1+=1 l1.append(["zz",i+1]) else: l1.append([s1[i],i+1]) if s2[i]=="?": q2+=1 l2.append(["zz",i+1]) else: l2.append([s2[i],i+1]) i=0 j=0 count=0 ans=[] l1.sort() l2.sort() temp1=[i for i in range(n+1)] temp2=[i for i in range(n+1)] while i<n and j<n: #print(i,j,l1[i][0],l2[j][0]) if l1[i][0]=="zz" or l2[j][0]=="zz": break if l1[i][0]==l2[j][0]: count+=1 ans.append([l1[i][1],l2[j][1]]) temp1[l1[i][1]]=-1 temp2[l2[j][1]]=-1 i+=1 j+=1 elif l1[i][0]<l2[j][0]: i+=1 else: j+=1 i=0 t=min(n,count+q1+q2)-len(ans) for j in range(0,min(q1,t)): while temp2[l2[i][1]]==-1: i+=1 temp2[l2[i][1]]=-1 ans.append([l1[n-j-1][1],l2[i][1]]) i=0 t = min(n, count + q1+q2) - len(ans) for j in range(0,t): while temp1[l1[i][1]]==-1: i+=1 temp1[l1[i][1]]=-1 ans.append([l1[i][1],l2[n-j-1][1]]) print(min(n,count+q1+q2)) for i in range(len(ans)): print(*ans[i]) ```
output
1
78,346
6
156,693
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible. Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. * The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. * The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. * The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel. For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o". For example of a not beautiful lyric, "hey man" "iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second). How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times. Input The first line contains single integer n (1 ≀ n ≀ 10^{5}) β€” the number of words. The i-th of the next n lines contains string s_{i} consisting lowercase alphabet letters β€” the i-th word. It is guaranteed that the sum of the total word length is equal or less than 10^{6}. Each word contains at least one vowel. Output In the first line, print m β€” the number of maximum possible beautiful lyrics. In next 2m lines, print m beautiful lyrics (two lines per lyric). If there are multiple answers, print any. Examples Input 14 wow this is the first mcdics codeforces round hooray i am proud about that Output 3 about proud hooray round wow first this is i that mcdics am Input 7 arsijo suggested the idea for this problem Output 0 Input 4 same same same differ Output 1 same differ same same Note In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces". In the second example, you cannot form any beautiful lyric from given words. In the third example, you can use the word "same" up to three times.
instruction
0
78,355
6
156,710
Tags: data structures, greedy, strings Correct Solution: ``` from collections import defaultdict vow = "aeoiu" def vowels(word): c = 0 for i in word: if i in vow: c += 1 return c def last_vov(word): for i in reversed(word): if i in vow: return i dic = defaultdict(lambda : defaultdict(list)) for _ in range(int(input())): inp = input() dic[vowels(inp)][last_vov(inp)].append(inp) first_w,second_w = [],[] for i in dic.values(): first_w_t = [] for words in i.values(): if(len(words) % 2 == 1): if(len(words) >= 2): second_w += words[:-1] first_w_t.append(words[-1]) else: second_w += words if(len(first_w_t) >=2): if(len(first_w_t) % 2 == 1): first_w += first_w_t[:-1] else: first_w += first_w_t # print(first_w,second_w) while(len(second_w) > len(first_w)): first_w.append(second_w.pop()) first_w.append(second_w.pop()) # print(first_w,second_w) print(len(second_w)//2) for i in range(min(len(second_w),len(first_w))): print(first_w[i], second_w[i]) ```
output
1
78,355
6
156,711
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible. Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. * The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. * The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. * The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel. For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o". For example of a not beautiful lyric, "hey man" "iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second). How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times. Input The first line contains single integer n (1 ≀ n ≀ 10^{5}) β€” the number of words. The i-th of the next n lines contains string s_{i} consisting lowercase alphabet letters β€” the i-th word. It is guaranteed that the sum of the total word length is equal or less than 10^{6}. Each word contains at least one vowel. Output In the first line, print m β€” the number of maximum possible beautiful lyrics. In next 2m lines, print m beautiful lyrics (two lines per lyric). If there are multiple answers, print any. Examples Input 14 wow this is the first mcdics codeforces round hooray i am proud about that Output 3 about proud hooray round wow first this is i that mcdics am Input 7 arsijo suggested the idea for this problem Output 0 Input 4 same same same differ Output 1 same differ same same Note In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces". In the second example, you cannot form any beautiful lyric from given words. In the third example, you can use the word "same" up to three times.
instruction
0
78,356
6
156,712
Tags: data structures, greedy, strings Correct Solution: ``` from collections import Counter n = int(input()) d = {} cnt = Counter() for _ in range(n): w = input() last_vow = "" nb = 0 for i in w: if i in "aeiou": nb += 1 last_vow = i if nb in d: if last_vow in d[nb]: d[nb][last_vow].append(w) else: d[nb][last_vow] = [w] else: d[nb] = {last_vow: [w]} cnt.update([nb]) only_first_word = [] second_words = [] for i in d: tmp = [] for j in d[i]: if not cnt[i] > 1: break if len(d[i][j])%2: tmp.append(d[i][j][0]) second_words += d[i][j][1:] else: second_words += d[i][j] if len(tmp) %2: tmp.pop() only_first_word += tmp n = max(min(len(only_first_word), len(second_words)), 0) ans = [] for i in range(n): ans.append((only_first_word[i], second_words[i])) N = len(second_words) for i in range(n, N, 4): if i + 3 >= N: break ans.append((second_words[i], second_words[i+2])) ans.append((second_words[i+1], second_words[i+3])) print(len(ans)//2) for x in ans: print(x[0], x[1]) ```
output
1
78,356
6
156,713
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible. Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. * The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. * The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. * The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel. For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o". For example of a not beautiful lyric, "hey man" "iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second). How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times. Input The first line contains single integer n (1 ≀ n ≀ 10^{5}) β€” the number of words. The i-th of the next n lines contains string s_{i} consisting lowercase alphabet letters β€” the i-th word. It is guaranteed that the sum of the total word length is equal or less than 10^{6}. Each word contains at least one vowel. Output In the first line, print m β€” the number of maximum possible beautiful lyrics. In next 2m lines, print m beautiful lyrics (two lines per lyric). If there are multiple answers, print any. Examples Input 14 wow this is the first mcdics codeforces round hooray i am proud about that Output 3 about proud hooray round wow first this is i that mcdics am Input 7 arsijo suggested the idea for this problem Output 0 Input 4 same same same differ Output 1 same differ same same Note In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces". In the second example, you cannot form any beautiful lyric from given words. In the third example, you can use the word "same" up to three times.
instruction
0
78,357
6
156,714
Tags: data structures, greedy, strings Correct Solution: ``` import sys from collections import defaultdict as dd from collections import deque from functools import * from fractions import Fraction as f from copy import * from bisect import * from heapq import * from math import * from itertools import permutations def eprint(*args): print(*args, file=sys.stderr) zz=1 #sys.setrecursionlimit(10**6) if zz: input=sys.stdin.readline else: sys.stdin=open('input.txt', 'r') sys.stdout=open('all.txt','w') def inc(d,c): d[c]=d[c]+1 if c in d else 1 def li(): return [int(xx) for xx in input().split()] def fli(): return [float(x) for x in input().split()] def comp(a,b): if(a>b): return 2 return 2 if a==b else 0 def gi(): return [xx for xx in input().split()] def fi(): return int(input()) def pro(a): return reduce(lambda a,b:a*b,a) def swap(a,i,j): a[i],a[j]=a[j],a[i] def si(): return list(input().rstrip()) def mi(): return map(int,input().split()) def gh(): sys.stdout.flush() def graph(n,m): for i in range(m): x,y=mi() a[x].append(y) a[y].append(x) def bo(i): return ord(i)-ord('a') def ck(x,y): return int(bin(x)[2:]+bin(y)[2:],2) n=fi() v=['a','e','i','o','u'] dv={'a':0,'e':1,'i':2,'o':3,'u':4} fg={} for _ in range(n): s=si() lv=5 vc=0 for i in range(len(s)): if s[i] in v: vc+=1 lv=dv[s[i]] if vc not in fg: fg[vc]=[[] for j in range(6)] fg[vc][lv].append("".join(s)) r=[[],[]] for i in fg: for j in range(6): while len(fg[i][j])>1: r[0].append([fg[i][j][-1],fg[i][j][-2]]) fg[i][j].pop() fg[i][j].pop() c=0 p=[] for j in range(6): while len(fg[i][j]): if c%2==1: p.append(fg[i][j][-1]) fg[i][j].pop() r[1].append(p) c+=1 p=[] else: p.append(fg[i][j][-1]) fg[i][j].pop() c+=1 ly=[] while len(r[1])<1: if len(r[0])>1: r[1].append(r[0][-1]) r[0].pop() else: break while len(r[0])>=1 and len(r[1])>=1: p=[] p.append(r[1][-1][0]) p.append(r[0][-1][0]) p.append(r[1][-1][1]) p.append(r[0][-1][1]) r[0].pop() r[1].pop() while len(r[1])<1: if len(r[0])>1: r[1].append(r[0][-1]) r[0].pop() else: break ly.append(p) print(len(ly)) for i in ly: print(i[0],i[1]) print(i[2],i[3]) ```
output
1
78,357
6
156,715
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible. Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. * The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. * The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. * The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel. For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o". For example of a not beautiful lyric, "hey man" "iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second). How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times. Input The first line contains single integer n (1 ≀ n ≀ 10^{5}) β€” the number of words. The i-th of the next n lines contains string s_{i} consisting lowercase alphabet letters β€” the i-th word. It is guaranteed that the sum of the total word length is equal or less than 10^{6}. Each word contains at least one vowel. Output In the first line, print m β€” the number of maximum possible beautiful lyrics. In next 2m lines, print m beautiful lyrics (two lines per lyric). If there are multiple answers, print any. Examples Input 14 wow this is the first mcdics codeforces round hooray i am proud about that Output 3 about proud hooray round wow first this is i that mcdics am Input 7 arsijo suggested the idea for this problem Output 0 Input 4 same same same differ Output 1 same differ same same Note In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces". In the second example, you cannot form any beautiful lyric from given words. In the third example, you can use the word "same" up to three times.
instruction
0
78,358
6
156,716
Tags: data structures, greedy, strings Correct Solution: ``` n=int(input()) a=[None]*n d=dict() vov=list("aeiou") for i in range(n): a[i]=input() vc=0 lv="a" for j in a[i]: if j in vov: vc+=1 lv=j try: d[vc][lv].append(a[i]) except: d[vc]={'a': [],'e': [],'i': [],'o': [],'u': []} d[vc][lv].append(a[i]) ans=[[-1 for i in range(4)]for j in range(n)] si=0 fi=0 for i in d.values(): if fi!=int(fi): fi-=0.5 for j in i.values(): for k in range(len(j)//2): ans[si][1]=j[2*k] ans[si][3]=j[2*k+1] si+=1 for k in range((len(j)//2)*2,len(j)): if int(fi)==fi: ans[int(fi)][0]=j[k] else: ans[int(fi)][2]=j[k] fi+=0.5 #print(ans) fa=[] icans=[] for i in range(len(ans)): if ans[i].count(-1)==0: fa.append(ans[i][:]) elif ans[i][1]!=-1 and ans[i][3]!=-1: icans.append([ans[i][1],ans[i][3]]) print(len(fa)+len(icans)//2) for i in range(len(fa)): print(fa[i][0],fa[i][1]) print(fa[i][2],fa[i][3]) for i in range(len(icans)//2): print(icans[i*2][0],icans[i*2+1][0]) print(icans[i*2][1],icans[i*2+1][1]) ```
output
1
78,358
6
156,717
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible. Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. * The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. * The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. * The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel. For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o". For example of a not beautiful lyric, "hey man" "iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second). How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times. Input The first line contains single integer n (1 ≀ n ≀ 10^{5}) β€” the number of words. The i-th of the next n lines contains string s_{i} consisting lowercase alphabet letters β€” the i-th word. It is guaranteed that the sum of the total word length is equal or less than 10^{6}. Each word contains at least one vowel. Output In the first line, print m β€” the number of maximum possible beautiful lyrics. In next 2m lines, print m beautiful lyrics (two lines per lyric). If there are multiple answers, print any. Examples Input 14 wow this is the first mcdics codeforces round hooray i am proud about that Output 3 about proud hooray round wow first this is i that mcdics am Input 7 arsijo suggested the idea for this problem Output 0 Input 4 same same same differ Output 1 same differ same same Note In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces". In the second example, you cannot form any beautiful lyric from given words. In the third example, you can use the word "same" up to three times.
instruction
0
78,359
6
156,718
Tags: data structures, greedy, strings Correct Solution: ``` from collections import deque if True: N = int(input()) # X = [[[] for _ in range(5)] for i in range(500001)] X = {} def calc(t): c = 0 v = 0 for u in reversed(t): if u == "a" or u == "i" or u == "u" or u == "e" or u == "o": if c == 0: if u == "a": v = 0 if u == "i": v = 1 if u == "u": v = 2 if u == "e": v = 3 if u == "o": v = 4 c += 1 if c not in X: X[c] = [[] for _ in range(5)] X[c][v].append(t) for _ in range(N): calc(input()) else: N = 14 X = [[[], [], [], [], []], [['am', 'that'], ['this', 'is', 'first', 'mcdics', 'i'], [], ['the'], ['wow']], [[], [], ['round', 'proud'], [], []], [['hooray'], [], ['about'], [], []], [[], [], [], ['codeforces'], []]] # print("X =", X) A = 0 B = 0 Q = deque([]) for i in X: # print("X[i] =", X[i]) # print([len(x)//2 for x in X[i]]) a = sum([len(x)//2 for x in X[i]]) * 2 b = sum([len(x) for x in X[i]])//2*2 - a A += a B += b # print("a, b, A, B =", a, b, A, B) for j in range(5): while len(X[i][j]) >= 2: deque.appendleft(Q, X[i][j].pop()) deque.appendleft(Q, X[i][j].pop()) for j in range(5): while len(X[i][j]) >= 1 and b > 0: deque.append(Q, X[i][j].pop()) b -= 1 # print("Q =", Q) ans = min(A//2, (A+B)//4) print(ans) for _ in range(ans): print(Q.pop(), Q.popleft()) print(Q.pop(), Q.popleft()) ```
output
1
78,359
6
156,719
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible. Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. * The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. * The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. * The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel. For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o". For example of a not beautiful lyric, "hey man" "iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second). How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times. Input The first line contains single integer n (1 ≀ n ≀ 10^{5}) β€” the number of words. The i-th of the next n lines contains string s_{i} consisting lowercase alphabet letters β€” the i-th word. It is guaranteed that the sum of the total word length is equal or less than 10^{6}. Each word contains at least one vowel. Output In the first line, print m β€” the number of maximum possible beautiful lyrics. In next 2m lines, print m beautiful lyrics (two lines per lyric). If there are multiple answers, print any. Examples Input 14 wow this is the first mcdics codeforces round hooray i am proud about that Output 3 about proud hooray round wow first this is i that mcdics am Input 7 arsijo suggested the idea for this problem Output 0 Input 4 same same same differ Output 1 same differ same same Note In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces". In the second example, you cannot form any beautiful lyric from given words. In the third example, you can use the word "same" up to three times.
instruction
0
78,360
6
156,720
Tags: data structures, greedy, strings Correct Solution: ``` vowels = ['a', 'e', 'i', 'o', 'u'] class word(): def __init__(self, p): o = ([int(p[i] in vowels) for i in range(len(p))]) self.nov = sum(o) o.reverse() self.lastvow = p[len(p) - 1 - o.index(1)] n = int(input()) ug = {} max_keys = 0 com_duos = [] for i in range(n): here = input() wd = word(here) imp = wd.nov if imp > max_keys: for i in range(max_keys+1, imp+1): ug[i] = [[], [], [], [], []] max_keys = imp see = ug[imp][vowels.index(wd.lastvow)] if (see == []): see.append(here) else: com_duos.append([see.pop(), here]) incom_duos = [] for key in ug: vess = '' for v in range(5): if ug[key][v] != []: if vess == '' : vess = ug[key][v][0] else : incom_duos += [[vess, ug[key][v][0]]] vess = '' x, y = len(com_duos), len(incom_duos) m = min(x, (x+y)//2) print(m) for i in range(m): com = com_duos.pop() if(incom_duos != []): incom =incom_duos.pop() else: incom =com_duos.pop() print(incom[0], com[0]) print(incom[1], com[1]) ```
output
1
78,360
6
156,721
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible. Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. * The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. * The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. * The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel. For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o". For example of a not beautiful lyric, "hey man" "iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second). How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times. Input The first line contains single integer n (1 ≀ n ≀ 10^{5}) β€” the number of words. The i-th of the next n lines contains string s_{i} consisting lowercase alphabet letters β€” the i-th word. It is guaranteed that the sum of the total word length is equal or less than 10^{6}. Each word contains at least one vowel. Output In the first line, print m β€” the number of maximum possible beautiful lyrics. In next 2m lines, print m beautiful lyrics (two lines per lyric). If there are multiple answers, print any. Examples Input 14 wow this is the first mcdics codeforces round hooray i am proud about that Output 3 about proud hooray round wow first this is i that mcdics am Input 7 arsijo suggested the idea for this problem Output 0 Input 4 same same same differ Output 1 same differ same same Note In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces". In the second example, you cannot form any beautiful lyric from given words. In the third example, you can use the word "same" up to three times.
instruction
0
78,361
6
156,722
Tags: data structures, greedy, strings Correct Solution: ``` from sys import stdin from collections import deque mod = 10**9 + 7 import sys sys.setrecursionlimit(10**5) from queue import PriorityQueue # def rl(): # return [int(w) for w in stdin.readline().split()] from bisect import bisect_right from bisect import bisect_left from collections import defaultdict from math import sqrt,factorial,gcd,log2,inf,ceil # map(int,input().split()) # # l = list(map(int,input().split())) # from itertools import permutations import heapq # input = lambda: sys.stdin.readline().rstrip() input = lambda : sys.stdin.readline().rstrip() from sys import stdin, stdout from heapq import heapify, heappush, heappop n = int(input()) la = [] for i in range(n): la.append(input()) hash = defaultdict(set) new_hash = defaultdict(list) l = [] cnti = defaultdict(int) for i in la: last = -1 cnt = 0 cnti[i]+=1 for j in i: if j == 'a' or j == 'e' or j == 'i' or j == 'o' or j == 'u': cnt+=1 last = j if last!=-1: hash[cnt].add(i) if new_hash[(last,cnt)] == []: new_hash[(last,cnt)].append(i) else: z = new_hash[(last,cnt)].pop() l.append((z,i)) for a,b in l: cnti[a]-=1 cnti[b]-=1 ans = [] # print(l) # print(hash) for i in la: cnt = 0 if l == []: break for j in i: if j == 'a' or j == 'e' or j == 'i' or j == 'o' or j == 'u': cnt+=1 last = j if cnti[i]>=2: cnti[i]-=2 a,b = l.pop(0) ans.append((i,a,i,b)) continue for j in hash[cnt]: if cnti[i] == 0: break if cnti[j] == 0 or i == j: continue cnti[i]-=1 cnti[j]-=1 a,b = l.pop(0) ans.append((i,a,j,b)) break for i in range(0,len(l),2): a,b = l[i] try: c,d = l[i+1] ans.append((a,c,b,d)) except: break print(len(ans)) for i in ans: a,b,c,d = i print(a,b) print(c,d) ```
output
1
78,361
6
156,723
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible. Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. * The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. * The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. * The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel. For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o". For example of a not beautiful lyric, "hey man" "iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second). How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times. Input The first line contains single integer n (1 ≀ n ≀ 10^{5}) β€” the number of words. The i-th of the next n lines contains string s_{i} consisting lowercase alphabet letters β€” the i-th word. It is guaranteed that the sum of the total word length is equal or less than 10^{6}. Each word contains at least one vowel. Output In the first line, print m β€” the number of maximum possible beautiful lyrics. In next 2m lines, print m beautiful lyrics (two lines per lyric). If there are multiple answers, print any. Examples Input 14 wow this is the first mcdics codeforces round hooray i am proud about that Output 3 about proud hooray round wow first this is i that mcdics am Input 7 arsijo suggested the idea for this problem Output 0 Input 4 same same same differ Output 1 same differ same same Note In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces". In the second example, you cannot form any beautiful lyric from given words. In the third example, you can use the word "same" up to three times.
instruction
0
78,362
6
156,724
Tags: data structures, greedy, strings Correct Solution: ``` def countvowels(s): count = 0 for i in s: if i in vowels: count += 1 last = i return count,last n = int(input()) a = [] count = {} vowels = {"a",'e','i','o','u'} last = {} for i in range(n): s = input() d,l = countvowels(s) if d not in count: count[d] = [s] else: count[d].append(s) last[s] = l lword = [] fword = [] for i in count: d = {} for j in count[i]: if last[j] not in d: d[last[j]] = j else: lword.append((j,d[last[j]])) del d[last[j]] if len(d)>1: k = [] for j in d: k.append(d[j]) for j in range(0,len(k)-1,2): fword.append((k[j],k[j+1])) # print (lword) # print (fword) if len(fword)<=len(lword): ans = (len(fword)+(len(lword)-len(fword))//2) print (ans) for i in range(len(fword)): print (fword[i][0],lword[i][0]) print (fword[i][1],lword[i][1]) for i in range(len(fword),len(lword)-1,2): print (lword[i][0],lword[i+1][0]) print (lword[i][1],lword[i+1][1]) else: ans = len(lword) print (ans) for i in range(ans): print (fword[i][0],lword[i][0]) print (fword[i][1],lword[i][1]) ```
output
1
78,362
6
156,725
Provide tags and a correct Python 3 solution for this coding contest problem. Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba. Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle? Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters. Output In a single line print the answer to the problem β€” the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them. Examples Input 2 ?ab ??b Output xab Input 2 a b Output ? Input 1 ?a?b Output cacb Note Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
instruction
0
78,617
6
157,234
Tags: implementation, strings Correct Solution: ``` z=['?']*100000;s=0 for _ in " "*int(input()): t=list(map(str,input().replace(""," ").split())) s=len(t) for i in range(len(t)): if z[i]=="@" or z[i]==t[i]=="?":continue if t[i]!="?" and z[i]=="?":z[i]=t[i] elif t[i]!="?" and z[i]!="?" and z[i]!=t[i]:z[i]="@" z=z[:s] for i in z: if i=="@":print("?",end="") elif i=="?":print("a",end="") else:print(i,end="") ```
output
1
78,617
6
157,235
Provide tags and a correct Python 3 solution for this coding contest problem. Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba. Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle? Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters. Output In a single line print the answer to the problem β€” the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them. Examples Input 2 ?ab ??b Output xab Input 2 a b Output ? Input 1 ?a?b Output cacb Note Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
instruction
0
78,618
6
157,236
Tags: implementation, strings Correct Solution: ``` from sys import stdin n = int(input()) ips = [] for _ in range(n): arr = stdin.readline().rstrip() ips.append(arr) output = ['?'] * len(ips[0]) for i in range(len(ips[0])): countSet = set() for j in range(n): if ips[j][i] != '?': countSet.add(ips[j][i]) if len(countSet) > 1: break else: if len(countSet) == 0: output[i] = 'x' else: output[i] = countSet.pop() print(''.join(output)) ```
output
1
78,618
6
157,237
Provide tags and a correct Python 3 solution for this coding contest problem. Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba. Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle? Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters. Output In a single line print the answer to the problem β€” the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them. Examples Input 2 ?ab ??b Output xab Input 2 a b Output ? Input 1 ?a?b Output cacb Note Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
instruction
0
78,619
6
157,238
Tags: implementation, strings Correct Solution: ``` for S in zip(*(input() for _ in range(int(input())))): L = set(S) - {'?'} if len(L) > 1: print('?', end='') elif len(L) > 0: print(*L, end='') else: print('a', end='') ```
output
1
78,619
6
157,239
Provide tags and a correct Python 3 solution for this coding contest problem. Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba. Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle? Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters. Output In a single line print the answer to the problem β€” the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them. Examples Input 2 ?ab ??b Output xab Input 2 a b Output ? Input 1 ?a?b Output cacb Note Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
instruction
0
78,620
6
157,240
Tags: implementation, strings Correct Solution: ``` import sys import itertools WILDCARD = '?' FILL = 'x' def main(): pattern_count = int(sys.stdin.readline()) patterns = itertools.islice(sys.stdin, pattern_count) result = intersect_patterns(p.strip() for p in patterns) print(result) def intersect_patterns(lines): return ''.join(_intersect_patterns(lines)) def _intersect_patterns(lines): first, *patterns = lines for position, char in enumerate(first): unique_chars = set(pattern[position] for pattern in patterns) unique_chars.add(char) unique_chars.discard(WILDCARD) if not unique_chars: yield FILL elif len(unique_chars) == 1: yield unique_chars.pop() else: yield WILDCARD if __name__ == '__main__': main() ```
output
1
78,620
6
157,241
Provide tags and a correct Python 3 solution for this coding contest problem. Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba. Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle? Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters. Output In a single line print the answer to the problem β€” the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them. Examples Input 2 ?ab ??b Output xab Input 2 a b Output ? Input 1 ?a?b Output cacb Note Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
instruction
0
78,621
6
157,242
Tags: implementation, strings Correct Solution: ``` n, t = int(input()), list(input()) for i in range(n - 1): for j, c in enumerate(input()): if t[j] == '!' or c == '?': continue if t[j] == '?': t[j] = c elif t[j] != c: t[j] = '!' print(''.join(t).replace('?', 'x').replace('!', '?')) ```
output
1
78,621
6
157,243
Provide tags and a correct Python 3 solution for this coding contest problem. Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba. Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle? Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters. Output In a single line print the answer to the problem β€” the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them. Examples Input 2 ?ab ??b Output xab Input 2 a b Output ? Input 1 ?a?b Output cacb Note Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
instruction
0
78,622
6
157,244
Tags: implementation, strings Correct Solution: ``` n = int(input()) s = input() str_len = len(s) good = [] for ch in s: if ch == '?': good.append('$') else: good.append(ch) r = range(n - 1) for i in r: s = input() j = int(0) while j < str_len: if (s[j] == '?') and (good[j] == '$'): good[j] = '$'; elif s[j] == '?': good[j] = good[j] elif good[j] == '$': good[j] = s[j] elif not(s[j] == good[j]): good[j] = '?' j = j + 1 ans = "" for ch in good: if ch == '$': ans = ans + 'z' else: ans = ans + ch print(ans) ```
output
1
78,622
6
157,245
Provide tags and a correct Python 3 solution for this coding contest problem. Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba. Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle? Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters. Output In a single line print the answer to the problem β€” the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them. Examples Input 2 ?ab ??b Output xab Input 2 a b Output ? Input 1 ?a?b Output cacb Note Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
instruction
0
78,623
6
157,246
Tags: implementation, strings Correct Solution: ``` from collections import Counter def best(t): cnt = Counter(t) if len(cnt) == 0: return 'a' if len(cnt) == 1: return t[0] return '?' n = int(input()) l = [] for i in range(n): l.append(input()) print(''.join(best([c for c in t if c != '?']) for t in zip(*l))) ```
output
1
78,623
6
157,247
Provide tags and a correct Python 3 solution for this coding contest problem. Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba. Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle? Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters. Output In a single line print the answer to the problem β€” the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them. Examples Input 2 ?ab ??b Output xab Input 2 a b Output ? Input 1 ?a?b Output cacb Note Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
instruction
0
78,624
6
157,248
Tags: implementation, strings Correct Solution: ``` import sys input = sys.stdin.readline ''' ''' n = int(input()) res = list(input().rstrip()) good = [1] * len(res) for _ in range(n-1): p = input().rstrip() for i, char in enumerate(p): if char == "?" or char == res[i]: continue elif char != res[i] and res[i] != "?": # collision res[i] = "?" good[i] = 0 elif res[i] == "?" and good[i]: res[i] = char for i in range(len(res)): if res[i] == "?" and good[i]: res[i] = "x" print("".join(res)) ```
output
1
78,624
6
157,249
Provide tags and a correct Python 3 solution for this coding contest problem. There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name. There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account? Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements. For example, the following pairs of words denote the same name: * "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper". * "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name. Input The first line contains integer number n (2 ≀ n ≀ 400) β€” number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive. Output Print the minimal number of groups where the words in each group denote the same name. Examples Input 10 mihail oolyana kooooper hoon ulyana koouper mikhail khun kuooper kkkhoon Output 4 Input 9 hariton hkariton buoi kkkhariton boooi bui khariton boui boi Output 5 Input 2 alex alex Output 1 Note There are four groups of words in the first example. Words in each group denote same name: 1. "mihail", "mikhail" 2. "oolyana", "ulyana" 3. "kooooper", "koouper" 4. "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name: 1. "hariton", "kkkhariton", "khariton" 2. "hkariton" 3. "buoi", "boooi", "boui" 4. "bui" 5. "boi" In the third example the words are equal, so they denote the same name.
instruction
0
78,814
6
157,628
Tags: implementation Correct Solution: ``` n = int(input()) ans = set() for i in range(n): s = str(input()) s = s.replace("u", "oo") # print(s) while "kh" in s: s = s.replace("kh", "h") # print(s) ans.add(s) print(len(ans)) # print(ans) ```
output
1
78,814
6
157,629
Provide tags and a correct Python 3 solution for this coding contest problem. There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name. There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account? Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements. For example, the following pairs of words denote the same name: * "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper". * "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name. Input The first line contains integer number n (2 ≀ n ≀ 400) β€” number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive. Output Print the minimal number of groups where the words in each group denote the same name. Examples Input 10 mihail oolyana kooooper hoon ulyana koouper mikhail khun kuooper kkkhoon Output 4 Input 9 hariton hkariton buoi kkkhariton boooi bui khariton boui boi Output 5 Input 2 alex alex Output 1 Note There are four groups of words in the first example. Words in each group denote same name: 1. "mihail", "mikhail" 2. "oolyana", "ulyana" 3. "kooooper", "koouper" 4. "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name: 1. "hariton", "kkkhariton", "khariton" 2. "hkariton" 3. "buoi", "boooi", "boui" 4. "bui" 5. "boi" In the third example the words are equal, so they denote the same name.
instruction
0
78,815
6
157,630
Tags: implementation Correct Solution: ``` d = {} n = int(input()) def simpler(word): p = 0 while p <= len(word): if word[p:p+1] == "u": word = word[:p] + "oo" + word[p+1:] p = 0 elif word[p:p+2] == "kh": word = word[:p] + "h" + word[p+2:] p = 0 else: p += 1 return word for i in range(n): word = simpler(input()) if word not in d: d[word] = 1 else: d[word] = d[word] + 1 print(len(d)) ```
output
1
78,815
6
157,631
Provide tags and a correct Python 3 solution for this coding contest problem. There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name. There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account? Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements. For example, the following pairs of words denote the same name: * "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper". * "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name. Input The first line contains integer number n (2 ≀ n ≀ 400) β€” number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive. Output Print the minimal number of groups where the words in each group denote the same name. Examples Input 10 mihail oolyana kooooper hoon ulyana koouper mikhail khun kuooper kkkhoon Output 4 Input 9 hariton hkariton buoi kkkhariton boooi bui khariton boui boi Output 5 Input 2 alex alex Output 1 Note There are four groups of words in the first example. Words in each group denote same name: 1. "mihail", "mikhail" 2. "oolyana", "ulyana" 3. "kooooper", "koouper" 4. "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name: 1. "hariton", "kkkhariton", "khariton" 2. "hkariton" 3. "buoi", "boooi", "boui" 4. "bui" 5. "boi" In the third example the words are equal, so they denote the same name.
instruction
0
78,816
6
157,632
Tags: implementation Correct Solution: ``` def conv(s): s = s.replace('u','oo') while 'kh' in s: s = s.replace('kh','h') #print(s) return s n = int(input()) arr = set() for i in range(n): s = input() arr.add(conv(s)) print(len(arr)) ```
output
1
78,816
6
157,633
Provide tags and a correct Python 3 solution for this coding contest problem. There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name. There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account? Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements. For example, the following pairs of words denote the same name: * "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper". * "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name. Input The first line contains integer number n (2 ≀ n ≀ 400) β€” number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive. Output Print the minimal number of groups where the words in each group denote the same name. Examples Input 10 mihail oolyana kooooper hoon ulyana koouper mikhail khun kuooper kkkhoon Output 4 Input 9 hariton hkariton buoi kkkhariton boooi bui khariton boui boi Output 5 Input 2 alex alex Output 1 Note There are four groups of words in the first example. Words in each group denote same name: 1. "mihail", "mikhail" 2. "oolyana", "ulyana" 3. "kooooper", "koouper" 4. "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name: 1. "hariton", "kkkhariton", "khariton" 2. "hkariton" 3. "buoi", "boooi", "boui" 4. "bui" 5. "boi" In the third example the words are equal, so they denote the same name.
instruction
0
78,817
6
157,634
Tags: implementation Correct Solution: ``` n=int(input()) arr=[] count=0 for i in range(n): x=input() while "kh" in x: x=x.replace("kh","h") while "u" in x: x=x.replace("u","oo") if x not in arr: count+=1 arr.append(x) print(count) ```
output
1
78,817
6
157,635