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. As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. Input The first line contains two lowercase English letters — the password on the phone. The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows. The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct. Output Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). Examples Input ya 4 ah oy to ha Output YES Input hp 2 ht tp Output NO Input ah 1 ha Output YES Note In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES". In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring. In the third example the string "hahahaha" contains "ah" as a substring.
instruction
0
86,218
6
172,436
Tags: brute force, implementation, strings Correct Solution: ``` passwd = input() words = [] for _ in range(int(input())): word = input() for i in word: if i in passwd: words.append(word) break for i in words: for j in words: if passwd in i + j: print('YES') break else: continue break else: print('NO') ```
output
1
86,218
6
172,437
Provide tags and a correct Python 3 solution for this coding contest problem. As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. Input The first line contains two lowercase English letters — the password on the phone. The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows. The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct. Output Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). Examples Input ya 4 ah oy to ha Output YES Input hp 2 ht tp Output NO Input ah 1 ha Output YES Note In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES". In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring. In the third example the string "hahahaha" contains "ah" as a substring.
instruction
0
86,219
6
172,438
Tags: brute force, implementation, strings Correct Solution: ``` s = input() n = int(input()) a = [input() for i in range(n)] for i in range(n): for j in range(n): if a[i] == s or a[i][1] + a[j][0] == s: print("YES") exit(0) print("NO") ```
output
1
86,219
6
172,439
Provide tags and a correct Python 3 solution for this coding contest problem. As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. Input The first line contains two lowercase English letters — the password on the phone. The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows. The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct. Output Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). Examples Input ya 4 ah oy to ha Output YES Input hp 2 ht tp Output NO Input ah 1 ha Output YES Note In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES". In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring. In the third example the string "hahahaha" contains "ah" as a substring.
instruction
0
86,220
6
172,440
Tags: brute force, implementation, strings Correct Solution: ``` password =input() n = int(input()) n1 = n li = [] i = 1 check = False while n != 0: temp = input() li.append(temp) n -= 1 for i in range(0,n1): for j in range(0,n1): a = li[i] + li[j] b = li[j] + li[i] if password in a or password in b: check = True if check: print("YES") else: print("NO") ```
output
1
86,220
6
172,441
Provide tags and a correct Python 3 solution for this coding contest problem. As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. Input The first line contains two lowercase English letters — the password on the phone. The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows. The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct. Output Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). Examples Input ya 4 ah oy to ha Output YES Input hp 2 ht tp Output NO Input ah 1 ha Output YES Note In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES". In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring. In the third example the string "hahahaha" contains "ah" as a substring.
instruction
0
86,221
6
172,442
Tags: brute force, implementation, strings Correct Solution: ``` password = input() n = int(input()) firstLetter = 0 secondLetter = 0 found = 0 for i in range(n): inputStr = input() if inputStr == password: found = 1 if inputStr[1] == password[0]: firstLetter = 1 if inputStr[0] == password[1]: secondLetter = 1 if ( found or (firstLetter and secondLetter) ): print('YES') else: print('NO') ```
output
1
86,221
6
172,443
Provide tags and a correct Python 3 solution for this coding contest problem. As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. Input The first line contains two lowercase English letters — the password on the phone. The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows. The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct. Output Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). Examples Input ya 4 ah oy to ha Output YES Input hp 2 ht tp Output NO Input ah 1 ha Output YES Note In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES". In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring. In the third example the string "hahahaha" contains "ah" as a substring.
instruction
0
86,222
6
172,444
Tags: brute force, implementation, strings Correct Solution: ``` s=input();n=int(input());x=0;y=0;k='';pd=0 for i in range(0,n): k=input() if k==s: print('YES') pd=1 break else: if k[0]==s[1]: x=1 if k[1]==s[0]: y=1 if x==1 and y==1: print('YES') pd=1 break if pd==0: print('NO') ```
output
1
86,222
6
172,445
Provide a correct Python 3 solution for this coding contest problem. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6
instruction
0
86,492
6
172,984
"Correct Solution: ``` class CheckError(Exception): pass def check(wclist, count): c = 0 while True: c += wclist.pop(0) if c == count: return wclist elif c > count: raise CheckError def tanku_check(wclist): for i in range(len(wclist)): try: wcl = wclist[:][i:] wcl = check(wcl, 5) wcl = check(wcl, 7) wcl = check(wcl, 5) wcl = check(wcl, 7) wcl = check(wcl, 7) return i+1 except CheckError: pass def main(): while True: n = int(input().strip()) if n == 0: break wclist = [len(input().strip()) for _ in range(n)] print(tanku_check(wclist)) if __name__ == '__main__': main() ```
output
1
86,492
6
172,985
Provide a correct Python 3 solution for this coding contest problem. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6
instruction
0
86,493
6
172,986
"Correct Solution: ``` while True: n = int(input()) if n==0: break w = [len(input()) for i in range(n)] a = [5,7,5,7,7] ans = n+1 for i in range(n): k,s = 0,0 for j in range(i,n): s += w[j] if s==a[k]: s,k=0,k+1 elif s>a[k]: break if k==5: ans = min(ans,i+1) break print(ans) ```
output
1
86,493
6
172,987
Provide a correct Python 3 solution for this coding contest problem. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6
instruction
0
86,494
6
172,988
"Correct Solution: ``` while True: n = int(input()) if n == 0: break else: phlist=[] phflag=0 for i in range(n): phlist.append(input()) for i in range(len(phlist)-4): cur=0 state=0 for j in range(i, len(phlist)): s = phlist[j] cur+=len(s) if state==0 and cur<5: continue elif state==0 and cur==5: cur=0 state=1 elif state==1 and cur<7: continue elif state==1 and cur==7: cur=0 state=2 elif state==2 and cur<5: continue elif state==2 and cur==5: cur=0 state=3 elif state==3 and cur<7: continue elif state==3 and cur==7: cur=0 state=4 elif state==4 and cur<7: continue elif state==4 and cur==7: print(i+1) phflag=1 break if phflag: break ```
output
1
86,494
6
172,989
Provide a correct Python 3 solution for this coding contest problem. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6
instruction
0
86,495
6
172,990
"Correct Solution: ``` from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,datetime sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inpl(): return list(map(int, input().split())) def inpl_str(): return list(input().split()) while True: n = int(input()) if n == 0: break else: ww = [len(input()) for i in range(n)] L = [5,7,5,7,7] for i in range(n): k = i tmp = 0 S = 0 flag = False while True: w = ww[k] if L[tmp] - S > w: S += w elif L[tmp] - S == w: tmp += 1 S = 0 else: break if tmp == 5: flag = True break k += 1 if flag: print(i+1) break ```
output
1
86,495
6
172,991
Provide a correct Python 3 solution for this coding contest problem. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6
instruction
0
86,496
6
172,992
"Correct Solution: ``` while True: n = int(input()) if n == 0: break count = [0] * n for i in range(n): count[i] = len(input()) for i in range(n-4): ind = i fin = True for tmp in [5, 7, 5, 7, 7]: while tmp > 0 and ind < n: tmp -= count[ind] ind += 1 if tmp != 0: fin = False break if fin: print(i+1) break ```
output
1
86,496
6
172,993
Provide a correct Python 3 solution for this coding contest problem. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6
instruction
0
86,497
6
172,994
"Correct Solution: ``` while True: n = int(input()) if n == 0: break a = [] for i in range(n): p = list(input()) a.append(len(p)) def solve(a): N = len(a) for i in range(N): judge = 0 rest = 5 for j in range(i,N): if judge == 0: rest -= a[j] if rest == 0: judge = 1 rest = 7 elif rest < 0: break elif judge == 1: rest -= a[j] if rest == 0: judge = 2 rest = 5 if rest < 0: break elif judge == 2: rest -= a[j] if rest == 0: judge = 3 rest = 7 elif rest < 0: break elif judge == 3: rest -= a[j] if rest == 0: judge = 4 rest = 7 elif rest < 0: break elif judge == 4: rest -= a[j] if rest == 0: judge = 5 break elif rest < 0: break if judge == 5: return i+1 print(solve(a)) ```
output
1
86,497
6
172,995
Provide a correct Python 3 solution for this coding contest problem. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6
instruction
0
86,498
6
172,996
"Correct Solution: ``` # AOJ 1601: Short Phrase # Python3 2018.7.13 bal4u a = [5,7,5,7,7] while True: n = int(input()) if n == 0: break ans = 0 w = [len(input()) for i in range(n)] for i in range(n): k = s = 0 for j in range(i, n): s += w[j] if s == a[k]: s, k = 0, k+1 if k == 5: ans = i+1; break elif s > a[k]: break if ans: break print(ans) ```
output
1
86,498
6
172,997
Provide a correct Python 3 solution for this coding contest problem. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6
instruction
0
86,499
6
172,998
"Correct Solution: ``` def solve(): n = int(input()) if n == 0: return False ok = [5, 7, 5, 7, 7] inputs = [input() for x in range(n)] for i in range(n): target = 0 cnt = i for v in ok: while target < v: s = inputs[cnt] target += len(s) cnt += 1 if target != v: break else: target = 0 else: print(i + 1) return True return True while solve(): pass ```
output
1
86,499
6
172,999
Provide tags and a correct Python 3 solution for this coding contest problem. Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 ≤ p < |s|) and perform one of the following actions: * either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it; * or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it. Let us note that letter "z" doesn't have a defined following letter and letter "a" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed. Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations. Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7). Input The input data contains several tests. The first line contains the only integer t (1 ≤ t ≤ 104) — the number of tests. Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ. Output For each word you should print the number of different other words that coincide with it in their meaning — not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7). Examples Input 1 ab Output 1 Input 1 aaaaaaaaaaa Output 0 Input 2 ya klmbfxzb Output 24 320092793 Note Some explanations about the operation: * Note that for each letter, we can clearly define the letter that follows it. Letter "b" alphabetically follows letter "a", letter "c" follows letter "b", ..., "z" follows letter "y". * Preceding letters are defined in the similar manner: letter "y" precedes letter "z", ..., "a" precedes letter "b". * Note that the operation never changes a word's length. In the first sample you can obtain the only other word "ba". In the second sample you cannot obtain any other word, so the correct answer is 0. Consider the third sample. One operation can transform word "klmbfxzb" into word "klmcexzb": we should choose p = 4, and replace the fourth letter with the following one ("b" → "c"), and the fifth one — with the preceding one ("f" → "e"). Also, we can obtain many other words from this one. An operation can transform word "ya" only into one other word "xb". Word "ya" coincides in its meaning with words "xb", "wc", "vd", ..., "ay" (overall there are 24 other words). The word "klmbfxzb has many more variants — there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 — the number 3320092814 modulo 109 + 7
instruction
0
86,901
6
173,802
Tags: combinatorics, dp Correct Solution: ``` S, N = 2505, 105 m = 1000000007 k = 26 p = [[0] * (S + k) for i in range(N)] p[0][0] = 1 for n in range(1, N): for s in range(S): p[n][s] = (p[n][s - 1] + p[n - 1][s] - p[n - 1][s - k]) % m r = [] for j in range(int(input())): t = input() s = sum(ord(q) - 97 for q in t) print(p[len(t)][s] - 1) ```
output
1
86,901
6
173,803
Provide tags and a correct Python 3 solution for this coding contest problem. Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 ≤ p < |s|) and perform one of the following actions: * either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it; * or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it. Let us note that letter "z" doesn't have a defined following letter and letter "a" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed. Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations. Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7). Input The input data contains several tests. The first line contains the only integer t (1 ≤ t ≤ 104) — the number of tests. Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ. Output For each word you should print the number of different other words that coincide with it in their meaning — not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7). Examples Input 1 ab Output 1 Input 1 aaaaaaaaaaa Output 0 Input 2 ya klmbfxzb Output 24 320092793 Note Some explanations about the operation: * Note that for each letter, we can clearly define the letter that follows it. Letter "b" alphabetically follows letter "a", letter "c" follows letter "b", ..., "z" follows letter "y". * Preceding letters are defined in the similar manner: letter "y" precedes letter "z", ..., "a" precedes letter "b". * Note that the operation never changes a word's length. In the first sample you can obtain the only other word "ba". In the second sample you cannot obtain any other word, so the correct answer is 0. Consider the third sample. One operation can transform word "klmbfxzb" into word "klmcexzb": we should choose p = 4, and replace the fourth letter with the following one ("b" → "c"), and the fifth one — with the preceding one ("f" → "e"). Also, we can obtain many other words from this one. An operation can transform word "ya" only into one other word "xb". Word "ya" coincides in its meaning with words "xb", "wc", "vd", ..., "ay" (overall there are 24 other words). The word "klmbfxzb has many more variants — there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 — the number 3320092814 modulo 109 + 7
instruction
0
86,902
6
173,804
Tags: combinatorics, dp Correct Solution: ``` S, N = 2501, 101 m = 1000000007 k = 26 p = [[0] * (S + k) for i in range(N)] p[0][0] = 1 for n in range(1, N): for s in range(S): p[n][s] = (p[n][s - 1] + p[n - 1][s] - p[n - 1][s - k]) % m r = [] for j in range(int(input())): t = input() s = sum(ord(q) - 97 for q in t) print(p[len(t)][s] - 1) ```
output
1
86,902
6
173,805
Provide tags and a correct Python 3 solution for this coding contest problem. Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 ≤ p < |s|) and perform one of the following actions: * either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it; * or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it. Let us note that letter "z" doesn't have a defined following letter and letter "a" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed. Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations. Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7). Input The input data contains several tests. The first line contains the only integer t (1 ≤ t ≤ 104) — the number of tests. Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ. Output For each word you should print the number of different other words that coincide with it in their meaning — not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7). Examples Input 1 ab Output 1 Input 1 aaaaaaaaaaa Output 0 Input 2 ya klmbfxzb Output 24 320092793 Note Some explanations about the operation: * Note that for each letter, we can clearly define the letter that follows it. Letter "b" alphabetically follows letter "a", letter "c" follows letter "b", ..., "z" follows letter "y". * Preceding letters are defined in the similar manner: letter "y" precedes letter "z", ..., "a" precedes letter "b". * Note that the operation never changes a word's length. In the first sample you can obtain the only other word "ba". In the second sample you cannot obtain any other word, so the correct answer is 0. Consider the third sample. One operation can transform word "klmbfxzb" into word "klmcexzb": we should choose p = 4, and replace the fourth letter with the following one ("b" → "c"), and the fifth one — with the preceding one ("f" → "e"). Also, we can obtain many other words from this one. An operation can transform word "ya" only into one other word "xb". Word "ya" coincides in its meaning with words "xb", "wc", "vd", ..., "ay" (overall there are 24 other words). The word "klmbfxzb has many more variants — there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 — the number 3320092814 modulo 109 + 7
instruction
0
86,903
6
173,806
Tags: combinatorics, dp Correct Solution: ``` p = [[0] * 2527 for i in range(101)] p[0][0] = 1 for n in range(100): for s in range(2501): p[n + 1][s] = (p[n + 1][s - 1] + p[n][s] - p[n][s - 26]) % 1000000007 for j in range(int(input())): t = input() s = sum(ord(q) - 97 for q in t) print(p[len(t)][s] - 1) ```
output
1
86,903
6
173,807
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya is a born Berland film director, he is currently working on a new blockbuster, "The Unexpected". Vasya knows from his own experience how important it is to choose the main characters' names and surnames wisely. He made up a list of n names and n surnames that he wants to use. Vasya haven't decided yet how to call characters, so he is free to match any name to any surname. Now he has to make the list of all the main characters in the following format: "Name1 Surname1, Name2 Surname2, ..., Namen Surnamen", i.e. all the name-surname pairs should be separated by exactly one comma and exactly one space, and the name should be separated from the surname by exactly one space. First of all Vasya wants to maximize the number of the pairs, in which the name and the surname start from one letter. If there are several such variants, Vasya wants to get the lexicographically minimal one. Help him. An answer will be verified a line in the format as is shown above, including the needed commas and spaces. It's the lexicographical minimality of such a line that needs to be ensured. The output line shouldn't end with a space or with a comma. Input The first input line contains number n (1 ≤ n ≤ 100) — the number of names and surnames. Then follow n lines — the list of names. Then follow n lines — the list of surnames. No two from those 2n strings match. Every name and surname is a non-empty string consisting of no more than 10 Latin letters. It is guaranteed that the first letter is uppercase and the rest are lowercase. Output The output data consist of a single line — the needed list. Note that one should follow closely the output data format! Examples Input 4 Ann Anna Sabrina John Petrov Ivanova Stoltz Abacaba Output Ann Abacaba, Anna Ivanova, John Petrov, Sabrina Stoltz Input 4 Aa Ab Ac Ba Ad Ae Bb Bc Output Aa Ad, Ab Ae, Ac Bb, Ba Bc Submitted Solution: ``` n = int(input()) F = [input() for _ in range(n)] L = [input() for _ in range(n)] F.sort() L.sort() i = 0 j = 0 def name(a,b): return a + ' ' + b names = [] while i < len(F) and j < len(L): if F[i][0] == L[j][0]: names.append(name(F[i], L[j])) del F[i] del L[j] elif F[i][0] < L[j][0]: i += 1 elif F[i][0] > L[j][0]: j += 1 othernames = [name(a,b) for a,b in zip(F,L)] names.reverse() othernames.reverse() res = [] while names and othernames: if names[-1] > othernames[-1]: res.append(othernames.pop()) elif names[-1] < othernames[-1]: res.append(names.pop()) res += names res += othernames print(', '.join(res)) ```
instruction
0
87,032
6
174,064
No
output
1
87,032
6
174,065
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence. He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not. Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes). Input First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100. Output Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower). Examples Input 6 tom lucius ginny harry ginny harry Output NO NO NO NO YES YES Input 3 a a a Output NO YES YES Note In test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".
instruction
0
87,206
6
174,412
Tags: brute force, implementation, strings Correct Solution: ``` import sys names = sys.stdin.readlines()[1:] for n, name in enumerate(names): if name in names[:n]: print('YES') else: print('NO') ```
output
1
87,206
6
174,413
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence. He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not. Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes). Input First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100. Output Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower). Examples Input 6 tom lucius ginny harry ginny harry Output NO NO NO NO YES YES Input 3 a a a Output NO YES YES Note In test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".
instruction
0
87,209
6
174,418
Tags: brute force, implementation, strings Correct Solution: ``` n = int(input()) a = [] for i in range(n): a.append(input()) for i in range(n): f = 0 for j in range(i): if a[i] == a[j]: print("YES") f = 1 break if f == 0: print("NO") ```
output
1
87,209
6
174,419
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence. He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not. Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes). Input First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100. Output Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower). Examples Input 6 tom lucius ginny harry ginny harry Output NO NO NO NO YES YES Input 3 a a a Output NO YES YES Note In test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".
instruction
0
87,210
6
174,420
Tags: brute force, implementation, strings Correct Solution: ``` n=int(input()) l=[] for i in range(n): a=input() if a not in l: print('NO') l.append(a) else: print('YES') ```
output
1
87,210
6
174,421
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence. He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not. Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes). Input First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100. Output Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower). Examples Input 6 tom lucius ginny harry ginny harry Output NO NO NO NO YES YES Input 3 a a a Output NO YES YES Note In test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".
instruction
0
87,211
6
174,422
Tags: brute force, implementation, strings Correct Solution: ``` # import sys # sys.stdin=open('input.in','r') # sys.stdout=open('output.out','w') n=int(input()) p=[] for x in range(n): k=input() if k not in p: print('NO') p.append(k) else: print('YES') ```
output
1
87,211
6
174,423
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence. He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not. Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes). Input First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100. Output Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower). Examples Input 6 tom lucius ginny harry ginny harry Output NO NO NO NO YES YES Input 3 a a a Output NO YES YES Note In test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".
instruction
0
87,212
6
174,424
Tags: brute force, implementation, strings Correct Solution: ``` # import sys # sys.stdin=open("input.in","r") # sys.stdout=open("output.out","w") x=int(input()) L=[] X={} FLAG=0 for i in range(x): FLAG=0 L.append(input()) for j in range(i): if L[i]==L[j]: print("YES") FLAG=1 break if FLAG==0: print("NO") ```
output
1
87,212
6
174,425
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence. He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not. Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes). Input First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100. Output Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower). Examples Input 6 tom lucius ginny harry ginny harry Output NO NO NO NO YES YES Input 3 a a a Output NO YES YES Note In test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".
instruction
0
87,213
6
174,426
Tags: brute force, implementation, strings Correct Solution: ``` number=int(input()) lst=[] for i in range(number): x=input() lst.append(x) for i in range (number): for j in range(0,i): if lst[i]==lst[j]: print ("Yes") break; else: print ( "NO") ```
output
1
87,213
6
174,427
Provide a correct Python 3 solution for this coding contest problem. Emacs is a text editor which is widely used by many programmers. The advantage of Emacs is that we can move a cursor without arrow keys and the mice. For example, the cursor can be moved right, left, down, and up by pushing f, b, n, p with the Control Key respectively. In addition, cut-and-paste can be performed without the mouse. Your task is to write a program which simulates key operations in the Emacs-like editor. The program should read a text and print the corresponding edited text. The text consists of several lines and each line consists of zero or more alphabets and space characters. A line, which does not have any character, is a blank line. The editor has a cursor which can point out a character or the end-of-line in the corresponding line. The cursor can also point out the end-of-line in a blank line. In addition, the editor has a buffer which can hold either a string (a sequence of characters) or a linefeed. The editor accepts the following set of commands (If the corresponding line is a blank line, the word "the first character" should be "the end-of-line"): * a Move the cursor to the first character of the current line. * e Move the cursor to the end-of-line of the current line. * p Move the cursor to the first character of the next upper line, if it exists. If there is no line above the current line, move the cursor to the first character of the current line. * n Move the cursor to the first character of the next lower line, if it exists. If there is no line below the current line, move the cursor to the first character of the current line. * f Move the cursor by one character to the right, unless the cursor points out the end-of-line. If the cursor points out the end-of-line and there is a line below the current line, move the cursor to the first character of the next lower line. Otherwise, do nothing. * b Move the cursor by one character to the left, unless the cursor points out the first character. If the cursor points out the first character and there is a line above the current line, move the cursor to the end-of-line of the next upper line. Otherwise, do nothing. * d If the cursor points out a character, delete the character (Characters and end-of-line next to the deleted character are shifted to the left). If the cursor points out the end-of-line and there is a line below, the next lower line is appended to the end-of-line of the current line (Lines below the current line are shifted to the upper). Otherwise, do nothing. * k If the cursor points out the end-of-line and there is a line below the current line, perform the command d mentioned above, and record a linefeed on the buffer. If the cursor does not point out the end-of-line, cut characters between the cursor (inclusive) and the end-of-line, and record them on the buffer. After this operation, the cursor indicates the end-of-line of the current line. * y If the buffer is empty, do nothing. If the buffer is holding a linefeed, insert the linefeed at the cursor. The cursor moves to the first character of the new line. If the buffer is holding characters, insert the characters at the cursor. The cursor moves to the character or end-of-line which is originally pointed by the cursor. The cursor position just after reading the text is the beginning of the first line, and the initial buffer is empty. Constraints * The number of lines in the text given as input ≤ 10 * The number of characters in a line given as input ≤ 20 * The number of commands ≤ 300 * The maximum possible number of lines in the text during operations ≤ 100 * The maximum possible number of characters in a line during operations ≤ 1000 Input The input consists of only one data-set which includes two parts. The first part gives a text consisting of several lines. The end of the text is indicated by a line (without quotes): "END_OF_TEXT" This line should not be included in the text. Next part gives a series of commands. Each command is given in a line. The end of the commands is indicated by a character '-'. Output For the input text, print the text edited by the commands. Example Input hyo ni END_OF_TEXT f d f f k p p e y a k y y n y - Output honihoni honi
instruction
0
87,448
6
174,896
"Correct Solution: ``` import sys class Cursor: BOL = (0,1) def __init__(self, text): assert isinstance(text, list) self.text = text for i in range(len(self.text)): self.text[i] = list(self.text[i]) self.buffer = "" self.line = 1 self.pos = self.BOL def _check(self): assert self.line > 0 def _get_pos_end_of_line(self): last_char = len(self.text[self.line-1]) return (last_char, last_char+1) def has_prev_line(self): return self.line > 1 def has_next_line(self): return self.line < len(self.text) def beginning_of_line(self): self.pos = self.BOL def end_of_line(self): self.pos = self._get_pos_end_of_line() def prev_line(self): if self.has_prev_line(): self.line -= 1 def next_line(self): if self.has_next_line(): self.line += 1 def right_pos(self): if self._get_pos_end_of_line() != self.pos: self.pos = (self.pos[0] + 1, self.pos[1] + 1) else: if self.has_next_line(): self.line += 1 self.pos = self.BOL def left_pos(self): if self.BOL != self.pos: self.pos = (self.pos[0] - 1, self.pos[1] - 1) else: if self.has_prev_line(): self.line -= 1 self.pos = self._get_pos_end_of_line() def remove_current_pos(self): if self._get_pos_end_of_line() != self.pos: self.text[self.line-1] = self.text[self.line-1][:self.pos[0]] + self.text[self.line-1][self.pos[1]:] else: if self.has_next_line(): self.text[self.line-1][self.pos[0]:self.pos[0]] = self.text[self.line] self.text.pop(self.line) def remove_to_end_of_line(self): if self._get_pos_end_of_line() == self.pos: if self.has_next_line(): self.remove_current_pos() self.buffer = '\n' else: self.buffer = self.text[self.line - 1][self.pos[0]:] self.text[self.line - 1] = self.text[self.line - 1][:self.pos[0]] self.pos = self._get_pos_end_of_line() def paste(self): if self.buffer: if self.buffer == '\n': prev = self.text[self.line - 1][:self.pos[0]] next = self.text[self.line - 1][self.pos[0]:] self.text[self.line - 1] = prev self.text.insert(self.line, next) self.line += 1 self.pos = self.BOL else: self.text[self.line - 1][self.pos[0]:self.pos[0]] = self.buffer self.pos = (self.pos[0] + len(self.buffer), self.pos[1] + len(self.buffer)) def print(self): for t in self.text: print("".join(t)) class Editor: def __init__(self, text): assert isinstance(text, list) self.cursor = Cursor(text) def process(self, commands): if not isinstance(commands, list): commands = [commands] for command in commands: self._process(command) self.cursor.print() def _process(self, command): if command == 'a': self.cursor.beginning_of_line() elif command == 'e': self.cursor.end_of_line() elif command == 'p': self.cursor.prev_line() self.cursor.beginning_of_line() elif command == 'n': self.cursor.next_line() self.cursor.beginning_of_line() elif command == 'f': self.cursor.right_pos() elif command == 'b': self.cursor.left_pos() elif command == 'd': self.cursor.remove_current_pos() elif command == 'k': self.cursor.remove_to_end_of_line() elif command == 'y': self.cursor.paste() def load_input(): inputs = [] while True: try: inputs.append(input()) except EOFError: return inputs def split_end_of_text(inputs): assert inputs assert 'END_OF_TEXT' in inputs for i in range(len(inputs)): if inputs[i] == 'END_OF_TEXT': return inputs[:i], inputs[i+1:] else: print("DO NOT DETECT END_OF_TEXT. got:", inputs) sys.exit(1) def main(): inputs = load_input() text, commands = split_end_of_text(inputs) # Attacking assert 'END_OF_TEXT' not in text assert 'END_OF_TEXT' not in commands editor = Editor(text) editor.process(commands) main() ```
output
1
87,448
6
174,897
Provide a correct Python 3 solution for this coding contest problem. Emacs is a text editor which is widely used by many programmers. The advantage of Emacs is that we can move a cursor without arrow keys and the mice. For example, the cursor can be moved right, left, down, and up by pushing f, b, n, p with the Control Key respectively. In addition, cut-and-paste can be performed without the mouse. Your task is to write a program which simulates key operations in the Emacs-like editor. The program should read a text and print the corresponding edited text. The text consists of several lines and each line consists of zero or more alphabets and space characters. A line, which does not have any character, is a blank line. The editor has a cursor which can point out a character or the end-of-line in the corresponding line. The cursor can also point out the end-of-line in a blank line. In addition, the editor has a buffer which can hold either a string (a sequence of characters) or a linefeed. The editor accepts the following set of commands (If the corresponding line is a blank line, the word "the first character" should be "the end-of-line"): * a Move the cursor to the first character of the current line. * e Move the cursor to the end-of-line of the current line. * p Move the cursor to the first character of the next upper line, if it exists. If there is no line above the current line, move the cursor to the first character of the current line. * n Move the cursor to the first character of the next lower line, if it exists. If there is no line below the current line, move the cursor to the first character of the current line. * f Move the cursor by one character to the right, unless the cursor points out the end-of-line. If the cursor points out the end-of-line and there is a line below the current line, move the cursor to the first character of the next lower line. Otherwise, do nothing. * b Move the cursor by one character to the left, unless the cursor points out the first character. If the cursor points out the first character and there is a line above the current line, move the cursor to the end-of-line of the next upper line. Otherwise, do nothing. * d If the cursor points out a character, delete the character (Characters and end-of-line next to the deleted character are shifted to the left). If the cursor points out the end-of-line and there is a line below, the next lower line is appended to the end-of-line of the current line (Lines below the current line are shifted to the upper). Otherwise, do nothing. * k If the cursor points out the end-of-line and there is a line below the current line, perform the command d mentioned above, and record a linefeed on the buffer. If the cursor does not point out the end-of-line, cut characters between the cursor (inclusive) and the end-of-line, and record them on the buffer. After this operation, the cursor indicates the end-of-line of the current line. * y If the buffer is empty, do nothing. If the buffer is holding a linefeed, insert the linefeed at the cursor. The cursor moves to the first character of the new line. If the buffer is holding characters, insert the characters at the cursor. The cursor moves to the character or end-of-line which is originally pointed by the cursor. The cursor position just after reading the text is the beginning of the first line, and the initial buffer is empty. Constraints * The number of lines in the text given as input ≤ 10 * The number of characters in a line given as input ≤ 20 * The number of commands ≤ 300 * The maximum possible number of lines in the text during operations ≤ 100 * The maximum possible number of characters in a line during operations ≤ 1000 Input The input consists of only one data-set which includes two parts. The first part gives a text consisting of several lines. The end of the text is indicated by a line (without quotes): "END_OF_TEXT" This line should not be included in the text. Next part gives a series of commands. Each command is given in a line. The end of the commands is indicated by a character '-'. Output For the input text, print the text edited by the commands. Example Input hyo ni END_OF_TEXT f d f f k p p e y a k y y n y - Output honihoni honi
instruction
0
87,449
6
174,898
"Correct Solution: ``` text = [] while True: s = input() if s == "END_OF_TEXT": break text.append(s) x, y = 0, 0 buff = "" while True: c = input() if c == "-": break elif c == "a": x = 0 elif c == "e": x = len(text[y]) elif c == "p": if y == 0: x = 0 else: x = 0 y -= 1 elif c == "n": if y == len(text) - 1: x = 0 else: y += 1 x = 0 elif c == "f": if x != len(text[y]): x += 1 elif y != len(text) - 1: y += 1 x = 0 elif c == "b": if x != 0: x -= 1 elif y != 0: y -= 1 x = len(text[y]) elif c =="d": if x < len(text[y]): text[y] = text[y][:x] + text[y][x + 1:] elif y != len(text) - 1: text[y] = text[y] + text[y + 1] text = text[:y + 1] + text[y + 2:] elif c == "k": if x < len(text[y]): buff = text[y][x:] text[y] = text[y][:x] elif y != len(text) - 1: text[y] = text[y] + text[y + 1] text = text[:y + 1] + text[y + 2:] buff = "\n" elif c =="y": if buff == "\n": new_row = text[y][x:] text[y] = text[y][:x] text = text[:y + 1] + [new_row] + text[y + 1:] x = 0 y += 1 else: text[y] = text[y][:x] + buff + text[y][x:] x += len(buff) print(*text, sep="\n") ```
output
1
87,449
6
174,899
Provide a correct Python 3 solution for this coding contest problem. Emacs is a text editor which is widely used by many programmers. The advantage of Emacs is that we can move a cursor without arrow keys and the mice. For example, the cursor can be moved right, left, down, and up by pushing f, b, n, p with the Control Key respectively. In addition, cut-and-paste can be performed without the mouse. Your task is to write a program which simulates key operations in the Emacs-like editor. The program should read a text and print the corresponding edited text. The text consists of several lines and each line consists of zero or more alphabets and space characters. A line, which does not have any character, is a blank line. The editor has a cursor which can point out a character or the end-of-line in the corresponding line. The cursor can also point out the end-of-line in a blank line. In addition, the editor has a buffer which can hold either a string (a sequence of characters) or a linefeed. The editor accepts the following set of commands (If the corresponding line is a blank line, the word "the first character" should be "the end-of-line"): * a Move the cursor to the first character of the current line. * e Move the cursor to the end-of-line of the current line. * p Move the cursor to the first character of the next upper line, if it exists. If there is no line above the current line, move the cursor to the first character of the current line. * n Move the cursor to the first character of the next lower line, if it exists. If there is no line below the current line, move the cursor to the first character of the current line. * f Move the cursor by one character to the right, unless the cursor points out the end-of-line. If the cursor points out the end-of-line and there is a line below the current line, move the cursor to the first character of the next lower line. Otherwise, do nothing. * b Move the cursor by one character to the left, unless the cursor points out the first character. If the cursor points out the first character and there is a line above the current line, move the cursor to the end-of-line of the next upper line. Otherwise, do nothing. * d If the cursor points out a character, delete the character (Characters and end-of-line next to the deleted character are shifted to the left). If the cursor points out the end-of-line and there is a line below, the next lower line is appended to the end-of-line of the current line (Lines below the current line are shifted to the upper). Otherwise, do nothing. * k If the cursor points out the end-of-line and there is a line below the current line, perform the command d mentioned above, and record a linefeed on the buffer. If the cursor does not point out the end-of-line, cut characters between the cursor (inclusive) and the end-of-line, and record them on the buffer. After this operation, the cursor indicates the end-of-line of the current line. * y If the buffer is empty, do nothing. If the buffer is holding a linefeed, insert the linefeed at the cursor. The cursor moves to the first character of the new line. If the buffer is holding characters, insert the characters at the cursor. The cursor moves to the character or end-of-line which is originally pointed by the cursor. The cursor position just after reading the text is the beginning of the first line, and the initial buffer is empty. Constraints * The number of lines in the text given as input ≤ 10 * The number of characters in a line given as input ≤ 20 * The number of commands ≤ 300 * The maximum possible number of lines in the text during operations ≤ 100 * The maximum possible number of characters in a line during operations ≤ 1000 Input The input consists of only one data-set which includes two parts. The first part gives a text consisting of several lines. The end of the text is indicated by a line (without quotes): "END_OF_TEXT" This line should not be included in the text. Next part gives a series of commands. Each command is given in a line. The end of the commands is indicated by a character '-'. Output For the input text, print the text edited by the commands. Example Input hyo ni END_OF_TEXT f d f f k p p e y a k y y n y - Output honihoni honi
instruction
0
87,450
6
174,900
"Correct Solution: ``` class Editer: def __init__(self, text): # カーソルの位置 self.row = 0 #行 self.col = 0 #列 # 編集中のテキスト self.text = [list(t) + ['\n'] for t in text] # バッファー self.buffer = [] def row_head(self): return 0 def row_tail(self): return len(self.text) - 1 def col_head(self): return 0 def col_tail(self): return len(self.text[self.row]) - 1 def __repr__(self): return ''.join(''.join(t) for t in self.text) def command_a(self): # カーソルを現在の行の先頭文字に移動 self.col = self.col_head() def command_e(self): # カーソルを現在の行の行末に移動 self.col = self.col_tail() def command_p(self): # 上に行があれば、カーソルを上の行に if self.row != self.row_head() : self.row -= 1 # カーソルを先頭に self.col = self.col_head() def command_n(self): # 下に行があれば if self.row != self.row_tail(): # カーソルを下の行に移動 self.row += 1 # カーソルを先頭文字に移動 self.col = self.col_head() def command_b(self): # カーソルが行末にない場合 if self.col != self.col_head(): # カーソルを1つ左に移動 self.col -= 1 # カーソルが行末にあり、上に行がある場合 elif self.row != self.row_head(): # カーソルを前の行の先頭に self.row -= 1 self.col = self.col_tail() def command_f(self): # カーソルが行末にない場合 if self.col != self.col_tail(): # カーソルを1つ右に移動 self.col += 1 # カーソルが行末にあり、下に行がある場合 elif self.row != self.row_tail(): # カーソルを次の行の先頭に self.row += 1 self.col = self.col_head() def command_d(self): # カーソルが行末にない場合 if self.col != self.col_tail(): # カーソルの文字を削除 self.text[self.row].pop(self.col) # カーソルが行末を指し、下に行がある場合 elif self.row != self.row_tail(): # 下の行をそのままカーソルの位置に繋げ、以下の行は上にシフト self.text[self.row].pop(self.col_tail()) self.text[self.row] += self.text.pop(self.row+1) def command_k(self): # カーソルが行末にない場合 if self.col != self.col_tail(): # カーソルが指す文字を含めた右側すべての文字を切り取りそれをバッファに記録する。 self.buffer = self.text[self.row][self.col:-1] self.text[self.row] = self.text[self.row][:self.col] + ['\n'] # カーソルは元の行の行末を指すようになる self.col = self.col_tail() # カーソルが行末にあり、下に行がある場合 elif self.row != self.row_tail(): # バッファに改行を記録する。 self.buffer = ['\n'] # 下の行をそのままカーソルの位置に繋げる。以下の行は上にシフトされる。 self.text[self.row].pop(self.col_tail()) self.text[self.row] += self.text.pop(self.row+1) def command_y(self): ''' カーソルが指す文字の直前にバッファを挿入 カーソルの位置はもともと指していた文字へ移動 バッファの内容が改行なら ''' if self.buffer != ['\n']: self.text[self.row][self.col:self.col] = self.buffer self.col += len(self.buffer) else: self.text.insert(self.row+1, self.text[self.row][self.col:]) self.text[self.row] = self.text[self.row][:self.col] + ['\n'] self.row += 1 self.col = self.col_head() def main(): # input text text = [] while True: str = input() if str == 'END_OF_TEXT': break text.append(str) editer = Editer(text) # input command while True: command = input() if command == 'a' : editer.command_a() elif command == 'e' : editer.command_e() elif command == 'p' : editer.command_p() elif command == 'n' : editer.command_n() elif command == 'f' : editer.command_f() elif command == 'b' : editer.command_b() elif command == 'd' : editer.command_d() elif command == 'y' : editer.command_y() elif command == 'k' : editer.command_k() elif command == '-' : break print(editer, end='') if __name__ == '__main__': main() ```
output
1
87,450
6
174,901
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sonya had a birthday recently. She was presented with the matrix of size n× m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right. Let's call a submatrix (i_1, j_1, i_2, j_2) (1≤ i_1≤ i_2≤ n; 1≤ j_1≤ j_2≤ m) elements a_{ij} of this matrix, such that i_1≤ i≤ i_2 and j_1≤ j≤ j_2. Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms. Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings abacaba, bcaacb, a are palindromes while strings abca, acbba, ab are not. Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix. Input The first line contains two integers n and m (1≤ n, m≤ 250) — the matrix dimensions. Each of the next n lines contains m lowercase Latin letters. Output Print one integer — the number of beautiful submatrixes. Examples Input 1 3 aba Output 4 Input 2 3 aca aac Output 11 Input 3 5 accac aaaba cccaa Output 43 Note In the first example, the following submatrixes are beautiful: ((1, 1), (1, 1)); ((1, 2), (1, 2)); ((1, 3), (1, 3)); ((1, 1), (1, 3)). In the second example, all submatrixes that consist of one element and the following are beautiful: ((1, 1), (2, 1)); ((1, 1), (1, 3)); ((2, 1), (2, 3)); ((1, 1), (2, 3)); ((2, 1), (2, 2)). Some of the beautiful submatrixes are: ((1, 1), (1, 5)); ((1, 2), (3, 4)); ((1, 1), (3, 5)). The submatrix ((1, 1), (3, 5)) is beautiful since it can be reordered as: accca aabaa accca In such a matrix every row and every column form palindromes. Submitted Solution: ``` #!/usr/bin/python # encoding:UTF-8 # Filename:Base.py import sys import random import copy from itertools import permutations, combinations from math import sqrt, fabs, ceil from collections import namedtuple # ------Util Const-------- in_file_path = "input.txt" output_file_path = "output.txt" SUBMIT = True def get_array(x, initial=None): dimension = len(x) if dimension == 1: return [copy.deepcopy(initial) for _ in range(x[0])] else: return [get_array(x[1:], initial) for _ in range(x[0])] def read_num(fin, num_type=int): tmp_list = [num_type(x) for x in fin.readline().strip().split()] if len(tmp_list) == 1: return tmp_list[0] else: return tuple(tmp_list) def manacher(s): # new_s = [s[0]] # for i in range(1, len(s)): # new_s.append('#') # new_s.append(s[i]) # print(new_s) ans_list = [] max_range = 0 max_center = 0 for i in range(0, len(s)): if max_range > i: p = min(ans_list[2 * max_center - i], max_range - i) else: p = 1 while i - p >= 0 and i + p < len(s) and s[i + p] == s[i - p]: p += 1 if i + p > max_range: max_center = i max_range = i + p ans_list.append(p) return ans_list # A # def solve(fin, fout): # n, k = read_num(fin) # print(ceil((n * 8.0) / k) + ceil((n * 2.0) / k) + ceil((n * 5.0) / k)) # B # def solve(fin): # n = read_num(fin) # for _ in range(0, n): # l, r = read_num(fin) # if (r - l + 1) % 2 == 0: # if l % 2 == 0: # print(int(-(r - l + 1) / 2)) # else: # print(int((r - l + 1) / 2)) # else: # if l % 2 == 0: # print(int(-(r - l) / 2 + r)) # else: # print(int((r - l) / 2 - r)) # C # def solve(fin): # def count_color(x, y, xx, yy): # # return _w(x, y, xx, yy), _b(x, y, xx, yy) # if x > xx or y > yy: # return 0, 0 # t = (xx - x + 1) * (yy - y + 1) # if t % 2 == 0: # return t // 2, t // 2 # else: # if (x + y) % 2 == 0: # return t - t // 2, t // 2 # else: # return t // 2, t - t // 2 # # T = read_num(fin) # for _ in range(0, T): # # print('Test: ',T) # n, m = read_num(fin) # x1, y1, x2, y2 = read_num(fin) # x3, y3, x4, y4 = read_num(fin) # w, _ = count_color(1, 1, n, m) # if (max(x1, x3) > min(x2, x4)) or (max(y1, y3) > min(y2, y4)): # tmp_w, tmp_b = count_color(x1, y1, x2, y2) # w += tmp_b # tmp_w, tmp_b = count_color(x3, y3, x4, y4) # w -= tmp_w # else: # tmp_w, tmp_b = count_color(x1, y1, x2, y2) # w += tmp_b # tmp_w, tmp_b = count_color(x3, y3, x4, y4) # w -= tmp_w # tmp_x_list = sorted([x1, x2, x3, x4]) # tmp_y_list = sorted([y1, y2, y3, y4]) # x5, x6 = tmp_x_list[1], tmp_x_list[2] # y5, y6 = tmp_y_list[1], tmp_y_list[2] # tmp_w, tmp_b = count_color(x5, y5, x6, y6) # w -= tmp_b # print(w, n * m - w) # D # def solve(fin): # T = read_num(fin) # for _ in range(0, T): # n, k = read_num(fin) # if n > 34 or k == 1: # print('YES', n - 1) # else: # f = [0] # for _ in range(0, n): # f.append(f[-1] * 4 + 1) # min_step = 1 # max_step = 1 + f[n - 1] # out_range = 3 # flag = True # for i in range(0, n): # if min_step <= k <= max_step: # print('YES', n - i - 1) # flag = False # break # max_step += out_range # min_step += out_range # out_range = out_range * 2 + 1 # if n - 2 - i >= 0: # max_step += (out_range - 2) * f[n - 2 - i] # if flag: # print('NO') # E def solve(fin): n, m = read_num(fin) mx = [] for line in fin: mx.append([ord(x) - ord('a') for x in line.strip()]) # print(mx[-1]) bit = [1] for i in range(1, 26): bit.append(bit[-1] * 251 % int(1e9 + 7)) ans = 0 for i in range(0, m): set_s = [0] * n count_s = get_array([n, 26], 0) count_odd = [0] * n for j in range(i, m): for k in range(0, n): p = mx[k][j] set_s[k] += bit[p] count_s[k][p] += 1 if count_s[k][p] & 1: count_odd[k] += 1 else: count_odd[k] -= 1 flag = False for i in range(1, len(set_s)): if set_s[i] != set_s[-1]: flag = True break if flag: new_s = [] for k in range(0, n): if count_odd[k] >= 2: new_s.append(-k-1) else: new_s.append(set_s[k]) if k + 1 < n: new_s.append(0) # print(new_s) ans_list = manacher(new_s) # print(i, j, new_s, ans_list) for k in range(0, len(ans_list)): if new_s[k] < 0: continue if k & 1: ans += ans_list[k] // 2 else: ans += int(ceil(ans_list[k] / 2.0)) else: # print(set_s) if count_odd[0] < 2 : ans += len(set_s) * (len(set_s) - 1) / 2 + len(set_s) print(ans) if __name__ == '__main__': if SUBMIT: solve(sys.stdin) else: solve(open(in_file_path, 'r')) ```
instruction
0
87,573
6
175,146
No
output
1
87,573
6
175,147
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sonya had a birthday recently. She was presented with the matrix of size n× m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right. Let's call a submatrix (i_1, j_1, i_2, j_2) (1≤ i_1≤ i_2≤ n; 1≤ j_1≤ j_2≤ m) elements a_{ij} of this matrix, such that i_1≤ i≤ i_2 and j_1≤ j≤ j_2. Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms. Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings abacaba, bcaacb, a are palindromes while strings abca, acbba, ab are not. Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix. Input The first line contains two integers n and m (1≤ n, m≤ 250) — the matrix dimensions. Each of the next n lines contains m lowercase Latin letters. Output Print one integer — the number of beautiful submatrixes. Examples Input 1 3 aba Output 4 Input 2 3 aca aac Output 11 Input 3 5 accac aaaba cccaa Output 43 Note In the first example, the following submatrixes are beautiful: ((1, 1), (1, 1)); ((1, 2), (1, 2)); ((1, 3), (1, 3)); ((1, 1), (1, 3)). In the second example, all submatrixes that consist of one element and the following are beautiful: ((1, 1), (2, 1)); ((1, 1), (1, 3)); ((2, 1), (2, 3)); ((1, 1), (2, 3)); ((2, 1), (2, 2)). Some of the beautiful submatrixes are: ((1, 1), (1, 5)); ((1, 2), (3, 4)); ((1, 1), (3, 5)). The submatrix ((1, 1), (3, 5)) is beautiful since it can be reordered as: accca aabaa accca In such a matrix every row and every column form palindromes. Submitted Solution: ``` #!/usr/bin/python # encoding:UTF-8 # Filename:Base.py import sys import random import copy from itertools import permutations, combinations from math import sqrt, fabs, ceil from collections import namedtuple # ------Util Const-------- in_file_path = "input.txt" output_file_path = "output.txt" SUBMIT = True def get_array(x, initial=None): dimension = len(x) if dimension == 1: return [copy.deepcopy(initial) for _ in range(x[0])] else: return [get_array(x[1:], initial) for _ in range(x[0])] def read_num(fin, num_type=int): tmp_list = [num_type(x) for x in fin.readline().strip().split()] if len(tmp_list) == 1: return tmp_list[0] else: return tuple(tmp_list) def manacher(s): ans_list = [] max_range = 0 max_center = 0 for i in range(0, len(s)): p = 1 if max_range > i: p = min(ans_list[2 * max_center - i], max_range - i) while i - p >= 0 and i + p < len(s) and s[i + p] == s[i - p]: p += 1 if i + p > max_range: max_center = i max_range = i + p ans_list.append(p) return ans_list # A # def solve(fin, fout): # n, k = read_num(fin) # print(ceil((n * 8.0) / k) + ceil((n * 2.0) / k) + ceil((n * 5.0) / k)) # B # def solve(fin): # n = read_num(fin) # for _ in range(0, n): # l, r = read_num(fin) # if (r - l + 1) % 2 == 0: # if l % 2 == 0: # print(int(-(r - l + 1) / 2)) # else: # print(int((r - l + 1) / 2)) # else: # if l % 2 == 0: # print(int(-(r - l) / 2 + r)) # else: # print(int((r - l) / 2 - r)) # C # def solve(fin): # def count_color(x, y, xx, yy): # # return _w(x, y, xx, yy), _b(x, y, xx, yy) # if x > xx or y > yy: # return 0, 0 # t = (xx - x + 1) * (yy - y + 1) # if t % 2 == 0: # return t // 2, t // 2 # else: # if (x + y) % 2 == 0: # return t - t // 2, t // 2 # else: # return t // 2, t - t // 2 # # T = read_num(fin) # for _ in range(0, T): # # print('Test: ',T) # n, m = read_num(fin) # x1, y1, x2, y2 = read_num(fin) # x3, y3, x4, y4 = read_num(fin) # w, _ = count_color(1, 1, n, m) # if (max(x1, x3) > min(x2, x4)) or (max(y1, y3) > min(y2, y4)): # tmp_w, tmp_b = count_color(x1, y1, x2, y2) # w += tmp_b # tmp_w, tmp_b = count_color(x3, y3, x4, y4) # w -= tmp_w # else: # tmp_w, tmp_b = count_color(x1, y1, x2, y2) # w += tmp_b # tmp_w, tmp_b = count_color(x3, y3, x4, y4) # w -= tmp_w # tmp_x_list = sorted([x1, x2, x3, x4]) # tmp_y_list = sorted([y1, y2, y3, y4]) # x5, x6 = tmp_x_list[1], tmp_x_list[2] # y5, y6 = tmp_y_list[1], tmp_y_list[2] # tmp_w, tmp_b = count_color(x5, y5, x6, y6) # w -= tmp_b # print(w, n * m - w) # D # def solve(fin): # T = read_num(fin) # for _ in range(0, T): # n, k = read_num(fin) # if n > 34 or k == 1: # print('YES', n - 1) # else: # f = [0] # for _ in range(0, n): # f.append(f[-1] * 4 + 1) # min_step = 1 # max_step = 1 + f[n - 1] # out_range = 3 # flag = True # for i in range(0, n): # if min_step <= k <= max_step: # print('YES', n - i - 1) # flag = False # break # max_step += out_range # min_step += out_range # out_range = out_range * 2 + 1 # if n - 2 - i >= 0: # max_step += (out_range - 2) * f[n - 2 - i] # if flag: # print('NO') # E def count_col(s, is_even): sum = 0 # print(s, is_even) for i in range(len(s)): min_s = s[i] for j in range(i, -1, -1): min_s = min(min_s, s[j]) if is_even: sum += int(ceil(min_s / 2.0)) else: sum += min_s // 2 # print(sum) return sum def solve(fin): n, m = read_num(fin) mx = [] for line in fin: mx.append([ord(x) - ord('a') for x in line.strip()]) # print(mx[-1]) dead_mask = -1 base = 251 bit = [1] for i in range(1, 26): bit.append(bit[-1] * 251) ans = 0 for i in range(0, m): set_s = [0] * n count_s = get_array([n, 26], 0) count_odd = [0] * n for j in range(i, m): for k in range(0, n): p = mx[k][j] set_s[k] += bit[p] count_s[k][p] += 1 if count_s[k][p] & 1: count_odd[k] += 1 else: count_odd[k] -= 1 new_s = [] for k in range(0, n): if count_odd[k] >= 2: new_s.append(-k-1) else: new_s.append(set_s[k]) if k + 1 != n: new_s.append(0) ans_list = manacher(new_s) # print(i, j, new_s, ans_list) for k in range(0, len(ans_list)): if new_s[int(ceil(k/2.0))] < 0: continue if k % 2 == 0: ans += int(ceil(ans_list[k] / 2.0)) else: ans += ans_list[k] // 2 print(ans) if __name__ == '__main__': if SUBMIT: solve(sys.stdin) else: solve(open(in_file_path, 'r')) ```
instruction
0
87,574
6
175,148
No
output
1
87,574
6
175,149
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sonya had a birthday recently. She was presented with the matrix of size n× m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right. Let's call a submatrix (i_1, j_1, i_2, j_2) (1≤ i_1≤ i_2≤ n; 1≤ j_1≤ j_2≤ m) elements a_{ij} of this matrix, such that i_1≤ i≤ i_2 and j_1≤ j≤ j_2. Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms. Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings abacaba, bcaacb, a are palindromes while strings abca, acbba, ab are not. Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix. Input The first line contains two integers n and m (1≤ n, m≤ 250) — the matrix dimensions. Each of the next n lines contains m lowercase Latin letters. Output Print one integer — the number of beautiful submatrixes. Examples Input 1 3 aba Output 4 Input 2 3 aca aac Output 11 Input 3 5 accac aaaba cccaa Output 43 Note In the first example, the following submatrixes are beautiful: ((1, 1), (1, 1)); ((1, 2), (1, 2)); ((1, 3), (1, 3)); ((1, 1), (1, 3)). In the second example, all submatrixes that consist of one element and the following are beautiful: ((1, 1), (2, 1)); ((1, 1), (1, 3)); ((2, 1), (2, 3)); ((1, 1), (2, 3)); ((2, 1), (2, 2)). Some of the beautiful submatrixes are: ((1, 1), (1, 5)); ((1, 2), (3, 4)); ((1, 1), (3, 5)). The submatrix ((1, 1), (3, 5)) is beautiful since it can be reordered as: accca aabaa accca In such a matrix every row and every column form palindromes. Submitted Solution: ``` # -*- coding:utf-8 -*- """ created by shuangquan.huang at 11/27/18 """ import collections N, M = map(int, input().split()) A = [] for i in range(N): A.append(list(input())) ans = 0 B = [[None for _ in range(M+1)] for _ in range(N)] for r in range(N): wc = collections.Counter() B[r][0] = wc.copy() for c in range(M): wc[A[r][c]] += 1 B[r][c+1] = wc.copy() for r in range(N): for c in range(M): for l in range(1, M-c+1): wc = B[r][c+l] - B[r][c] if sum([1 if x % 2 == 1 else 0 for x in wc.values()]) <= 1: print(r, c, l) ans += 1 for h in range(r+1, N): a = r b = h p = True while a < b: if B[a][c + l] - B[a][c] != B[b][c+l] - B[b][c]: p = False break a += 1 b -= 1 if p: ans += 1 print(ans) ```
instruction
0
87,575
6
175,150
No
output
1
87,575
6
175,151
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sonya had a birthday recently. She was presented with the matrix of size n× m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right. Let's call a submatrix (i_1, j_1, i_2, j_2) (1≤ i_1≤ i_2≤ n; 1≤ j_1≤ j_2≤ m) elements a_{ij} of this matrix, such that i_1≤ i≤ i_2 and j_1≤ j≤ j_2. Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms. Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings abacaba, bcaacb, a are palindromes while strings abca, acbba, ab are not. Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix. Input The first line contains two integers n and m (1≤ n, m≤ 250) — the matrix dimensions. Each of the next n lines contains m lowercase Latin letters. Output Print one integer — the number of beautiful submatrixes. Examples Input 1 3 aba Output 4 Input 2 3 aca aac Output 11 Input 3 5 accac aaaba cccaa Output 43 Note In the first example, the following submatrixes are beautiful: ((1, 1), (1, 1)); ((1, 2), (1, 2)); ((1, 3), (1, 3)); ((1, 1), (1, 3)). In the second example, all submatrixes that consist of one element and the following are beautiful: ((1, 1), (2, 1)); ((1, 1), (1, 3)); ((2, 1), (2, 3)); ((1, 1), (2, 3)); ((2, 1), (2, 2)). Some of the beautiful submatrixes are: ((1, 1), (1, 5)); ((1, 2), (3, 4)); ((1, 1), (3, 5)). The submatrix ((1, 1), (3, 5)) is beautiful since it can be reordered as: accca aabaa accca In such a matrix every row and every column form palindromes. Submitted Solution: ``` #!/usr/bin/python # encoding:UTF-8 # Filename:Base.py import sys import random import copy from itertools import permutations, combinations from math import sqrt, fabs, ceil from collections import namedtuple # ------Util Const-------- in_file_path = "input.txt" output_file_path = "output.txt" SUBMIT = True def get_array(x, initial=None): dimension = len(x) if dimension == 1: return [copy.deepcopy(initial) for _ in range(x[0])] else: return [get_array(x[1:], initial) for _ in range(x[0])] def read_num(fin, num_type=int): tmp_list = [num_type(x) for x in fin.readline().strip().split()] if len(tmp_list) == 1: return tmp_list[0] else: return tuple(tmp_list) def manacher(s): # new_s = [s[0]] # for i in range(1, len(s)): # new_s.append('#') # new_s.append(s[i]) # print(new_s) ans_list = [] max_range = 0 max_center = 0 for i in range(0, len(s)): if max_range > i: p = min(ans_list[2 * max_center - i], max_range - i) else: p = 1 while i - p >= 0 and i + p < len(s) and s[i + p] == s[i - p]: p += 1 if i + p > max_range: max_center = i max_range = i + p ans_list.append(p) return ans_list # A # def solve(fin, fout): # n, k = read_num(fin) # print(ceil((n * 8.0) / k) + ceil((n * 2.0) / k) + ceil((n * 5.0) / k)) # B # def solve(fin): # n = read_num(fin) # for _ in range(0, n): # l, r = read_num(fin) # if (r - l + 1) % 2 == 0: # if l % 2 == 0: # print(int(-(r - l + 1) / 2)) # else: # print(int((r - l + 1) / 2)) # else: # if l % 2 == 0: # print(int(-(r - l) / 2 + r)) # else: # print(int((r - l) / 2 - r)) # C # def solve(fin): # def count_color(x, y, xx, yy): # # return _w(x, y, xx, yy), _b(x, y, xx, yy) # if x > xx or y > yy: # return 0, 0 # t = (xx - x + 1) * (yy - y + 1) # if t % 2 == 0: # return t // 2, t // 2 # else: # if (x + y) % 2 == 0: # return t - t // 2, t // 2 # else: # return t // 2, t - t // 2 # # T = read_num(fin) # for _ in range(0, T): # # print('Test: ',T) # n, m = read_num(fin) # x1, y1, x2, y2 = read_num(fin) # x3, y3, x4, y4 = read_num(fin) # w, _ = count_color(1, 1, n, m) # if (max(x1, x3) > min(x2, x4)) or (max(y1, y3) > min(y2, y4)): # tmp_w, tmp_b = count_color(x1, y1, x2, y2) # w += tmp_b # tmp_w, tmp_b = count_color(x3, y3, x4, y4) # w -= tmp_w # else: # tmp_w, tmp_b = count_color(x1, y1, x2, y2) # w += tmp_b # tmp_w, tmp_b = count_color(x3, y3, x4, y4) # w -= tmp_w # tmp_x_list = sorted([x1, x2, x3, x4]) # tmp_y_list = sorted([y1, y2, y3, y4]) # x5, x6 = tmp_x_list[1], tmp_x_list[2] # y5, y6 = tmp_y_list[1], tmp_y_list[2] # tmp_w, tmp_b = count_color(x5, y5, x6, y6) # w -= tmp_b # print(w, n * m - w) # D # def solve(fin): # T = read_num(fin) # for _ in range(0, T): # n, k = read_num(fin) # if n > 34 or k == 1: # print('YES', n - 1) # else: # f = [0] # for _ in range(0, n): # f.append(f[-1] * 4 + 1) # min_step = 1 # max_step = 1 + f[n - 1] # out_range = 3 # flag = True # for i in range(0, n): # if min_step <= k <= max_step: # print('YES', n - i - 1) # flag = False # break # max_step += out_range # min_step += out_range # out_range = out_range * 2 + 1 # if n - 2 - i >= 0: # max_step += (out_range - 2) * f[n - 2 - i] # if flag: # print('NO') # E def solve(fin): n, m = read_num(fin) mx = [] for line in fin: mx.append([ord(x) - ord('a') for x in line.strip()]) # print(mx[-1]) bit = [1] for i in range(1, 26): bit.append(bit[-1] * 251 % int(1e9 + 7)) ans = 0 for i in range(0, m): set_s = [0] * n count_s = get_array([n, 26], 0) count_odd = [0] * n for j in range(i, m): for k in range(0, n): p = mx[k][j] set_s[k] += bit[p] count_s[k][p] += 1 if count_s[k][p] & 1: count_odd[k] += 1 else: count_odd[k] -= 1 flag = False for i in range(1, len(set_s)): if set_s[i] != set_s[-1]: flag = True break if flag: new_s = [] for k in range(0, n): if count_odd[k] >= 2: new_s.append(-k-1) else: new_s.append(set_s[k]) if k + 1 < n: new_s.append(0) # print(new_s) ans_list = manacher(new_s) # print(i, j, new_s, ans_list) for k in range(0, len(ans_list)): if new_s[k] < 0: continue if k & 1: ans += ans_list[k] // 2 else: ans += int(ceil(ans_list[k] / 2.0)) else: ans += len(set_s) * (len(set_s) - 1) / 2 print(ans) if __name__ == '__main__': if SUBMIT: solve(sys.stdin) else: solve(open(in_file_path, 'r')) ```
instruction
0
87,576
6
175,152
No
output
1
87,576
6
175,153
Provide tags and a correct Python 3 solution for this coding contest problem. After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique. For a given sentence, the cipher is processed as: 1. Convert all letters of the sentence to lowercase. 2. Reverse each of the words of the sentence individually. 3. Remove all the spaces in the sentence. For example, when this cipher is applied to the sentence Kira is childish and he hates losing the resulting string is ariksihsidlihcdnaehsetahgnisol Now Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times. Input The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t. The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000. Output Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those. Examples Input 30 ariksihsidlihcdnaehsetahgnisol 10 Kira hates is he losing death childish L and Note Output Kira is childish and he hates losing Input 12 iherehtolleh 5 HI Ho there HeLLo hello Output HI there HeLLo Note In sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.
instruction
0
87,991
6
175,982
Tags: data structures, dp, hashing, implementation, sortings, string suffix structures, strings Correct Solution: ``` #!/usr/bin/env python3 # http://codeforces.com/contest/633/problem/C from collections import deque # import sys # sys.setrecursionlimit(10001) n = int(input()) s = input() m = int(input()) words = [] for i in range(0, m): words.append(input()) dict_words = {} for word in words: dict_words[word.lower()[::-1]] = word trie_words = {} for word in dict_words.keys(): d = trie_words for letter in word: d = d.setdefault(letter, {}) d['word'] = word def find_sentence(s): # stack = [0, '', dict_words, []] # position, used words so far, pos in trie we stopped on, children roots = deque() # position, used words so far, pos in trie we stopped on, children d = trie_words for i in range(0, len(s)): if not s[i] in d: break; d = d[s[i]] if 'word' in d: word = d['word'] new_root = [i + 1, word, None] roots.append(new_root) if i + 1 == len(s): return new_root while len(roots) > 0: root = roots.popleft() d = trie_words for i in range(root[0], len(s)): if not s[i] in d: break; d = d[s[i]] if 'word' in d: word = d['word'] new_root = [i + 1, word, root] roots.appendleft(new_root) if i + 1 == len(s): return new_root result = find_sentence(s) words = [] while not result is None: word = result[1] words.append(dict_words[word]) result = result[2] print(' '.join(reversed(words))) ```
output
1
87,991
6
175,983
Provide tags and a correct Python 3 solution for this coding contest problem. After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique. For a given sentence, the cipher is processed as: 1. Convert all letters of the sentence to lowercase. 2. Reverse each of the words of the sentence individually. 3. Remove all the spaces in the sentence. For example, when this cipher is applied to the sentence Kira is childish and he hates losing the resulting string is ariksihsidlihcdnaehsetahgnisol Now Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times. Input The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t. The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000. Output Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those. Examples Input 30 ariksihsidlihcdnaehsetahgnisol 10 Kira hates is he losing death childish L and Note Output Kira is childish and he hates losing Input 12 iherehtolleh 5 HI Ho there HeLLo hello Output HI there HeLLo Note In sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.
instruction
0
87,992
6
175,984
Tags: data structures, dp, hashing, implementation, sortings, string suffix structures, strings Correct Solution: ``` def main(): stop, s, words, stack = int(input()), input()[::-1], {}, [] for _ in range(int(input())): w = input() words[w.lower()] = w lel = tuple(sorted(set(map(len, words.keys())), reverse=True)) push, pop = stack.append, stack.pop it = iter(lel) while True: try: le = next(it) start = stop - le if start >= 0: v = s[start:stop] if v in words: push((v, it, stop)) stop = start if not stop: print(' '.join(words[w] for w, _, _ in stack)) return it = iter(lel) except StopIteration: _, it, stop = pop() if __name__ == '__main__': main() # Made By Mostafa_Khaled ```
output
1
87,992
6
175,985
Provide tags and a correct Python 3 solution for this coding contest problem. After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique. For a given sentence, the cipher is processed as: 1. Convert all letters of the sentence to lowercase. 2. Reverse each of the words of the sentence individually. 3. Remove all the spaces in the sentence. For example, when this cipher is applied to the sentence Kira is childish and he hates losing the resulting string is ariksihsidlihcdnaehsetahgnisol Now Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times. Input The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t. The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000. Output Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those. Examples Input 30 ariksihsidlihcdnaehsetahgnisol 10 Kira hates is he losing death childish L and Note Output Kira is childish and he hates losing Input 12 iherehtolleh 5 HI Ho there HeLLo hello Output HI there HeLLo Note In sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.
instruction
0
87,993
6
175,986
Tags: data structures, dp, hashing, implementation, sortings, string suffix structures, strings Correct Solution: ``` def main(): stop, s, words, stack = int(input()), input()[::-1], {}, [] for _ in range(int(input())): w = input() words[w.lower()] = w lel = tuple(sorted(set(map(len, words.keys())), reverse=True)) push, pop = stack.append, stack.pop it = iter(lel) while True: try: le = next(it) start = stop - le if start >= 0: v = s[start:stop] if v in words: push((v, it, stop)) stop = start if not stop: print(' '.join(words[w] for w, _, _ in stack)) return it = iter(lel) except StopIteration: _, it, stop = pop() if __name__ == '__main__': main() ```
output
1
87,993
6
175,987
Provide tags and a correct Python 3 solution for this coding contest problem. After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique. For a given sentence, the cipher is processed as: 1. Convert all letters of the sentence to lowercase. 2. Reverse each of the words of the sentence individually. 3. Remove all the spaces in the sentence. For example, when this cipher is applied to the sentence Kira is childish and he hates losing the resulting string is ariksihsidlihcdnaehsetahgnisol Now Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times. Input The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t. The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000. Output Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those. Examples Input 30 ariksihsidlihcdnaehsetahgnisol 10 Kira hates is he losing death childish L and Note Output Kira is childish and he hates losing Input 12 iherehtolleh 5 HI Ho there HeLLo hello Output HI there HeLLo Note In sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.
instruction
0
87,994
6
175,988
Tags: data structures, dp, hashing, implementation, sortings, string suffix structures, strings Correct Solution: ``` # [https://codeforces.com/contest/633/submission/33363209] n = int(input()) t = input()[::-1] m = int(input()) d = {q.lower(): q for q in [input() for i in range(m)]} k = 0 s = [] l = sorted(set(map(len, d))) while n: k -= 1 if len(l) + k < 0: k, n = s.pop() elif n >= l[k] and t[n - l[k]:n] in d: s.append((k, n)) n -= l[k] k = 0 print(*[d[t[n - l[i]:n]] for i, n in s]) ```
output
1
87,994
6
175,989
Provide tags and a correct Python 3 solution for this coding contest problem. After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique. For a given sentence, the cipher is processed as: 1. Convert all letters of the sentence to lowercase. 2. Reverse each of the words of the sentence individually. 3. Remove all the spaces in the sentence. For example, when this cipher is applied to the sentence Kira is childish and he hates losing the resulting string is ariksihsidlihcdnaehsetahgnisol Now Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times. Input The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t. The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000. Output Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those. Examples Input 30 ariksihsidlihcdnaehsetahgnisol 10 Kira hates is he losing death childish L and Note Output Kira is childish and he hates losing Input 12 iherehtolleh 5 HI Ho there HeLLo hello Output HI there HeLLo Note In sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.
instruction
0
87,995
6
175,990
Tags: data structures, dp, hashing, implementation, sortings, string suffix structures, strings Correct Solution: ``` import sys p = sys.stdin.read().split() n, t = int(p[0]), p[1][::-1] d = {q.lower(): q for q in p[3:]} k, s = 0, [] l = sorted(set(map(len, d))) while n: k -= 1 if len(l) + k < 0: k, n = s.pop() elif n >= l[k] and t[n - l[k]:n] in d: s.append((k, n)) n -= l[k] k = 0 print(*[d[t[n - l[i]:n]] for i, n in s]) ```
output
1
87,995
6
175,991
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a
instruction
0
88,035
6
176,070
Tags: implementation Correct Solution: ``` string = input() stack = [len(string)] for letter in string: if letter == stack[-1]: stack.pop() else: stack.append(letter) print(''.join(stack[1:])) ```
output
1
88,035
6
176,071
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a
instruction
0
88,036
6
176,072
Tags: implementation Correct Solution: ``` ##############--->>>>> Deepcoder Amit Kumar Bhuyan <<<<<---############## """ Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away. """ from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def msi(): return map(str,input().strip().split(" ")) def li(): return list(mi()) def dmain(): sys.setrecursionlimit(1000000) threading.stack_size(1024000) thread = threading.Thread(target=main) thread.start() #from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace #from math import log,sqrt,factorial,cos,tan,sin,radians #from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right #from decimal import * #import threading #from itertools import permutations #Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy import sys input = sys.stdin.readline scanner = lambda: int(input()) string = lambda: input().rstrip() get_list = lambda: list(read()) read = lambda: map(int, input().split()) get_float = lambda: map(float, input().split()) # from bisect import bisect_left as lower_bound; # from bisect import bisect_right as upper_bound; # from math import ceil, factorial; def ceil(x): if x != int(x): x = int(x) + 1 return x def factorial(x, m): val = 1 while x>0: val = (val * x) % m x -= 1 return val def fact(x): val = 1 while x > 0: val *= x x -= 1 return val # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; ## gcd function def gcd(a,b): if b == 0: return a; return gcd(b, a % b); ## lcm function def lcm(a, b): return (a * b) // math.gcd(a, b) def is_integer(n): return math.ceil(n) == math.floor(n) ## nCr function efficient using Binomial Cofficient def nCr(n, k): if k > n: return 0 if(k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## upper bound function code -- such that e in a[:i] e < x; ## prime factorization def primefs(n): ## if n == 1 ## calculating primes primes = {} while(n%2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n//2 for i in range(3, int(n**0.5)+2, 2): while(n%i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n//i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## DISJOINT SET UNINON FUNCTIONS def swap(a,b): temp = a a = b b = temp return a,b; # find function with path compression included (recursive) # def find(x, link): # if link[x] == x: # return x # link[x] = find(link[x], link); # return link[x]; # find function with path compression (ITERATIVE) def find(x, link): p = x; while( p != link[p]): p = link[p]; while( x != p): nex = link[x]; link[x] = p; x = nex; return p; # the union function which makes union(x,y) # of two nodes x and y def union(x, y, link, size): x = find(x, link) y = find(y, link) if size[x] < size[y]: x,y = swap(x,y) if x != y: size[x] += size[y] link[y] = x ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n+1)] prime[0], prime[1] = False, False p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime # Euler's Toitent Function phi def phi(n) : result = n p = 2 while(p * p<= n) : if (n % p == 0) : while (n % p == 0) : n = n // p result = result * (1.0 - (1.0 / (float) (p))) p = p + 1 if (n > 1) : result = result * (1.0 - (1.0 / (float)(n))) return (int)(result) def is_prime(n): if n == 0: return False if n == 1: return True for i in range(2, int(n ** (1 / 2)) + 1): if not n % i: return False return True def next_prime(n, primes): while primes[n] != True: n += 1 return n #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e5 + 5) def spf_sieve(): spf[1] = 1; for i in range(2, MAXN): spf[i] = i; for i in range(4, MAXN, 2): spf[i] = 2; for i in range(3, ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i*i, MAXN, i): if spf[j] == j: spf[j] = i; ## function for storing smallest prime factors (spf) in the array ################## un-comment below 2 lines when using factorization ################# spf = [0 for i in range(MAXN)] # spf_sieve(); def factoriazation(x): res = [] for i in range(2, int(x ** 0.5) + 1): while x % i == 0: res.append(i) x //= i if x != 1: res.append(x) return res ## this function is useful for multiple queries only, o/w use ## primefs function above. complexity O(log n) def factors(n): res = [] for i in range(1, int(n ** 0.5) + 1): if n % i == 0: res.append(i) res.append(n // i) return list(set(res)) ## taking integer array input def int_array(): return list(map(int, input().strip().split())); def float_array(): return list(map(float, input().strip().split())); ## taking string array input def str_array(): return input().strip().split(); def binary_search(low, high, w, h, n): while low < high: mid = low + (high - low) // 2 # print(low, mid, high) if check(mid, w, h, n): low = mid + 1 else: high = mid return low ## for checking any conditions def check(beauty, s, n, count): pass #defining a couple constants MOD = int(1e9)+7; CMOD = 998244353; INF = float('inf'); NINF = -float('inf'); alphs = "abcdefghijklmnopqrstuvwxyz" ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### from itertools import permutations import math import bisect as bis import random import sys import collections as collect # import numpy as np def solve(): s = string() ans = [] for i in s: if ans and i == ans[-1]: ans.pop() else: ans += [i] print("".join(ans)) # region fastio # template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": #read() # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") for i in range(1): solve() #dmain() # Comment Read() # fin_time = datetime.now() # print("Execution time (for loop): ", (fin_time-init_time)) ```
output
1
88,036
6
176,073
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a
instruction
0
88,037
6
176,074
Tags: implementation Correct Solution: ``` s = input() stack = [] for char in s: # print("Comparing", char, "&", stack) if len(stack)==0: stack.append(char) else: if(char == stack[-1]): stack.pop() else: stack.append(char) print("".join(stack)) ```
output
1
88,037
6
176,075
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a
instruction
0
88,038
6
176,076
Tags: implementation Correct Solution: ``` s = [] for i in input(): if s and s[-1] == i: s.pop() else: s.append(i) print("".join(s)) ```
output
1
88,038
6
176,077
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a
instruction
0
88,039
6
176,078
Tags: implementation Correct Solution: ``` s = input() l = [""]*200000 li = 0 for c in s: li += 1 if len(l) > 0 and l[li-1] == c: l[li-1] = "" li -= 2 else: l[li] = c print(*l[:li+1], sep="") ```
output
1
88,039
6
176,079
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a
instruction
0
88,040
6
176,080
Tags: implementation Correct Solution: ``` p=list(input()) a=[ ] #Creacion d euna lista vacia a.append(p[0]) #incluir el primer elemnto de p a la lista a m=len(p) #tamaño de p i=1 while i<m: if (len(a)==0): a.append(p[i]) else: if(a[-1]==p[i]): a.pop() else: a.append(p[i]) i=i+1 #Convertir listas a strings print(''.join(a)) ```
output
1
88,040
6
176,081
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a
instruction
0
88,041
6
176,082
Tags: implementation Correct Solution: ``` s=input() ans=[s[0]] for i in range(1,len(s)): if len(ans) and ans[-1]==s[i]: ans.pop() else: ans.append(s[i]) print("".join(ans)) ```
output
1
88,041
6
176,083
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a
instruction
0
88,042
6
176,084
Tags: implementation Correct Solution: ``` string = input() def plugInX(string): stringNew = [] for i in string: if i not in stringNew: stringNew.append(i) elif i == stringNew[-1]: stringNew.pop() else: stringNew.append(i) if len(stringNew) > 0: for i in stringNew: print(i, end="") else: print("") plugInX(string) ```
output
1
88,042
6
176,085
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a Submitted Solution: ``` s = input() l = [] for c in s: if len(l) > 0 and l[-1] == c: del l[-1] else: l += [c] print(*l, sep="") ```
instruction
0
88,045
6
176,090
Yes
output
1
88,045
6
176,091
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a Submitted Solution: ``` import sys from collections import OrderedDict f = sys.stdin #f = open("input.txt", "r") a = f.readline().strip() a1 = list(OrderedDict.fromkeys(a)) ans = "" for i in a1: if a.count(i)<=1: ans += i print(ans) ```
instruction
0
88,047
6
176,094
No
output
1
88,047
6
176,095
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a Submitted Solution: ``` letters = input() lettersList = [] newList = [] for y in letters: lettersList.append(y) for x in lettersList: if x not in newList: newList.append(x) elif x in newList: #index = newList.index(x) lettersList.pop() print(''.join(lettersList)) ```
instruction
0
88,050
6
176,100
No
output
1
88,050
6
176,101
Provide tags and a correct Python 3 solution for this coding contest problem. Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen. The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac. Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations. Input The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000). After that, there are two strings s and t, consisting of n lowercase Latin letters each. Output If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1. Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied. Examples Input 6 abacbb babcba Output 4 6 3 2 3 Input 3 aba bba Output -1
instruction
0
88,099
6
176,198
Tags: constructive algorithms, implementation, strings Correct Solution: ``` n, s, t = int(input()), input(), input() #print n, s, t if sorted(s)!=sorted(t): print(-1) else: ans = [] def shift(k, cur): if k == 0: return cur return cur[:-k-1:-1] + cur [:-k] def DO_SWAP(x): ans.append(x) return shift(x, s) #[begin:end:step] for i in range(n): curr = t[i] j = -1 for k in range(n-i): if s[k] == curr: j = k break s = DO_SWAP(n-j-1) s = DO_SWAP(1) s = DO_SWAP(n-1) assert s == t print (len(ans)) for x in ans: print(x, end = " ") #print(*args, sep=' ', end='\n', file=None) ```
output
1
88,099
6
176,199
Provide tags and a correct Python 3 solution for this coding contest problem. Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen. The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac. Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations. Input The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000). After that, there are two strings s and t, consisting of n lowercase Latin letters each. Output If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1. Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied. Examples Input 6 abacbb babcba Output 4 6 3 2 3 Input 3 aba bba Output -1
instruction
0
88,100
6
176,200
Tags: constructive algorithms, implementation, strings Correct Solution: ``` def reverse(s,k): if not k: return s return s[-1:-k-1:-1]+s[:-k] n=int(input()) s=input() t=input() cnt=[0]*26 for i in s: cnt[ord(i)-ord('a')]+=1 for i in t: cnt[ord(i)-ord('a')]-=1 for i in cnt: if i!=0: print(-1) exit(0) print(n*3) for i in t: mark=s.find(i) # print(i,s,mark) print(n-(mark+1),end=" ") print(1,end=" ") print(n,end=" ") s=reverse(s,n-(mark+1)) s=reverse(s,1) s=reverse(s,n) # print(s) ```
output
1
88,100
6
176,201
Provide tags and a correct Python 3 solution for this coding contest problem. Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen. The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac. Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations. Input The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000). After that, there are two strings s and t, consisting of n lowercase Latin letters each. Output If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1. Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied. Examples Input 6 abacbb babcba Output 4 6 3 2 3 Input 3 aba bba Output -1
instruction
0
88,101
6
176,202
Tags: constructive algorithms, implementation, strings Correct Solution: ``` import math import sys input = sys.stdin.readline result = [] def move(s, x): result.append(x) # print(s[-1:-1-x:-1] + s[:len(s) - x]) return s[-1:-1-x:-1] + s[:len(s) - x] def getFirst(s, need, size): piv = -1 for i in range(size, len(s)): if s[i] == need: piv = i break if piv == -1: print(-1) exit(0) s = move(s, len(s) - piv) s = move(s, piv - size) s = move(s, size + 1) return s n = int(input()) s = input().strip() t = input().strip() l, r = len(s) // 2, len(s) // 2 s = getFirst(s, t[l], 0) size = 1 while size < len(s): if size % 2 == 1: l = l - 1 s = getFirst(s, t[l], size) else: r = r + 1 s = getFirst(s, t[r], size) size = size + 1 # print(s) if s != t: s = move(s, len(s)) # print(s) print(len(result)) print(' '.join(map(str, result))) ```
output
1
88,101
6
176,203
Provide tags and a correct Python 3 solution for this coding contest problem. Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen. The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac. Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations. Input The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000). After that, there are two strings s and t, consisting of n lowercase Latin letters each. Output If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1. Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied. Examples Input 6 abacbb babcba Output 4 6 3 2 3 Input 3 aba bba Output -1
instruction
0
88,102
6
176,204
Tags: constructive algorithms, implementation, strings Correct Solution: ``` n = int(input()) s = input() t = input() if sorted(s) != sorted(t): print(-1) else: res = [] for i in range(n): k = 0; while(s[k] != t[i]): k += 1 res += [n-k-1, 1, n] s = "".join(reversed(s[:k])) + s[k+1:] + s[k] #print(s) print(len(res)) print(*res) ```
output
1
88,102
6
176,205