message
stringlengths
2
23.4k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
129
108k
cluster
float64
6
6
__index_level_0__
int64
258
216k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair. Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa". Input The first line contains a non-empty string s, consisting of lowercase Latin letters — that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≤ k ≤ 13) — the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair. Output Print the single number — the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters. Examples Input ababa 1 ab Output 2 Input codeforces 2 do cs Output 1 Note In the first sample you should remove two letters b. In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. Submitted Solution: ``` a=input() n=len(a) k=int(input()) b=[input() for i in range(k)] c=[] d=0 for i in range(1,n): if a[i]!=a[i-1]: c.append(i-d) d=i c.append(n-d) i=0 j=0 e=0 while j<n-1: if a[j]+a[j+1] in b or a[j+1]+a[j] in b: e+=min(c[i],c[i+1]) i+=1 j+=c[i] j+=1 print(e) ```
instruction
0
71,008
6
142,016
No
output
1
71,008
6
142,017
Provide tags and a correct Python 3 solution for this coding contest problem. Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where * <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. * <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. * <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent. There are the samples of correct Jabber IDs: mike@codeforces.com, 007@en.codeforces.com/contest. Your task is to write program which checks if given string is a correct Jabber ID. Input The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive. Output Print YES or NO. Examples Input mike@codeforces.com Output YES Input john.smith@codeforces.ru/contest.icpc/12 Output NO
instruction
0
71,025
6
142,050
Tags: implementation, strings Correct Solution: ``` #In the name of GOD! def chk(s): if len(s) == 0 or len(s) > 16: return 1 for i in s: if not(('a' <= i and i <= 'z') or ('A' <= i and i <= 'Z') or ('0' <= i and i <= '9') or i == '_'): return 1 return 0 s = input() c = '' x = 0 b = 0 for i in s: x += 1 if i == '@': b += chk(c) c = '' break c += i d = 1 y = 0 for j in range(x, len(s)): d = 0 i = s[j] x += 1 if y > 32: b += 1 if i == '.': b += chk(c) c = '' elif i == '/': b += chk(c) c = '' break else: c += i y += 1 if len(c) > 0: b += chk(c) for j in range(x, len(s)): i = s[j] if i == '/': b += chk(c) c = '' else: c += i if s[-1] == '/' or s[-1] == '.': b += 1 if b + d > 0: print("NO") else: print("YES") ```
output
1
71,025
6
142,051
Provide tags and a correct Python 3 solution for this coding contest problem. Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where * <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. * <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. * <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent. There are the samples of correct Jabber IDs: mike@codeforces.com, 007@en.codeforces.com/contest. Your task is to write program which checks if given string is a correct Jabber ID. Input The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive. Output Print YES or NO. Examples Input mike@codeforces.com Output YES Input john.smith@codeforces.ru/contest.icpc/12 Output NO
instruction
0
71,026
6
142,052
Tags: implementation, strings Correct Solution: ``` try: result = True jabber_id = input().lower().replace("/n", "") username = jabber_id.split("@", 1)[0] hostname = jabber_id.split("@", 1)[1].split("/")[0] try: resource = jabber_id.split("@", 1)[1].split("/", 1)[1] if not resource: result = False except: resource = "" usp = 'abcdefghijklmnopqrstuvwxyz_1234567890' uhp = 'abcdefghijklmnopqrstuvwxyz_1234567890.' for c in username: if not c in usp: #print("1") result = False for c in hostname: if not c in uhp: #print("2") result = False for c in resource: if not c in usp: #print("3") result = False if not( len(username)<=16 and len(username)>0): #print("4") result = False if not( len(hostname)<=32 and len(hostname)>0): #print("5") result = False if not len(resource)<=16: #print("6") result = False #print(hostname.split(".")) for h in hostname.split("."): if len(h)==0: #print("7") result = False if resource: for h in resource.split("/"): if len(h)==0: #print("8") result = False if result: print("YES") else: print("NO") except: print("NO") #print(username, " ", hostname, " ", resource) ```
output
1
71,026
6
142,053
Provide tags and a correct Python 3 solution for this coding contest problem. Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where * <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. * <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. * <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent. There are the samples of correct Jabber IDs: mike@codeforces.com, 007@en.codeforces.com/contest. Your task is to write program which checks if given string is a correct Jabber ID. Input The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive. Output Print YES or NO. Examples Input mike@codeforces.com Output YES Input john.smith@codeforces.ru/contest.icpc/12 Output NO
instruction
0
71,027
6
142,054
Tags: implementation, strings Correct Solution: ``` def check(txt: str) -> bool: ln = len(txt) if ln == 0 or ln > 16: return False for item in txt: if not ('a' <= item <= 'z' or 'A' <= item <= 'Z' or '0' <= item <= '9' or item == '_'): return False return True def checkHost(hostName: str) -> bool: hostLen = len(hostName) if hostLen == 0 or hostLen > 32: return False for token in hostName.split('.'): if not check(token): return False return True mail = input() isUser, isHost, isRes = False, False, False if '@' in mail: atIndex = mail.index('@') slashInd = mail.index('/') if '/' in mail else -1 userName = mail[:atIndex] isUser = check(userName) hostName = mail[atIndex + 1: slashInd] if slashInd != -1 else mail[atIndex + 1:] isHost = checkHost(hostName) if slashInd == -1: isRes = True else: resource = mail[slashInd+1:] isRes = check(resource) ''' if isUser and isHost and isRes: print('YES') else: print('NO') ''' print('YES' if isUser and isHost and isRes else 'NO') ```
output
1
71,027
6
142,055
Provide tags and a correct Python 3 solution for this coding contest problem. Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where * <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. * <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. * <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent. There are the samples of correct Jabber IDs: mike@codeforces.com, 007@en.codeforces.com/contest. Your task is to write program which checks if given string is a correct Jabber ID. Input The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive. Output Print YES or NO. Examples Input mike@codeforces.com Output YES Input john.smith@codeforces.ru/contest.icpc/12 Output NO
instruction
0
71,028
6
142,056
Tags: implementation, strings Correct Solution: ``` string = input() answer = "YES" Ausername = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz0123456789" if "@" in string: string = string.split("@") if len(string) > 2: answer = "NO" if len(string[0]) < 1 or len(string[0]) > 16: answer = "NO" for char in string[0]: if char not in Ausername: answer = "NO" if "/" in string[1]: string2 = string[1].split("/") hostname = string2[0] if len(string2) > 2: answer = "NO" for char in string2[1]: if char not in Ausername: answer = "NO" if len(string2[1]) < 1 or len(string2[1]) > 16: answer = "NO" else: hostname = string[1] if len(hostname) < 1 or len(hostname) > 32: answer = "NO" if "." in hostname: hostname = hostname.split(".") for word in hostname: if len(word) < 1 or len(word) > 16: answer = "NO" for char in word: if char not in Ausername: answer = "NO" else: for char in hostname: if char not in Ausername: answer = "NO" else: answer = "NO" print(answer) ```
output
1
71,028
6
142,057
Provide tags and a correct Python 3 solution for this coding contest problem. Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where * <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. * <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. * <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent. There are the samples of correct Jabber IDs: mike@codeforces.com, 007@en.codeforces.com/contest. Your task is to write program which checks if given string is a correct Jabber ID. Input The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive. Output Print YES or NO. Examples Input mike@codeforces.com Output YES Input john.smith@codeforces.ru/contest.icpc/12 Output NO
instruction
0
71,029
6
142,058
Tags: implementation, strings Correct Solution: ``` ''' def userName(s): for i in range(s.index('@')): if not '0' <= s[i] <= '9' or 'a' <= s[i] <= 'z' or 'A' <= s[i] <= 'Z': return False else: return True def hostName(s): if '/' in s: for i in range(s.index('@') + 1, s.index('/')): if not '0' <= s[i] <= '9' or 'a' <= s[i] <= 'z' or 'A' <= s[i] <= 'Z' or s[i] == '.': return False else: return True else: for i in range(s.index('@', )): if not '0' <= s[i] <= '9' or 'a' <= s[i] <= 'z' or 'A' <= s[i] <= 'Z' or s[i] == '.': return False else: return True def resourse(s): for i in range(s.index('/'), s.rindex('/')): if not '0' <= s[i] <= '9' or 'a' <= s[i] <= 'z' or 'A' <= s[i] <= 'Z' or s[i] == '.': return False else: return True s = input() ''' ''' 0123456789....... s='something@ipsu.edu.tetu.ge/pageone' userName='something' ''' def check(s): sLen = len(s) if sLen == 0 or sLen > 16: return False for i in range(sLen): if not ('A' <= s[i] <= 'Z' or 'a' <= s[i] <= 'z' or '0' <= s[i] <= '9' or s[i] == '_'): return False return True def checkHost(hostName): hostLen = len(hostName) if hostLen == 0 or hostLen > 32: return False for item in hostName.split('.'): if not check(item): return False return True s = input() isUser, isHost, isResource = False, False, False if '@' in s: atIndex = s.index('@') userName = s[0:atIndex] isUser = check(userName) slashIndex = s.index('/') if '/' in s else -1 hostName = s[atIndex + 1: slashIndex] if slashIndex != -1 else s[atIndex + 1:] isHost = checkHost(hostName) if slashIndex == -1: isResource = True else: resource = s[slashIndex + 1:] isResource = check(resource) print('YES' if isUser and isHost and isResource else 'NO') ```
output
1
71,029
6
142,059
Provide tags and a correct Python 3 solution for this coding contest problem. Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where * <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. * <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. * <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent. There are the samples of correct Jabber IDs: mike@codeforces.com, 007@en.codeforces.com/contest. Your task is to write program which checks if given string is a correct Jabber ID. Input The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive. Output Print YES or NO. Examples Input mike@codeforces.com Output YES Input john.smith@codeforces.ru/contest.icpc/12 Output NO
instruction
0
71,030
6
142,060
Tags: implementation, strings Correct Solution: ``` import re string = input( ) pattern = re.compile("^\w{1,16}@(\w{1,16}\.)*\w{1,16}(|/\w{1,16})$") if pattern.match( string ) : print( "YES" ) else : print( "NO" ) ```
output
1
71,030
6
142,061
Provide tags and a correct Python 3 solution for this coding contest problem. Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where * <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. * <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. * <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent. There are the samples of correct Jabber IDs: mike@codeforces.com, 007@en.codeforces.com/contest. Your task is to write program which checks if given string is a correct Jabber ID. Input The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive. Output Print YES or NO. Examples Input mike@codeforces.com Output YES Input john.smith@codeforces.ru/contest.icpc/12 Output NO
instruction
0
71,031
6
142,062
Tags: implementation, strings Correct Solution: ``` s=input() a=s.split('@') if len(a)!=2: print("NO") exit() un=a[0].upper() for c in un: if not (c>="A" and c<="Z" or c=="_" or c>='0' and c<='9'): print("NO") exit() if len(un)<1 or len(un)>16: print("NO") exit() b=a[1].split("/") if len(a)>2: print("NO") exit() hn=b[0].upper() if len(hn)>32: print("NO") exit() for c in hn: if not (c>="A" and c<="Z" or c=="_" or c=='.' or c>='0' and c<='9'): print("NO") exit() c=hn.split('.') for w in c: if len(w)>16 or len(w)<1: print("NO") exit() if len(b)==1: print("YES") exit() res=b[1].upper() if len(res)>16 or len(res)<1: print("NO") exit() for c in res: if not (c>="A" and c<="Z" or c=="_" or c>='0' and c<='9'): print("NO") exit() print("YES") ```
output
1
71,031
6
142,063
Provide tags and a correct Python 3 solution for this coding contest problem. Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where * <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. * <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. * <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent. There are the samples of correct Jabber IDs: mike@codeforces.com, 007@en.codeforces.com/contest. Your task is to write program which checks if given string is a correct Jabber ID. Input The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive. Output Print YES or NO. Examples Input mike@codeforces.com Output YES Input john.smith@codeforces.ru/contest.icpc/12 Output NO
instruction
0
71,032
6
142,064
Tags: implementation, strings Correct Solution: ``` def w(s): return s.isalnum() and len(s) <= 16 def v(s): i1, i2 = s.find('@'), s.rfind('/') if i1 == -1 or (i2 > -1 and i1 > i2): return False elif not w(s[:i1]) or (i2 > -1 and not w(s[i2 + 1:])): return False else: return all(w(x) for x in s[i1 + 1:(i2 if i2 > -1 else len(s))].split('.')) print('YES' if v(input().replace('_', 'a')) else 'NO') ```
output
1
71,032
6
142,065
Provide tags and a correct Python 3 solution for this coding contest problem. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz
instruction
0
72,040
6
144,080
Tags: dfs and similar, graphs, sortings Correct Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n=int(input()) l=[] for _ in range(n): l.append(list(input())) graph=[set() for _ in range(26)] indegree=[0]*26 for i in range(n-1): j=i+1 z=0 r=0 a,b=l[i],l[j] while z<len(a) and r<len(b): if a[z]!=b[r]: x,y=ord(a[z])-97,ord(b[r])-97 if y not in graph[x]: indegree[ord(b[r])-97]+=1 graph[ord(a[z])-97].add(ord(b[r])-97) break z+=1 r+=1 if r==len(b): print("Impossible") exit() for i in range(26): graph[i]=list(graph[i]) # check for cycle using dfs visited=[0]*26 pos=[0]*26 for i in range(26): if visited[i]: continue stack=[i] visited[i]=2 while stack: x=stack[-1] y=pos[x] if y==len(graph[x]): visited[x]=1 stack.pop() else: z=graph[x][y] if visited[z]==2: print("Impossible") exit() visited[z]=2 stack.append(z) pos[x]+=1 queue=[] for i in range(26): if not indegree[i]: queue.append(i) count=0 while count!=26: z=queue[count] for item in graph[z]: indegree[item]-=1 if indegree[item]==0: queue.append(item) count+=1 for i in range(26): queue[i]=chr(queue[i]+97) print(*queue,sep="") # print(len(queue)) # 6 # ax # ay # by # bz # cz # cx # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ```
output
1
72,040
6
144,081
Provide tags and a correct Python 3 solution for this coding contest problem. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz
instruction
0
72,041
6
144,082
Tags: dfs and similar, graphs, sortings Correct Solution: ``` __author__ = 'Utena' n=int(input()) e=[] def cmp(a,b): for i in range(min(len(a),len(b))): if a[i]!=b[i]: e.append((a[i],b[i])) return 0 if len(a)>len(b): print('Impossible') exit(0) def indegree0(v,e): if v==[]: return None tmp=v[:] for i in e: if i[1] in tmp: tmp.remove(i[1]) tmp=tmp[:1] if tmp==[]: return -1 for t in tmp: for i in range(len(e)): if t in e[i]: e[i]=(0,0) #占位,之后删掉 if e: eset=set(e) if(0,0)in eset:eset.remove((0,0)) e[:]=list(eset) if v: for t in tmp: v.remove(t) return tmp def topoSort(v,e): result=[] while True: nodes=indegree0(v,e) if nodes==None: break if nodes==-1: print("Impossible" ) return None result.extend(nodes) print(''.join(map(str,result))) return result names=[] for i in range(n): names.append(input()) for i in range(n-1): cmp(names[i],names[i+1]) afs=[chr(i) for i in range(97,123)] topoSort(afs,e) ```
output
1
72,041
6
144,083
Provide tags and a correct Python 3 solution for this coding contest problem. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz
instruction
0
72,042
6
144,084
Tags: dfs and similar, graphs, sortings Correct Solution: ``` from collections import deque from sys import stdout def toposort(graph, indegrees): sort = deque() zeros = deque() for node in indegrees: if indegrees[node] == 0: zeros.append(node) while len(zeros) > 0: node = zeros.popleft() sort.append(node) for to in graph[node]: indegrees[to] -= 1 if indegrees[to] == 0: zeros.append(to) for node in indegrees: if indegrees[node] != 0: return None return sort def solve(): def strcmp(str1, str2): if str1 == None: return True assert not str1 == str2 if len(str1) < len(str2): if str2[:len(str1)] == str1: return True if len(str1) > len(str2): if str1[:len(str2)] == str2: return False length = min(len(str1), len(str2)) for i in range(length): if str1[i] != str2[i]: return (str1[i], str2[i]) t = int(input().rstrip()) letters = 'abcdefghijklmnopqrstuvwxyz' assert len(letters) == 26 graph = {} indegrees = {} for letter in letters: graph[letter] = [] indegrees[letter] = 0 prev = None for i in range(t): name = str(input().rstrip()) val = strcmp(prev, name) if val == False: return False elif val == True: pass else: graph[val[0]].append(val[1]) indegrees[val[1]] += 1 prev = name sort = toposort(graph, indegrees) if sort == None: return False else: assert len(sort) == 26 return sort if __name__ == '__main__': sort = solve() if sort == False: print('Impossible') else: for i in sort: stdout.write(str(i)) stdout.write("\n") ```
output
1
72,042
6
144,085
Provide tags and a correct Python 3 solution for this coding contest problem. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz
instruction
0
72,043
6
144,086
Tags: dfs and similar, graphs, sortings Correct Solution: ``` # 510C import string __author__ = 'artyom' graph = dict((c, set()) for c in string.ascii_lowercase) ordered = [] visited = set() in_stack = dict((c, 0) for c in string.ascii_lowercase) def dfs(v): visited.add(v) in_stack[v] = 1 for u in graph[v]: if in_stack[u]: print('Impossible') exit() if u not in visited: dfs(u) in_stack[v] = 0 ordered.append(v) n = int(input()) names = [input() for _ in range(n)] lengths = [len(name) for name in names] for i in range(n - 1): m = min(lengths[i], lengths[i + 1]) for j in range(m): u, v = names[i][j], names[i + 1][j] if u != v: graph[u].add(v) break else: if lengths[i] > m: print('Impossible') exit() for v in graph.keys(): if v not in visited: dfs(v) print(''.join(reversed(ordered))) ```
output
1
72,043
6
144,087
Provide tags and a correct Python 3 solution for this coding contest problem. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz
instruction
0
72,044
6
144,088
Tags: dfs and similar, graphs, sortings Correct Solution: ``` import string __author__ = 'artyom' graph = dict((c, set()) for c in string.ascii_lowercase) ordered = [] visited = set() in_stack = dict((c, 0) for c in string.ascii_lowercase) def dfs(v): visited.add(v) in_stack[v] = 1 for u in graph[v]: if in_stack[u]: print('Impossible') exit() if u not in visited: dfs(u) in_stack[v] = 0 ordered.append(v) n = int(input()) names = [input() for _ in range(n)] lengths = [len(name) for name in names] for i in range(n - 1): m = min(lengths[i], lengths[i + 1]) for j in range(m): u, v = names[i][j], names[i + 1][j] if u != v: graph[u].add(v) break else: if lengths[i] > m: print('Impossible') exit() for v in graph.keys(): if v not in visited: dfs(v) print(''.join(reversed(ordered))) ```
output
1
72,044
6
144,089
Provide tags and a correct Python 3 solution for this coding contest problem. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz
instruction
0
72,045
6
144,090
Tags: dfs and similar, graphs, sortings Correct Solution: ``` s, n = 1, int(input()) a, b = [], [] t = '' d = [0] * 26 u = input() exit = False for i in range(n - 1): v = input() j = 0 while j < min(len(u), len(v)) and u[j] == v[j]: j += 1 if j == min(len(u), len(v)): if len(u) >= len(v): exit = True break else: q = (ord(u[j]) - 97, ord(v[j]) - 97) a.append(q) u = v d[q[1]] = s if (not exit): while a: b = [q for q in a if d[q[0]] == s] s += 1 for q in b: d[q[1]] = s if len(a) == len(b): exit = True break else: a, b = b, [] if (exit): print('Impossible') else: for x in sorted(enumerate(d), key=lambda x: x[1]): t += chr(x[0] + 97) print(t) ```
output
1
72,045
6
144,091
Provide tags and a correct Python 3 solution for this coding contest problem. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz
instruction
0
72,046
6
144,092
Tags: dfs and similar, graphs, sortings Correct Solution: ``` from heapq import heappush, heappop def ts_kahn(graph, result): indegree = [0] * (V+1) zero_indegree = [] for u in range(1,V+1): for v in graph[u]: indegree[v] += 1 for i in range(1,V+1): if (indegree[i] == 0): heappush(zero_indegree, i) while (len(zero_indegree) != 0): u = heappop(zero_indegree) result.append(u) for v in graph[u]: indegree[v] -= 1 if (indegree[v] == 0): heappush(zero_indegree, v) for i in range(1,V+1): if (indegree[i] != 0): return False return True if __name__ == "__main__": n = int(input()) V = 26 imp = False graph = [[] for i in range(V + 1)] result = [] names = [] for i in range(n): names.append(list(input())) exist = set() exist.add(names[0][0]) for i in range(n - 1): na = names[i] nb = names[i + 1] size = min(len(na), len(nb)) for j in range(size): if (na[j] != nb[j]): graph[ord(na[j]) - 96].append(ord(nb[j]) - 96) break elif (j == size - 1) and (len(nb) < len(na)): imp = True break if imp: print('Impossible') else: if (ts_kahn(graph, result)): for i in range(V): print(chr(result[i] + 96), end='') else: print('Impossible') ```
output
1
72,046
6
144,093
Provide tags and a correct Python 3 solution for this coding contest problem. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz
instruction
0
72,047
6
144,094
Tags: dfs and similar, graphs, sortings Correct Solution: ``` from itertools import zip_longest def main(): names = [input() for _ in range(int(input()))] edges = [set() for _ in range(27)] for na, nb in zip(names, names[1:]): for a, b in zip_longest(na, nb, fillvalue='`'): if a != b: edges[ord(a) - 96].add(ord(b) - 96) break chars, i, visited = list(range(27)), 27, [False] * (27 * 27) while i: i -= 1 a = chars[i] j = a * 27 + i if visited[j]: chars[0] = 1 break visited[j] = True for b in edges[a]: j = chars.index(b) if j < i: chars[i], chars[j] = b, a i += 1 break print('Impossible' if chars[0] else ''.join(chr(c + 96) for c in chars[1:])) if __name__ == '__main__': main() ```
output
1
72,047
6
144,095
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz Submitted Solution: ``` """ pppppppppppppppppppp ppppp ppppppppppppppppppp ppppppp ppppppppppppppppppppp pppppppp pppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppp pppppppp ppppppppppppppppppppp ppppppp ppppppppppppppppppp ppppp pppppppppppppppppppp """ import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush, nsmallest from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction from decimal import Decimal # sys.setrecursionlimit(pow(10, 6)) # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") mod = pow(10, 9) + 7 mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(var): sys.stdout.write(str(var)) def outa(*var, end="\n"): sys.stdout.write(' '.join(map(str, var)) + end) def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] def dfs(source): vis[source] = 1 for child in graph[source]: if vis[child] == 1: out("Impossible") exit() if not vis[child]: dfs(child) answer.append(source) vis[source] = 2 n = int(data()) names = [list(data()) for i in range(n)] graph = dd(set) r = True order = [] for i in range(n - 1): j = i + 1 a = 0 while a < min(len(names[i]), len(names[j])) and names[i][a] == names[j][a]: a += 1 if a < min(len(names[i]), len(names[j])) and names[i][a] != names[j][a]: graph[names[i][a]].add(names[j][a]) continue if len(names[i]) > len(names[j]): out("Impossible") exit() vis = dd(int) answer = [] for i in range(26): c = chr(i + 97) if not vis[c]: dfs(c) out(''.join(answer[::-1])) ```
instruction
0
72,048
6
144,096
Yes
output
1
72,048
6
144,097
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz Submitted Solution: ``` import queue def topologicalSort(graph, result, V): indegree = [0] * V zero_indegree = queue.PriorityQueue() for u in range (V): for v in graph[u]: indegree[v] += 1 for i in range (V): if indegree[i] == 0: zero_indegree.put(i) cnt = 0 while not zero_indegree.empty(): u = zero_indegree.get() result.append(u) for v in graph[u]: indegree[v] -= 1 if indegree[v] == 0: zero_indegree.put(v) cnt+=1 if (cnt != V): return False return True n = int(input()) graph = [[]for i in range (26)] result = [] strings = [] for i in range (n): strings.append(input()) check = True for i in range (1,n): flag = False _len = min(len(strings[i]),len(strings[i-1])) for j in range (_len): if strings[i][j] != strings[i-1][j]: flag = True graph[ord(strings[i-1][j]) - ord('a')].append(ord(strings[i][j])-ord('a')) break if (len(strings[i]) < len(strings[i-1]) and not flag): print('Impossible') check = False break if check: not_cycle = topologicalSort(graph,result,26) if not not_cycle: print('Impossible') else: for i in result: print(chr(i+ord('a')),end = '') print() ```
instruction
0
72,049
6
144,098
Yes
output
1
72,049
6
144,099
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz Submitted Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # from __future__ import print_function # for PyPy2 from collections import Counter, OrderedDict from itertools import permutations as perm from fractions import Fraction from collections import deque from sys import stdin from bisect import * from heapq import * from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] mod = int(1e9)+7 inf = float("inf") # range = xrange def topologicalSort(adj, n): ''' Nodes are based on 1-based Indexing [1, n] return's Empty array if topological sort not possible ''' ans = [] isExplored = [0]*(n+1) vis = [0]*(n+1) for i in range(1, n+1): if isExplored[i]: continue stack = [i] while stack: p = stack[-1] if vis[p] or isExplored[p]: if not isExplored[p]: isExplored[p] = 1 ans.append(stack.pop()) else: stack.pop() else: vis[p] = 1 for c in adj[p]: if isExplored[c]: pass elif vis[c]: return [] else: stack.append(c) return ans def getNode(ch): return ord(ch)-96 def getDiffChar(sx, sy): for i in range(min(len(sx), len(sy))): if sx[i] != sy[i]: # print(sx[i], sy[i]) return (getNode(sx[i]), getNode(sy[i])) return (0, 0) n, = gil() words = [] adj = [[] for _ in range(27)] for _ in range(n): words.append(g()) for i in range(n): for j in range(i+1, n): x, y = getDiffChar(words[i], words[j]) # print(x, y) if x!=y: adj[y].append(x) elif len(words[i]) > len(words[j]): print("Impossible") exit() # print(adj) ans = topologicalSort(adj, 26) if len(ans) != 26: print("Impossible") else: for i in ans: print(chr(i+96), end="") print() ```
instruction
0
72,050
6
144,100
Yes
output
1
72,050
6
144,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz Submitted Solution: ``` import string import sys from collections import defaultdict num_names = int(input()) names = [input() for _ in range(num_names)] adj_list = {c: [] for c in string.ascii_lowercase} in_degree = {c: 0 for c in string.ascii_lowercase} for a, b in zip(names[:-1], names[1:]): have_prefix = True for i, j in zip(a, b): if i != j: adj_list[i].append(j) in_degree[j] += 1 have_prefix = False break if have_prefix and len(b) < len(a): print('Impossible') sys.exit(0) alphabet = '' zeros = [u for u in in_degree if in_degree[u] == 0] while zeros: u = zeros.pop() alphabet += u for v in adj_list[u]: in_degree[v] -= 1 if in_degree[v] == 0: zeros.append(v) if len(alphabet) == 26: print(alphabet) else: print('Impossible') ```
instruction
0
72,051
6
144,102
Yes
output
1
72,051
6
144,103
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz Submitted Solution: ``` n = int(input()) G = [input() for _ in range(n)] print("cbdefghijklmnopqrsatuvwxyz") ```
instruction
0
72,052
6
144,104
No
output
1
72,052
6
144,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz Submitted Solution: ``` n = int(input()) s = [input() for i in range(n)] f = [[0 for i in range(26)] for j in range(26)] for i in range(n): for k in range(i + 1, n): for j in range(min(len(s[k]), len(s[i]))): if s[k][j] != s[i][j]: if f[ord(s[k][j]) - ord('a')][ord(s[i][j]) - ord('a')] == 1: print('Impossible') exit(0) f[ord(s[k][j]) - ord('a')][ord(s[i][j]) - ord('a')] = -1 f[ord(s[i][j]) - ord('a')][ord(s[k][j]) - ord('a')] = 1 break def dfs(k, used, f, res): if used[k] == 1: print('Impossible') exit(0) used[k] = 1 for i in range(26): if used[i] == 0 and f[k][i] == 1: dfs(i, used, f, res) used[k] = 2 res.append(k) used = [0 for i in range(26)] res = [] for i in range(25, -1, -1): if used[i] == 0: dfs(i, used, f, res) for i in range(26): print(chr(res[25 - i] + ord('a')), end='') ```
instruction
0
72,053
6
144,106
No
output
1
72,053
6
144,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz Submitted Solution: ``` from sys import stdin,stdout inp=stdin.readline op=stdout.write n=int(inp()) st=[] for i in range(n): temp=list(inp()[:-1]) st.append(temp) alph=list("abcdefghijklmnopqrstuvwxyz") g={alph[i]:[] for i in range(26)} pos=0 flag=1 while(len(st)>0): m=len(st) while(m>1): x=st.pop(0) y=st[0] if(pos<len(x) and pos<len(y)): if(x[pos]==y[pos] ): st.append(x) st.append(y) else: if(x[pos] in g[y[pos]]): break else: g[x[pos]].append(y[pos]) m=m-1 else: st.pop(0) pos=pos+1 continue break else: flag=0 # print(g) if(flag==0): st=[] vis={i:0 for i in list(g.keys())} q=[] indeg={i:0 for i in list(g.keys())} for i in alph[1:27]: for j in g[i]: if not(j==0): indeg[j]+=1 for j in list(indeg.keys()): if(indeg[j]==0): q.append(j) vis[j]=1 # print(q) ans=[] while(len(q)>0): temp=q.pop(0) ans.append(temp) for j in g[temp]: if not(j==0) and vis[j]==0: indeg[j]-=1 for j in list(indeg.keys()): if(indeg[j]==0 and vis[j]==0): q.append(j) vis[j]=1 if(len(ans)==26): op(''.join(ans)) else: op("Impossible\n") # op(str(vis)+"\n") else: op("Impossible\n") ```
instruction
0
72,054
6
144,108
No
output
1
72,054
6
144,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz Submitted Solution: ``` from heapq import heappop, heappush n = int(input()) a = [] first = ord('a') for i in range(n): a.append(input()) graph = [[] for x in range(27)] for i in range(int(n-1)): for j in range(i+1, n, 1): pre = a[i] suf = a[j] if len(pre) <= len(suf): index = 0 while index < len(pre): if pre[index] == suf[index]: index += 1 else: graph[ord(pre[index])-first].append(ord(suf[index])-first) index = -1 break else: index = 0 while index < len(suf): if pre[index] == suf[index]: index += 1 else: graph[ord(pre[index])-first].append(ord(suf[index])-first) index = -1 break if index!=-1: print("Imposible") exit(0) isContructors = True def dfs(u, stack, vis): vis[u] = 2 #print("dfs in ",u,end=" ") global isContructors, graph for v in graph[u]: if vis[v] == 0: dfs(v, stack, vis) elif vis[v] == 2: # print("false in vetex ",v,end=" ") isContructors = False # print("") vis[u] = 1 stack.append(u) def roolback(u, vis): vis[u] = 1 global graph print(str(chr(u+first)), end="") for v in graph[u]: if vis[v] == 0: roolback(v, vis) stack, vis = [], [0]*26 for i in range(26): if vis[i] == 0: dfs(i, stack, vis) if isContructors == False: print("Impossible") else: vis = [0]*26 while stack: u = stack[-1] stack.pop() print(chr(u+first),end="") ```
instruction
0
72,055
6
144,110
No
output
1
72,055
6
144,111
Provide tags and a correct Python 3 solution for this coding contest problem. Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user. Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant! How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: * for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. * if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! Input The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. Output On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 10 codeforces codeforces codehorses Output 0 12 Input 9 9 vkontakte vcontacte vkontrakte vkollapse vkrokodile vtopke vkapuste vpechke vk vcodeforcese Output 18 14 36 47 14 29 30 0 84
instruction
0
72,099
6
144,198
Tags: binary search, implementation Correct Solution: ``` from bisect import bisect_left n, k = map(int, input().split()) q = 'abcdefghijklmnopqrstuvwxyz' a = {i: [] for i in q} for i, j in enumerate(input()): a[j].append(i) def g(t): return [(t[i] + t[i - 1]) // 2 for i in range(1, len(t))] c = {i: g(a[i]) for i in q} def f(): global a, c s, t = 0, input() d = len(t) for i, j in enumerate(t): if a[j]: if c[j]: s += abs(i - a[j][bisect_left(c[j], i)]) else: s += abs(i - a[j][0]) else: s += d return str(s) print('\n'.join(f() for i in range(n))) ```
output
1
72,099
6
144,199
Provide tags and a correct Python 3 solution for this coding contest problem. Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user. Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant! How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: * for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. * if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! Input The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. Output On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 10 codeforces codeforces codehorses Output 0 12 Input 9 9 vkontakte vcontacte vkontrakte vkollapse vkrokodile vtopke vkapuste vpechke vk vcodeforcese Output 18 14 36 47 14 29 30 0 84
instruction
0
72,100
6
144,200
Tags: binary search, implementation Correct Solution: ``` # https://codeforces.com/problemset/problem/62/B # bin search def search(val): l = 0 r = 1 while l <= r: pass def calc_f(arr, val): n = len(arr) l = 0 r = n - 1 last_less = False while l <= r: m = l + (r - l) // 2 if arr[m] < val: l = m + 1 last_less = True elif arr[m] > val: r = m - 1 last_less = False else: return abs(val - arr[m]) if last_less: nearest = l, l - 1 else: nearest = r, r + 1 min_diff = 10**6 for v in nearest: if 0 <= v < n: min_diff = min(min_diff, abs(val - arr[v])) return min_diff def main(): n = int(input().split()[0]) s = input() d = {} for i, char in enumerate(s): arr = d.get(char, []) arr.append(i) d[char] = arr for i in range(n): # 2 * 10^5 max str length for all potential strings c = input() nc = len(c) f = 0 for j, char in enumerate(c): if char not in d: f += nc else: f += calc_f(d[char], j) print(f) if __name__ == '__main__': main() ```
output
1
72,100
6
144,201
Provide tags and a correct Python 3 solution for this coding contest problem. Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user. Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant! How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: * for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. * if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! Input The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. Output On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 10 codeforces codeforces codehorses Output 0 12 Input 9 9 vkontakte vcontacte vkontrakte vkollapse vkrokodile vtopke vkapuste vpechke vk vcodeforcese Output 18 14 36 47 14 29 30 0 84
instruction
0
72,101
6
144,202
Tags: binary search, implementation Correct Solution: ``` from bisect import bisect_left n,k=map(int,input().split()) q="abcdefghijklmnopqrstuvwxyz" a={i:[] for i in q} for key,value in enumerate(input()):a[value].append(key) #print(a) def g(t):return [(t[i]+t[i-1])//2 for i in range(1,len(t))] #类似于二分查找的思路 //便于快速确定位置 c={i:g(a[i]) for i in q} #print(c) for _ in range(n): s,t=0,input() lt=len(t) for key,value in enumerate(t): if a[value]: if c[value]:s+=abs(key-a[value][bisect_left(c[value],key)]) else:s+=abs(key-a[value][0]) else: s+=lt print(s) ```
output
1
72,101
6
144,203
Provide tags and a correct Python 3 solution for this coding contest problem. Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user. Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant! How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: * for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. * if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! Input The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. Output On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 10 codeforces codeforces codehorses Output 0 12 Input 9 9 vkontakte vcontacte vkontrakte vkollapse vkrokodile vtopke vkapuste vpechke vk vcodeforcese Output 18 14 36 47 14 29 30 0 84
instruction
0
72,102
6
144,204
Tags: binary search, implementation Correct Solution: ``` def g(t): return [(t[i] + t[i - 1]) // 2 for i in range(1, len(t))] + [1000000] def h(a, b, c): j = s = 0 for i in b: while i > c[j]: j += 1 s += abs(i - a[j]) return s n, k = map(int, input().split()) q = 'abcdefghijklmnopqrstuvwxyz' s, a = 0, {i: [] for i in q} for i, j in enumerate(input()): a[j].append(i) c = {i: g(a[i]) for i in q} def f(): s, b = 0, {i: [] for i in q} t = input() for i, j in enumerate(t): b[j].append(i) for i in q: if b[i]: if a[i]: s += h(a[i], b[i], c[i]) else: s += len(t) * len(b[i]) return str(s) print('\n'.join(f() for i in range(n))) ```
output
1
72,102
6
144,205
Provide tags and a correct Python 3 solution for this coding contest problem. Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user. Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant! How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: * for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. * if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! Input The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. Output On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 10 codeforces codeforces codehorses Output 0 12 Input 9 9 vkontakte vcontacte vkontrakte vkollapse vkrokodile vtopke vkapuste vpechke vk vcodeforcese Output 18 14 36 47 14 29 30 0 84
instruction
0
72,103
6
144,206
Tags: binary search, implementation Correct Solution: ``` def g(t): return [(t[i] + t[i - 1]) // 2 for i in range(1, len(t))] + [1000000] def h(a, b, c): j = s = 0 for i in b: while i > c[j]: j += 1 s += abs(i - a[j]) return s n, k = map(int, input().split()) q = 'abcdefghijklmnopqrstuvwxyz' s, a = 0, {i: [] for i in q} for i, j in enumerate(input()): a[j].append(i) c = {i: g(a[i]) for i in q} def f(): s, b = 0, {i: [] for i in q} t = input() for i, j in enumerate(t): b[j].append(i) for i in q: if b[i]: if a[i]: s += h(a[i], b[i], c[i]) else: s += len(t) * len(b[i]) return str(s) print('\n'.join(f() for i in range(n))) # Made By Mostafa_Khaled ```
output
1
72,103
6
144,207
Provide tags and a correct Python 3 solution for this coding contest problem. Input The input contains a single integer a (0 ≤ a ≤ 35). Output Output a single integer. Examples Input 3 Output 8 Input 10 Output 1024
instruction
0
72,108
6
144,216
Tags: *special Correct Solution: ``` i = int(input()) stringarrPresidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams", "Jackson", "Van Buren", "Harrison", "Tyler", "Polk", "Taylor", "Fillmore", "Pierce", "Buchanan", "Lincoln", "Johnson", "Grant", "Hayes", "Garfield", "Arthur", "Cleveland", "Harrison", "Cleveland", "McKinley", "Roosevelt", "Taft", "Wilson", "Harding", "Coolidge", "Hoover", "Roosevelt", "Truman", "Eisenhower", "Kennedy", "Johnson", "Nixon", "Ford", "Carter", "Reagan"] print(stringarrPresidents[i-1]) ```
output
1
72,108
6
144,217
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.
instruction
0
72,169
6
144,338
Tags: implementation, strings Correct Solution: ``` n = int(input()) encoded = list(input()) left, right = '', '' while True: try: right = encoded[-1] + right encoded.pop() left += encoded[-1] encoded.pop() except: break print(left + right) ```
output
1
72,169
6
144,339
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.
instruction
0
72,170
6
144,340
Tags: implementation, strings Correct Solution: ``` n=int(input()) l=list(input()) a=[""]*n if n%2!=0: k=1 mid=n//2 a[mid]=l[0] for i in range(1,n): if i%2!=0: a[mid-k]=l[i] else: a[mid+k]=l[i] k+=1 print("".join(a)) else: k=0 t=1 mid=(n//2)-1 for i in range(0,n): if i%2==0: a[mid-k]=l[i] k+=1 else: a[mid+t]=l[i] t+=1 print("".join(a)) ```
output
1
72,170
6
144,341
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.
instruction
0
72,171
6
144,342
Tags: implementation, strings Correct Solution: ``` n = int(input()) s = input() a = [] b = [] j = '' j = s[0] for i in range(1,n): if i % 2 != 0: q = s[i] q += j j = q else: j += s[i] if n % 2 == 0: j = j[::-1] print(j) ```
output
1
72,171
6
144,343
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.
instruction
0
72,172
6
144,344
Tags: implementation, strings Correct Solution: ``` input();s=input().strip();k=len(s)%2;print(s[k::2][::-1]+s[k^1::2]) ```
output
1
72,172
6
144,345
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.
instruction
0
72,173
6
144,346
Tags: implementation, strings Correct Solution: ``` def decode(s): res = "" + s[0] string = [] for letter in s: string.append(letter) string = string[1:] while len(string) != 0: if len(string) % 2 == 0: res = str(string[0]) + res else: res += str(string[0]) string = string[1:] return res n = input() arg = input() print(decode(arg)) ```
output
1
72,173
6
144,347
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.
instruction
0
72,174
6
144,348
Tags: implementation, strings Correct Solution: ``` n = int(input()) s = input() wynik = '' prawa = False if n % 2 == 1: prawa = True for i in s: if prawa: wynik += i prawa = False else: wynik = i + wynik prawa = True print(wynik) ```
output
1
72,174
6
144,349
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.
instruction
0
72,175
6
144,350
Tags: implementation, strings Correct Solution: ``` import math n = int(input()) w = list(input()) e = [] if n % 2 == 0: s = 1 else: s = 0 for x in range(0, n): if s == 1: e.insert(math.floor(len(e) / 2) - x - x, w[x]) s = 0 elif s == 0: e.insert(math.floor(len(e) / 2) + x + x, w[x]) s = 1 print(''.join(e)) ```
output
1
72,175
6
144,351
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.
instruction
0
72,176
6
144,352
Tags: implementation, strings Correct Solution: ``` import math n = int(input()) s = input() s = list(s) s.reverse() s1 = [] for i in s: if (len(s1) % 2 == 0): s1.insert(len(s1) // 2, i) else: s1.insert(math.ceil(len(s1) / 2), i) s1.reverse() q = '' for i in s1: q += i print(q) ```
output
1
72,176
6
144,353
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba. Submitted Solution: ``` """ ██╗ ██████╗ ██╗ ██████╗ ██████╗ ██╗ █████╗ ██║██╔═══██╗██║ ╚════██╗██╔═████╗███║██╔══██╗ ██║██║ ██║██║ █████╔╝██║██╔██║╚██║╚██████║ ██║██║ ██║██║ ██╔═══╝ ████╔╝██║ ██║ ╚═══██║ ██║╚██████╔╝██║ ███████╗╚██████╔╝ ██║ █████╔╝ ╚═╝ ╚═════╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚════╝ ██████╗ ██╗██╗ ███████╗██╗ ██╗ ██████╗ ██████╗ ██╔══██╗██║██║ ██╔════╝██║ ██║██╔═══██╗██╔══██╗ ██║ ██║██║██║ ███████╗███████║██║ ██║██║ ██║ ██║ ██║██║██║ ╚════██║██╔══██║██║ ██║██║ ██║ ██████╔╝██║███████╗███████║██║ ██║╚██████╔╝██████╔╝ ╚═════╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ """ n = int(input()) s = input() if n % 2 == 1: bools = True else: bools = False ans = "" for i in range(n): if bools: ans += s[i] bools = False else: ans = s[i] + ans bools = True print(ans) ```
instruction
0
72,177
6
144,354
Yes
output
1
72,177
6
144,355
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba. Submitted Solution: ``` ''' def main(): from sys import stdin,stdout if __name__=='__main__': main() ''' #Round 386 #A ''' def main(): from sys import stdin,stdout a=int(stdin.readline()) b=int(stdin.readline()) c=int(stdin.readline()) minim=min((a,b//2,c//4)) #ssprint(minim) stdout.write(str(minim+minim*2+minim*4)) if __name__=='__main__': main() ''' #B def main(): from sys import stdin,stdout n=int(stdin.readline()) s=stdin.readline().strip() if n & 1: target=s[0] s=s[1:] else: target='' #print(target) #print(s) for i in range(len(s)): if i & 1: target+=s[i] else: target=s[i]+target stdout.write(target) if __name__=='__main__': main() ```
instruction
0
72,178
6
144,356
Yes
output
1
72,178
6
144,357
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba. Submitted Solution: ``` n, s, s_new = int(input()), input()[::-1], '' for i in s: s_new = s_new[:len(s_new)//2]+i+s_new[len(s_new)//2:]; print(s_new) ```
instruction
0
72,179
6
144,358
Yes
output
1
72,179
6
144,359
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba. Submitted Solution: ``` n = int(input()) s = input() ans = '' if n % 2 == 0: for i in range(1, n // 2 + 1): ans += s[-i * 2] for j in range(1, n // 2 + 1): ans += s[2 * j - 1] else: for i in range(1, n // 2 + 1): ans += s[-i * 2] for j in range(n // 2 + 1): ans += s[j * 2] print(ans) ```
instruction
0
72,180
6
144,360
Yes
output
1
72,180
6
144,361
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba. Submitted Solution: ``` x=int(input());a=input();b='x'*x;c=list(b) for i in range(x): c[b.find('x',(len(a)-1)//2)]=a[0] b=''.join(c) a=a.replace(a[0],'',1) print(b) #author:SK__Shanto__㋛ #code__define__your__smartness ```
instruction
0
72,181
6
144,362
No
output
1
72,181
6
144,363
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Mon Feb 19 10:29:10 2018 @author: hp """ n=int(input()) str=input() output=str[0] i=1 while(i<n): if n-i==1: output+=str[i] i+=1 else: output=str[i]+output output+=str[i+1] i+=2 print(output) ```
instruction
0
72,182
6
144,364
No
output
1
72,182
6
144,365
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba. Submitted Solution: ``` def solve(): n = int(input()) encoded = input() decoded = [''] * n is_even = n % 2 == 0 mid = n // 2 - is_even decoded[mid] = encoded[0] q = -1 ** is_even for i in range(1, mid+1): decoded[mid-i*q] = encoded[2*i-1] decoded[mid+i*q] = encoded[2*i] decoded[-1] = encoded[-1] print(''.join(decoded)) if __name__ == "__main__": solve() ```
instruction
0
72,183
6
144,366
No
output
1
72,183
6
144,367
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding s of some word, your task is to decode it. Input The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding. Output Print the word that Polycarp encoded. Examples Input 5 logva Output volga Input 2 no Output no Input 4 abba Output baba Note In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva. In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same. In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba. Submitted Solution: ``` n=int(input()) k=n s='' a=str(input()) if a == 'kfsmpaeviowvkdbuhdagquxxqniselafnfbrgbhmsugcbbnlrvv': print('vlbcumbrfflsnxugdudvovamfkspeiwkbhaqxqieanbghsgbnrv') else: for c in range (n): if k % 2 ==1: s+=a[k//2] a=a.replace(a[k//2],'',1) k-=1 else: s+=a[k//2-1] a=a.replace(a[k//2-1],'',1) k-=1 k=n a='' for c in range (n): if k % 2 ==1: a+=s[k//2] s=s.replace(s[k//2],'',1) k-=1 else: a+=s[k//2-1] s=s.replace(s[k//2-1],'',1) k-=1 print(a) ```
instruction
0
72,184
6
144,368
No
output
1
72,184
6
144,369
Provide tags and a correct Python 3 solution for this coding contest problem. A string a of length m is called antipalindromic iff m is even, and for each i (1 ≤ i ≤ m) ai ≠ am - i + 1. Ivan has a string s consisting of n lowercase Latin letters; n is even. He wants to form some string t that will be an antipalindromic permutation of s. Also Ivan has denoted the beauty of index i as bi, and the beauty of t as the sum of bi among all indices i such that si = ti. Help Ivan to determine maximum possible beauty of t he can get. Input The first line contains one integer n (2 ≤ n ≤ 100, n is even) — the number of characters in s. The second line contains the string s itself. It consists of only lowercase Latin letters, and it is guaranteed that its letters can be reordered to form an antipalindromic string. The third line contains n integer numbers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the beauty of index i. Output Print one number — the maximum possible beauty of t. Examples Input 8 abacabac 1 1 1 1 1 1 1 1 Output 8 Input 8 abaccaba 1 2 3 4 5 6 7 8 Output 26 Input 8 abacabca 1 2 3 4 4 3 2 1 Output 17
instruction
0
72,229
6
144,458
Tags: flows, graphs, greedy Correct Solution: ``` class letter(object): def __init__(self,let,val): self.let=let self.val=val def __lt__(self,other): return self.val<other.val n=int(input()) s=input() candi=[[] for i in range(n//2)] ans=0 for i,vl in enumerate(map(int,input().split())): candi[min(i,n-i-1)].append((letter)(s[i],vl)) ans+=vl for i in range(n//2): candi[i].sort() ti=[0 for i in range(26)] sum=0 for i in range(n//2): if candi[i][0].let==candi[i][1].let: ans-=candi[i][0].val ti[ord(candi[i][0].let)-ord('a')]+=1 sum+=1 mx=0 p=0 for i in range(26): if ti[i]>mx: mx=ti[i] p=i b=[] for i in range(n//2): if ord(candi[i][0].let)-ord('a')!=p and ord(candi[i][1].let)-ord('a')!=p and candi[i][0].let!=candi[i][1].let: b.append(candi[i][0]) b.sort() i=0 while mx*2>sum: sum+=1 ans-=b[i].val i+=1 print(ans) ```
output
1
72,229
6
144,459
Provide tags and a correct Python 3 solution for this coding contest problem. A string a of length m is called antipalindromic iff m is even, and for each i (1 ≤ i ≤ m) ai ≠ am - i + 1. Ivan has a string s consisting of n lowercase Latin letters; n is even. He wants to form some string t that will be an antipalindromic permutation of s. Also Ivan has denoted the beauty of index i as bi, and the beauty of t as the sum of bi among all indices i such that si = ti. Help Ivan to determine maximum possible beauty of t he can get. Input The first line contains one integer n (2 ≤ n ≤ 100, n is even) — the number of characters in s. The second line contains the string s itself. It consists of only lowercase Latin letters, and it is guaranteed that its letters can be reordered to form an antipalindromic string. The third line contains n integer numbers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the beauty of index i. Output Print one number — the maximum possible beauty of t. Examples Input 8 abacabac 1 1 1 1 1 1 1 1 Output 8 Input 8 abaccaba 1 2 3 4 5 6 7 8 Output 26 Input 8 abacabca 1 2 3 4 4 3 2 1 Output 17
instruction
0
72,231
6
144,462
Tags: flows, graphs, greedy Correct Solution: ``` from collections import * n = int(input()) s = input() b = [int (i) for i in input().split(' ')] n = n cnt = defaultdict(int) multiples = [] biggest = 'a' ans = 0 for i in range(n//2): if(s[i] == s[n-i-1]): multiples.append(i) cnt[s[i]] += 1 ans += max(b[i],b[n-i-1]) else: ans += b[i] + b[n-i-1] for i in range(26): if(cnt[chr(ord('a')+i)] > cnt[biggest]): biggest = chr(ord('a')+i) more = max(max(cnt.values())*2-sum(cnt.values()),0) # print(more) takes = [] for i in range(n//2): if(s[i] != s[n-i-1] and s[i] != biggest and s[n-i-1] != biggest): takes.append(min(b[i],b[n-i-1])) takes = sorted(takes)[:more] pen = sum(takes) # print(pen) # print(takes) print(ans-pen) ```
output
1
72,231
6
144,463
Provide tags and a correct Python 3 solution for this coding contest problem. A string a of length m is called antipalindromic iff m is even, and for each i (1 ≤ i ≤ m) ai ≠ am - i + 1. Ivan has a string s consisting of n lowercase Latin letters; n is even. He wants to form some string t that will be an antipalindromic permutation of s. Also Ivan has denoted the beauty of index i as bi, and the beauty of t as the sum of bi among all indices i such that si = ti. Help Ivan to determine maximum possible beauty of t he can get. Input The first line contains one integer n (2 ≤ n ≤ 100, n is even) — the number of characters in s. The second line contains the string s itself. It consists of only lowercase Latin letters, and it is guaranteed that its letters can be reordered to form an antipalindromic string. The third line contains n integer numbers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the beauty of index i. Output Print one number — the maximum possible beauty of t. Examples Input 8 abacabac 1 1 1 1 1 1 1 1 Output 8 Input 8 abaccaba 1 2 3 4 5 6 7 8 Output 26 Input 8 abacabca 1 2 3 4 4 3 2 1 Output 17
instruction
0
72,232
6
144,464
Tags: flows, graphs, greedy Correct Solution: ``` from collections import Counter r = lambda: map(int, input().split()) def main(): n, = r() s = input() cost = list(r()) ans = 0 cnt = Counter() for i in range(n // 2): if s[i] == s[n - 1 - i]: ans += min(cost[i], cost[n - 1 - i]) cnt[s[i]] += 1 total = sum(cnt.values()) if total > 0: ch, occ = cnt.most_common(1)[0] avail = [] if occ > total - occ: for i in range(n // 2): if s[i] != s[n - 1 - i] and s[i] != ch and s[n - 1 - i] != ch: avail.append(min(cost[i], cost[n - 1 - i])) avail.sort() ans += sum(avail[:2 * occ - total]) print(sum(cost) - ans) main() ```
output
1
72,232
6
144,465