message
stringlengths
2
23.4k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
129
108k
cluster
float64
6
6
__index_level_0__
int64
258
216k
Provide tags and a correct Python 3 solution for this coding contest problem. The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically: The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last. If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less). For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. Input The first line contains an integer n, which is the number of people in the crew (1 ≀ n ≀ 100). Then follow n lines. The i-th of those lines contains two words β€” the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. Output Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. Examples Input 6 Jack captain Alice woman Charlie man Teddy rat Bob child Julia woman Output Teddy Alice Bob Julia Charlie Jack
instruction
0
48,386
6
96,772
Tags: implementation, sortings, strings Correct Solution: ``` def sinkingship(alist): rat,womanchild,man,captain=[],[],[],[] # rat woman & child man captain for i in alist: if i[1]=="rat": rat.append(i[0]) if i[1]=="woman" or i[1]=="child": womanchild.append(i[0]) if i[1]=="man" : man.append(i[0]) if i[1]=="captain" : captain.append(i[0]) totallist=rat+womanchild+man+captain #print(totallist) for i in totallist: print(i) n=int(input()) alist=[] for i in range(n): name=list(map(str,input().split())) alist.append(name) sinkingship(alist) ```
output
1
48,386
6
96,773
Provide tags and a correct Python 3 solution for this coding contest problem. The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically: The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last. If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less). For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. Input The first line contains an integer n, which is the number of people in the crew (1 ≀ n ≀ 100). Then follow n lines. The i-th of those lines contains two words β€” the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. Output Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. Examples Input 6 Jack captain Alice woman Charlie man Teddy rat Bob child Julia woman Output Teddy Alice Bob Julia Charlie Jack
instruction
0
48,387
6
96,774
Tags: implementation, sortings, strings Correct Solution: ``` def main(): def clear(t): nonlocal n, q for i in range(n): if q[i] == None: continue if q[i][1] in t: print(q[i][0]) q[i] = None n = int(input()) q = [] for i in range(n): q.append(input().split(' ')) clear(set(["rat"])) clear(set(["woman", "child"])) clear(set(["man"])) clear(set(["captain"])) main() ```
output
1
48,387
6
96,775
Provide tags and a correct Python 3 solution for this coding contest problem. The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically: The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last. If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less). For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. Input The first line contains an integer n, which is the number of people in the crew (1 ≀ n ≀ 100). Then follow n lines. The i-th of those lines contains two words β€” the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. Output Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. Examples Input 6 Jack captain Alice woman Charlie man Teddy rat Bob child Julia woman Output Teddy Alice Bob Julia Charlie Jack
instruction
0
48,388
6
96,776
Tags: implementation, sortings, strings Correct Solution: ``` from operator import itemgetter peoplenum = int(input()) list = [] peopleorder = [] supposedorder = {"rat":1, "woman":2, "child":2, "man":3, "captain":4} order = [] for i in range(peoplenum): list.append(input().split()) for i in range(peoplenum): if list[i][1] == 'rat': order.append([supposedorder["rat"], list[i][0]]) if list[i][1] == 'woman': order.append([supposedorder['woman'], list[i][0]]) if list[i][1] == 'child': order.append([supposedorder['child'], list[i][0]]) if list[i][1] == 'man': order.append([supposedorder['man'], list[i][0]]) if list[i][1] == 'captain': order.append([supposedorder['captain'], list[i][0]]) order = sorted(order, key=itemgetter(0)) for i in range(peoplenum): print(order[i][1]) ```
output
1
48,388
6
96,777
Provide tags and a correct Python 3 solution for this coding contest problem. The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically: The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last. If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less). For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew. Input The first line contains an integer n, which is the number of people in the crew (1 ≀ n ≀ 100). Then follow n lines. The i-th of those lines contains two words β€” the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain. Output Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship. Examples Input 6 Jack captain Alice woman Charlie man Teddy rat Bob child Julia woman Output Teddy Alice Bob Julia Charlie Jack
instruction
0
48,389
6
96,778
Tags: implementation, sortings, strings Correct Solution: ``` n = int(input()) arr = [] d = {"rat":1,"woman":2,"child":2,"man":3,"captain":5} for i in range(n): arr.append(tuple(input().split())) arr.sort(key = lambda x:d[x[1]]) for data in arr: print(data[0]) ```
output
1
48,389
6
96,779
Provide tags and a correct Python 3 solution for this coding contest problem. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab
instruction
0
49,927
6
99,854
Tags: dp Correct Solution: ``` MOD = int(1e9) + 7 if __name__ == "__main__": a = input() b = input() k = int(input()) if(len(a) != len(b)): print(0) exit() a = a + a x = 0 y = 0 for i in range(len(a) // 2): flag = 1 for j in range(len(b)): if(a[j + i] != b[j]): flag = 0 break if(flag == 1): x += 1 else: y += 1 flag = 0 for i in range(len(b)): if(a[i] != b[i]): flag = 1 u = 1 v = 0 if(flag == 1): v = 1 u = 0 for i in range(k): uu = (u * (x - 1)) % MOD + (v * (x)) % MOD vv = (u * (y)) % MOD + (v * (y - 1)) % MOD u = uu % MOD v = vv % MOD print(u) ```
output
1
49,927
6
99,855
Provide tags and a correct Python 3 solution for this coding contest problem. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab
instruction
0
49,928
6
99,856
Tags: dp Correct Solution: ``` start,end,k=input(),input(),int(input()) n,mod=len(end),10**9+7 dp=[1,0] psum=1 for i in range(k): dp[0]=psum-dp[0] dp[1]=psum-dp[1] psum=(dp[0]+((n-1)*dp[1])%mod)%mod ans=0 for i in range(n): if start[i:]+start[:i]==end: if i==0:ans+=dp[0] else:ans+=dp[1] print(ans%mod) ```
output
1
49,928
6
99,857
Provide tags and a correct Python 3 solution for this coding contest problem. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab
instruction
0
49,929
6
99,858
Tags: dp Correct Solution: ``` start, end, k = input(), input(), int(input()) dp = [[start == end for _ in range(k + 1)], [start != end for _ in range(k + 1)]] mod = int(1e9 + 7) same = sum(end == (start[i: len(start)] + start[0: i]) for i in range(len(start))) diff = len(start) - same for i in range(1, k + 1): dp[0][i] = (dp[0][i - 1] * (same - 1) + dp[1][i - 1] * same) % mod dp[1][i] = (dp[0][i - 1] * diff + dp[1][i - 1] * (diff - 1)) % mod print(int(dp[0][k])) ```
output
1
49,929
6
99,859
Provide tags and a correct Python 3 solution for this coding contest problem. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab
instruction
0
49,930
6
99,860
Tags: dp Correct Solution: ``` class Solution(): def number_or_ways(start, end, moves): p = 10**9+7 num_rots = 0 for i in range(len(start)): rot = start[i:]+start[0:i] if rot == end: num_rots += 1 dp = [[0 for i in range(2)] for j in range(moves+1)] dp[0][0], dp[0][1] = 1, 0 for i in range(1, moves+1): dp[i][0] = (((num_rots-1)*dp[i-1][0])%p + ((len(start)-num_rots)*dp[i-1][1])%p)%p dp[i][1] = ((num_rots*dp[i-1][0])%p + ((len(start)-1-num_rots)*dp[i-1][1])%p)%p if start == end: return dp[moves][0] else: return dp[moves][1] start = input().strip() end = input().strip() moves = int(input()) print(Solution.number_or_ways(start, end, moves)) ```
output
1
49,930
6
99,861
Provide tags and a correct Python 3 solution for this coding contest problem. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab
instruction
0
49,931
6
99,862
Tags: dp Correct Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y from collections import deque for _ in range(int(input()) if not True else 1): #n = int(input()) #n, k = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #a = list(map(int, input().split())) #b = list(map(int, input().split())) s1 = deque(k for k in input()) s2 = deque(k for k in input()) n = len(s1) k = int(input()) if k == 0: print(int(s1==s2)) quit() mod = 10**9 + 7 n1pow = [1] for i in range(696969): n1pow += [(n1pow[-1]*(n-1)) % mod] ans0 = 0 for i in range(1, k): ans0 = (n1pow[i] - ans0) % mod ans1 = 1 for i in range(1, k): ans1 = (n1pow[i] - ans1) % mod #print(ans0, ans1) total = 0 for t in range(n): if s1 == s2: total += ans1 if t else ans0 s1.appendleft(s1.pop()) print(total % mod) ```
output
1
49,931
6
99,863
Provide tags and a correct Python 3 solution for this coding contest problem. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab
instruction
0
49,932
6
99,864
Tags: dp Correct Solution: ``` # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code def main(): MOD = int(1e9 + 7) a = input() b = input() n = int(input()) ca, cb = 0,0 for i in range(len(a)): s = a[i:] + a[:i] if s == b: ca += 1 else: cb += 1 if ca == 0: print(0) return da = [0] * (n + 1) db = da[:] da[0] = 1 if a == b else 0 db[0] = 1 - da[0] for i in range(1, n + 1): da[i] = da[i - 1] * (ca - 1) + db[i - 1] * ca db[i] = da[i - 1] * cb + db[i - 1] * (cb - 1) da[i] %= MOD db[i] %= MOD # print(da[i], db[i], ca, cb) print(da[n]) return if __name__ == "__main__": main() ```
output
1
49,932
6
99,865
Provide tags and a correct Python 3 solution for this coding contest problem. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab
instruction
0
49,933
6
99,866
Tags: dp Correct Solution: ``` def WordCut(): start = input() end = input() k = int(input()) n=len(start) dpA,dpB = (start==end),(start!=end) end+=end A=sum(start==end[i:i+n] for i in range(n)) B = n- A M = 10**9+7 for _ in range(k): dpA,dpB=(dpA*(A-1)+dpB*A)%M,(dpA*B+dpB*(B-1))%M return int(dpA) print(WordCut()) ```
output
1
49,933
6
99,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab Submitted Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y from collections import deque for _ in range(int(input()) if not True else 1): #n = int(input()) #n, k = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #a = list(map(int, input().split())) #b = list(map(int, input().split())) s1 = deque(k for k in input()) s2 = deque(k for k in input()) n = len(s1) k = int(input()) if k == 0: print(int(s1==s2)) quit() mod = 10**9 + 7 n1pow = [1] for i in range(696969): n1pow += [(n1pow[-1]*(n-1)) % mod] ans0 = 0 for i in range(2, k+1): ans0 = (n1pow[i] - ans0) % mod ans1 = 1 for i in range(2, k+1): ans1 = (n1pow[i] - ans1) % mod #print(ans0, ans1) total = 0 for t in range(n): if s1 == s2: total += ans1 if t else ans0 s1.appendleft(s1.pop()) print(total % mod) ```
instruction
0
49,934
6
99,868
No
output
1
49,934
6
99,869
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab Submitted Solution: ``` # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code def main(): MOD = int(1e9 + 7) a = input() b = input() n = int(input()) ca, cb = 0,0 for i in range(len(a)): s = a[i:] + a[:i] if s == b: ca += 1 else: cb += 1 if ca == 0: print(0) return da = [0] * (n + 1) db = da[:] da[0] = 1 if a == b else 0 db[0] = 1 - da[0] for i in range(1, n + 1): da[i] = da[i - 1] * (ca - 1) da[i] += db[i - 1] * cb db[i] = da[i - 1] * ca if cb: db[i - 1] * (cb - 1) da[i] %= MOD db[i] %= MOD print(da[n]) return if __name__ == "__main__": main() ```
instruction
0
49,935
6
99,870
No
output
1
49,935
6
99,871
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab Submitted Solution: ``` # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code def main(): MOD = int(1e9 + 7) a = input() b = input() n = int(input()) ca, cb = 0,0 for i in range(len(a)): s = a[i:] + a[:i] if s == b: ca += 1 else: cb += 1 da = [0] * (n + 1) db = da[:] da[0] = 1 if a == b else 0 db[0] = 1 - da[0] for i in range(1, n + 1): da[i] = da[i - 1] * (ca - 1) + db[i - 1] * cb db[i] = da[i - 1] * ca + db[i - 1] * (cb - 1) da[i] %= MOD db[i] %= MOD print(da[n]) return if __name__ == "__main__": main() ```
instruction
0
49,936
6
99,872
No
output
1
49,936
6
99,873
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab Submitted Solution: ``` # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code def main(): MOD = int(1e9 + 7) a = input() b = input() n = int(input()) ca, cb = 0,0 for i in range(len(a)): s = a[i:] + a[:i] if s == b: ca += 1 else: cb += 1 if ca == 0: print(0) return da = [0] * (n + 1) db = da[:] da[0] = 1 if a == b else 0 db[0] = 1 - da[0] for i in range(1, n + 1): da[i] = da[i - 1] * (ca - 1) + db[i - 1] * cb db[i] = da[i - 1] * ca + db[i - 1] * (cb - 1) da[i] %= MOD db[i] %= MOD print(da[n]) return if __name__ == "__main__": main() ```
instruction
0
49,937
6
99,874
No
output
1
49,937
6
99,875
Provide tags and a correct Python 3 solution for this coding contest problem. There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: * <hostname> β€” server name (consists of words and maybe some dots separating them), * /<path> β€” optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β€” for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications. Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name. Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: * <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. * <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output First print k β€” the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. Examples Input 10 http://abacaba.ru/test http://abacaba.ru/ http://abacaba.com http://abacaba.com/test http://abacaba.de/ http://abacaba.ru/test http://abacaba.de/test http://abacaba.com/ http://abacaba.com/t http://abacaba.com/test Output 1 http://abacaba.de http://abacaba.ru Input 14 http://c http://ccc.bbbb/aba..b http://cba.com http://a.c/aba..b/a http://abc/ http://a.c/ http://ccc.bbbb http://ab.ac.bc.aa/ http://a.a.a/ http://ccc.bbbb/ http://cba.com/ http://cba.com/aba..b http://a.a.a/aba..b/a http://abc/aba..b/a Output 2 http://cba.com http://ccc.bbbb http://a.a.a http://a.c http://abc
instruction
0
50,095
6
100,190
Tags: *special, binary search, data structures, implementation, sortings, strings Correct Solution: ``` P = 910519 MOD = 32416190071 p = [1] for i in range(1, 200010): p.append((P * p[i - 1]) % MOD) n = int(input()) s = list(set([input() for i in range(n)])) n = len(s) name = ['' for i in range(n)] path = ['' for i in range(n)] mp = {} for i in range(n): link = s[i] j = link[7:].find('/') if j != -1: path[i] = link[j + 7:] name[i] = link[:j + 7] else: name[i] = link for i in range(n): if path[i] not in mp: mp[path[i]] = len(mp) h = {name[i] : 0 for i in range(n)} for i in range(n): h[name[i]] += p[mp[path[i]]] gp = {} for key, val in h.items(): if val in gp: gp[val].append(key) else: gp[val] = [key] ans = [] for key, val in gp.items(): if len(val) > 1: ans.append(val) print(len(ans)) for a in ans: print(' '.join(a)) ```
output
1
50,095
6
100,191
Provide tags and a correct Python 3 solution for this coding contest problem. There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: * <hostname> β€” server name (consists of words and maybe some dots separating them), * /<path> β€” optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β€” for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications. Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name. Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: * <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. * <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output First print k β€” the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. Examples Input 10 http://abacaba.ru/test http://abacaba.ru/ http://abacaba.com http://abacaba.com/test http://abacaba.de/ http://abacaba.ru/test http://abacaba.de/test http://abacaba.com/ http://abacaba.com/t http://abacaba.com/test Output 1 http://abacaba.de http://abacaba.ru Input 14 http://c http://ccc.bbbb/aba..b http://cba.com http://a.c/aba..b/a http://abc/ http://a.c/ http://ccc.bbbb http://ab.ac.bc.aa/ http://a.a.a/ http://ccc.bbbb/ http://cba.com/ http://cba.com/aba..b http://a.a.a/aba..b/a http://abc/aba..b/a Output 2 http://cba.com http://ccc.bbbb http://a.a.a http://a.c http://abc
instruction
0
50,096
6
100,192
Tags: *special, binary search, data structures, implementation, sortings, strings Correct Solution: ``` n=int(input()) d={}; D={}; ans=[] for _ in range(n): s=input()+'/'; t=s.find('/',7); d.setdefault(s[:t],set()).add(s[t:]) for k in d: D.setdefault(frozenset(d[k]),[]).append(k) [ans.append(D[k]) for k in D if len(D[k])>1] print(len(ans)) print('\n'.join(map(' '.join,ans))) ```
output
1
50,096
6
100,193
Provide tags and a correct Python 3 solution for this coding contest problem. There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: * <hostname> β€” server name (consists of words and maybe some dots separating them), * /<path> β€” optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β€” for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications. Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name. Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: * <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. * <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output First print k β€” the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. Examples Input 10 http://abacaba.ru/test http://abacaba.ru/ http://abacaba.com http://abacaba.com/test http://abacaba.de/ http://abacaba.ru/test http://abacaba.de/test http://abacaba.com/ http://abacaba.com/t http://abacaba.com/test Output 1 http://abacaba.de http://abacaba.ru Input 14 http://c http://ccc.bbbb/aba..b http://cba.com http://a.c/aba..b/a http://abc/ http://a.c/ http://ccc.bbbb http://ab.ac.bc.aa/ http://a.a.a/ http://ccc.bbbb/ http://cba.com/ http://cba.com/aba..b http://a.a.a/aba..b/a http://abc/aba..b/a Output 2 http://cba.com http://ccc.bbbb http://a.a.a http://a.c http://abc
instruction
0
50,097
6
100,194
Tags: *special, binary search, data structures, implementation, sortings, strings Correct Solution: ``` import sys from collections import defaultdict # sys.stdin = open("ivo.in") n = int(sys.stdin.readline()) h = defaultdict(set) for iter in range(n): entry = sys.stdin.readline().rstrip() + "/" path_start = 7 + entry[7:].index('/') hostname = entry[:path_start] path = entry[path_start:] h[hostname].add(path) res = defaultdict(list) for k, v in h.items(): res[frozenset(v)].append(k) output = [] for v in res.values(): if len(v) > 1: output.append(" ".join(v)) print(len(output)) for u in output: print(u) ```
output
1
50,097
6
100,195
Provide tags and a correct Python 3 solution for this coding contest problem. There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: * <hostname> β€” server name (consists of words and maybe some dots separating them), * /<path> β€” optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β€” for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications. Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name. Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: * <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. * <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output First print k β€” the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. Examples Input 10 http://abacaba.ru/test http://abacaba.ru/ http://abacaba.com http://abacaba.com/test http://abacaba.de/ http://abacaba.ru/test http://abacaba.de/test http://abacaba.com/ http://abacaba.com/t http://abacaba.com/test Output 1 http://abacaba.de http://abacaba.ru Input 14 http://c http://ccc.bbbb/aba..b http://cba.com http://a.c/aba..b/a http://abc/ http://a.c/ http://ccc.bbbb http://ab.ac.bc.aa/ http://a.a.a/ http://ccc.bbbb/ http://cba.com/ http://cba.com/aba..b http://a.a.a/aba..b/a http://abc/aba..b/a Output 2 http://cba.com http://ccc.bbbb http://a.a.a http://a.c http://abc
instruction
0
50,098
6
100,196
Tags: *special, binary search, data structures, implementation, sortings, strings Correct Solution: ``` n=int(input()) d={} D={} for i in range(n): h,*p=(input()[7:]+'/').split('/') d.setdefault(h,set()).add('/'.join(p)) for x in d: t=tuple(sorted(d[x])) D.setdefault(t,[]).append(x) def ans(): for x in D: if len(D[x])>1: yield 'http://'+' http://'.join(D[x]) print(sum(1 for x in D if len(D[x])>1)) print('\n'.join(ans())) ```
output
1
50,098
6
100,197
Provide tags and a correct Python 3 solution for this coding contest problem. There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: * <hostname> β€” server name (consists of words and maybe some dots separating them), * /<path> β€” optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β€” for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications. Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name. Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: * <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. * <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output First print k β€” the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. Examples Input 10 http://abacaba.ru/test http://abacaba.ru/ http://abacaba.com http://abacaba.com/test http://abacaba.de/ http://abacaba.ru/test http://abacaba.de/test http://abacaba.com/ http://abacaba.com/t http://abacaba.com/test Output 1 http://abacaba.de http://abacaba.ru Input 14 http://c http://ccc.bbbb/aba..b http://cba.com http://a.c/aba..b/a http://abc/ http://a.c/ http://ccc.bbbb http://ab.ac.bc.aa/ http://a.a.a/ http://ccc.bbbb/ http://cba.com/ http://cba.com/aba..b http://a.a.a/aba..b/a http://abc/aba..b/a Output 2 http://cba.com http://ccc.bbbb http://a.a.a http://a.c http://abc
instruction
0
50,099
6
100,198
Tags: *special, binary search, data structures, implementation, sortings, strings Correct Solution: ``` from itertools import groupby web_addresses_number = int(input()) prephix = "http://" def split_address(address): host = "" path = "" address = address[7:] i = 0 while i < len(address) and address[i] != '/': host += address[i] i += 1 while i < len(address): path += address[i] i += 1 return (host, path) hosts = {} for i in range(web_addresses_number): host, path = split_address(input()) if host in hosts: hosts[host].add(path) else: hosts[host] = {path} groups = [] hosts = {host:"+".join(sorted(hosts[host])) for host in hosts} groping = groupby(sorted(hosts, key = lambda host: hosts[host]), key = lambda host: hosts[host]) for key, group in groping: g = list(group) if len(g) > 1: groups.append(g) print(len(groups)) [print(" ".join(map(lambda host: prephix + host, group))) for group in groups] ```
output
1
50,099
6
100,199
Provide tags and a correct Python 3 solution for this coding contest problem. There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: * <hostname> β€” server name (consists of words and maybe some dots separating them), * /<path> β€” optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β€” for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications. Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name. Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: * <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. * <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output First print k β€” the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. Examples Input 10 http://abacaba.ru/test http://abacaba.ru/ http://abacaba.com http://abacaba.com/test http://abacaba.de/ http://abacaba.ru/test http://abacaba.de/test http://abacaba.com/ http://abacaba.com/t http://abacaba.com/test Output 1 http://abacaba.de http://abacaba.ru Input 14 http://c http://ccc.bbbb/aba..b http://cba.com http://a.c/aba..b/a http://abc/ http://a.c/ http://ccc.bbbb http://ab.ac.bc.aa/ http://a.a.a/ http://ccc.bbbb/ http://cba.com/ http://cba.com/aba..b http://a.a.a/aba..b/a http://abc/aba..b/a Output 2 http://cba.com http://ccc.bbbb http://a.a.a http://a.c http://abc
instruction
0
50,100
6
100,200
Tags: *special, binary search, data structures, implementation, sortings, strings Correct Solution: ``` import sys n = int(input()) domains = {} for full_request in sys.stdin: request = full_request[7:-1] domain, sep, path = request.partition('/') if domain in domains: domains[domain].add(sep + path) else: domains[domain] = {sep + path} path_hashes = [] for domain, paths in domains.items(): path_hashes.append(('|'.join(sorted(paths)), domain)) sorted_hashes = sorted(path_hashes, key=lambda x: x[0]) previous_hash = None previous_domains = [] groups = [] for path_hash, domain in sorted_hashes: if previous_hash == path_hash: previous_domains.append(domain) else: previous_hash = path_hash if len(previous_domains) > 1: groups.append(previous_domains) previous_domains = [domain] if len(previous_domains) > 1: groups.append(previous_domains) print(len(groups)) print('\n'.join(map(lambda x: ' '.join(map(lambda y: 'http://' + y, x)), groups))) ```
output
1
50,100
6
100,201
Provide tags and a correct Python 3 solution for this coding contest problem. There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: * <hostname> β€” server name (consists of words and maybe some dots separating them), * /<path> β€” optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β€” for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications. Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name. Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: * <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. * <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output First print k β€” the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. Examples Input 10 http://abacaba.ru/test http://abacaba.ru/ http://abacaba.com http://abacaba.com/test http://abacaba.de/ http://abacaba.ru/test http://abacaba.de/test http://abacaba.com/ http://abacaba.com/t http://abacaba.com/test Output 1 http://abacaba.de http://abacaba.ru Input 14 http://c http://ccc.bbbb/aba..b http://cba.com http://a.c/aba..b/a http://abc/ http://a.c/ http://ccc.bbbb http://ab.ac.bc.aa/ http://a.a.a/ http://ccc.bbbb/ http://cba.com/ http://cba.com/aba..b http://a.a.a/aba..b/a http://abc/aba..b/a Output 2 http://cba.com http://ccc.bbbb http://a.a.a http://a.c http://abc
instruction
0
50,101
6
100,202
Tags: *special, binary search, data structures, implementation, sortings, strings Correct Solution: ``` n=int(input()) d={} D={} for i in range(n): h,*p=(input()[7:]+'/').split('/') d.setdefault(h,set()).add('/'.join(p)) for x in d: D.setdefault(frozenset(d[x]),[]).append(x) def ans(): for x in D: if len(D[x])>1: yield 'http://'+' http://'.join(D[x]) print(sum(1 for x in D if len(D[x])>1)) print('\n'.join(ans())) ```
output
1
50,101
6
100,203
Provide tags and a correct Python 3 solution for this coding contest problem. There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: * <hostname> β€” server name (consists of words and maybe some dots separating them), * /<path> β€” optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β€” for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications. Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name. Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different. Input The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: * <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. * <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output First print k β€” the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. Examples Input 10 http://abacaba.ru/test http://abacaba.ru/ http://abacaba.com http://abacaba.com/test http://abacaba.de/ http://abacaba.ru/test http://abacaba.de/test http://abacaba.com/ http://abacaba.com/t http://abacaba.com/test Output 1 http://abacaba.de http://abacaba.ru Input 14 http://c http://ccc.bbbb/aba..b http://cba.com http://a.c/aba..b/a http://abc/ http://a.c/ http://ccc.bbbb http://ab.ac.bc.aa/ http://a.a.a/ http://ccc.bbbb/ http://cba.com/ http://cba.com/aba..b http://a.a.a/aba..b/a http://abc/aba..b/a Output 2 http://cba.com http://ccc.bbbb http://a.a.a http://a.c http://abc
instruction
0
50,102
6
100,204
Tags: *special, binary search, data structures, implementation, sortings, strings Correct Solution: ``` import sys d = dict() b='/' for line in sys.stdin: line=line[:-1].split(b) host,coso=b.join(line[:3]), b.join(line[3:]) if len(line)>3: coso='/'+coso if len(line)>1: if host in d: d[host].append("I"+coso) else: d[host]=["I"+coso] for host in d: b = ',' d[host]=sorted(set(d[host])) d[host]=b.join(d[host]) d2=dict() for host in d: if d[host] in d2: d2[d[host]].append(host) else: d2[d[host]]=[host] print (sum([len(d2[x])>1 for x in d2])) for x in d2: ans = "" if len(d2[x])>1: for i in d2[x]: ans+=i+' ' print (ans) ```
output
1
50,102
6
100,205
Provide tags and a correct Python 3 solution for this coding contest problem. You have recently fallen through a hole and, after several hours of unconsciousness, have realized you are in an underground city. On one of your regular, daily walks through the unknown, you have encountered two unusually looking skeletons called Sanz and P’pairus, who decided to accompany you and give you some puzzles for seemingly unknown reasons. One day, Sanz has created a crossword for you. Not any kind of crossword, but a 1D crossword! You are given m words and a string of length n. You are also given an array p, which designates how much each word is worth β€” the i-th word is worth pi points. Whenever you find one of the m words in the string, you are given the corresponding number of points. Each position in the crossword can be used at most x times. A certain word can be counted at different places, but you cannot count the same appearance of a word multiple times. If a word is a substring of another word, you can count them both (presuming you haven’t used the positions more than x times). In order to solve the puzzle, you need to tell Sanz what’s the maximum achievable number of points in the crossword. There is no need to cover all postions, just get the maximal score! Crossword and words contain only lowercase English letters. Input The first line of the input contains a single integer n (1 ≀ n ≀ 500) β€” the length of the crossword. The second line contains the crossword string. The third line contains a single integer m (1 ≀ m ≀ 100) β€” the number of given words, and next m lines contain description of words: each line will have a string representing a non-empty word (its length doesn't exceed the length of the crossword) and integer pi (0 ≀ pi ≀ 100). Last line of the input will contain x (1 ≀ x ≀ 100) β€” maximum number of times a position in crossword can be used. Output Output single integer β€” maximum number of points you can get. Example Input 6 abacba 2 aba 6 ba 3 3 Output 12 Note For example, with the string "abacba", words "aba" (6 points) and "ba" (3 points), and x = 3, you can get at most 12 points - the word "aba" appears once ("abacba"), while "ba" appears two times ("abacba"). Note that for x = 1, you could get at most 9 points, since you wouldn’t be able to count both "aba" and the first appearance of "ba".
instruction
0
50,113
6
100,226
Tags: flows Correct Solution: ``` import sys from heapq import heappop, heappush class Edge: def __init__(self, u, v, cap, flow, cost, rev) -> None: self.u = u self.v = v self.cap = cap self.flow = flow self.cost = cost self.rev = rev def add_edge(adj, u, v, capv, flowv, costv): if u == 6 and v == 7: foo = 0 adj[u].append(Edge(u, v, capv, flowv, costv, len(adj[v]))) adj[v].append(Edge(v, u, 0, flowv, -costv, len(adj[u])-1)) def match(crossword, cw_idx, word): for k in range(len(word)): if crossword[cw_idx + k] != word[k]: return False return True def read_input(): ''' 6 abacba 5 aba 6 ba 3 bac 4 cb 3 c 6 2 ''' n = int(sys.stdin.readline()) # n = int('6\n') crossword = sys.stdin.readline()[:-1] # crossword = 'abacba\n'[:-1] m = int(sys.stdin.readline()) # m = int('5\n') adj = [[] for _ in range(n+2)] # foo m_words = ["aba 6\n", "ba 3\n", "bac 4\n", "cb 3\n", "c 6"] # print(len(cost)) for idx in range(m): word, p = sys.stdin.readline().split() # word, p = m_words[idx].split() p = int(p) i = 0 while i + len(word) <= n: if match(crossword, i, word): u, v = i + 1, i + 1 + len(word) # print((u, v)) add_edge(adj, u, v, 1, 0, -p) i += 1 x = int(sys.stdin.readline()) # x = int('2\n') for i in range(n + 1): u, v = i, i + 1 # print((u, v)) add_edge(adj, u, v, x, 0, 0) return adj def bellman_ford(adj, potencial): for _ in range(len(adj)): for u in range(len(adj)): for e in adj[u]: reduced_cost = potencial[e.u] + e.cost - potencial[e.v] if e.cap > 0 and reduced_cost < 0: potencial[e.v] += reduced_cost def dijkstra(adj, potencial, dist, pi, s, t): oo = float('inf') for u in range(len(adj)): dist[u] = +oo pi[u] = None dist[s] = 0 heap = [(0, s)] while heap: du, u = heappop(heap) if dist[u] < du: continue if u == t: break for e in adj[u]: reduced_cost = potencial[e.u] + e.cost - potencial[e.v] if e.flow < e.cap and dist[e.v] > dist[e.u] + reduced_cost: dist[e.v] = dist[e.u] + reduced_cost heappush(heap, (dist[e.v], e.v)) pi[e.v] = e def min_cost_max_flow(adj): min_cost, max_flow = 0, 0 potencial, oo = [0] * len(adj), float('inf') dist, pi = [+oo] * len(adj), [None] * len(adj) bellman_ford(adj, potencial) s, t = 0, len(adj) - 1 while True: dijkstra(adj, potencial, dist, pi, s, t) if dist[t] == +oo: break for u in range(len(adj)): if dist[u] < dist[t]: potencial[u] += dist[u] - dist[t] limit, v = +oo, t while v: e = pi[v] limit = min(limit, e.cap - e.flow) v = e.u v = t while v: e = pi[v] e.flow += limit try: adj[v][e.rev].flow -= limit except: adj[v][e.rev].flow -= limit v = e.u min_cost += limit * (potencial[t] - potencial[s]) max_flow += limit # path = [] # v = t # while v: # path.append(v) # v = pi[v] # path.reverse() # print(path) return min_cost, max_flow adj = read_input() # print({ # 'len(adj)': len(adj), # 'len(cap)': len(cap), # 'len(cost)': len(cost) # }) # print({ 'adj': adj}) # print({ 'cap': cap}) # print({ 'cost': cost}) min_cost, _ = min_cost_max_flow(adj) print(-min_cost) ```
output
1
50,113
6
100,227
Provide tags and a correct Python 3 solution for this coding contest problem. You have recently fallen through a hole and, after several hours of unconsciousness, have realized you are in an underground city. On one of your regular, daily walks through the unknown, you have encountered two unusually looking skeletons called Sanz and P’pairus, who decided to accompany you and give you some puzzles for seemingly unknown reasons. One day, Sanz has created a crossword for you. Not any kind of crossword, but a 1D crossword! You are given m words and a string of length n. You are also given an array p, which designates how much each word is worth β€” the i-th word is worth pi points. Whenever you find one of the m words in the string, you are given the corresponding number of points. Each position in the crossword can be used at most x times. A certain word can be counted at different places, but you cannot count the same appearance of a word multiple times. If a word is a substring of another word, you can count them both (presuming you haven’t used the positions more than x times). In order to solve the puzzle, you need to tell Sanz what’s the maximum achievable number of points in the crossword. There is no need to cover all postions, just get the maximal score! Crossword and words contain only lowercase English letters. Input The first line of the input contains a single integer n (1 ≀ n ≀ 500) β€” the length of the crossword. The second line contains the crossword string. The third line contains a single integer m (1 ≀ m ≀ 100) β€” the number of given words, and next m lines contain description of words: each line will have a string representing a non-empty word (its length doesn't exceed the length of the crossword) and integer pi (0 ≀ pi ≀ 100). Last line of the input will contain x (1 ≀ x ≀ 100) β€” maximum number of times a position in crossword can be used. Output Output single integer β€” maximum number of points you can get. Example Input 6 abacba 2 aba 6 ba 3 3 Output 12 Note For example, with the string "abacba", words "aba" (6 points) and "ba" (3 points), and x = 3, you can get at most 12 points - the word "aba" appears once ("abacba"), while "ba" appears two times ("abacba"). Note that for x = 1, you could get at most 9 points, since you wouldn’t be able to count both "aba" and the first appearance of "ba".
instruction
0
50,114
6
100,228
Tags: flows Correct Solution: ``` import sys from heapq import heappop, heappush class Edge: def __init__(self, u, v, cap, flow, cost, rev) -> None: self.u = u self.v = v self.cap = cap self.flow = flow self.cost = cost self.rev = rev def add_edge(adj, u, v, capv, flowv, costv): if u == 6 and v == 7: foo = 0 adj[u].append(Edge(u, v, capv, flowv, costv, len(adj[v]))) adj[v].append(Edge(v, u, 0, flowv, -costv, len(adj[u])-1)) def match(crossword, cw_idx, word): for k in range(len(word)): if crossword[cw_idx + k] != word[k]: return False return True def read_input(): ''' 6 abacba 5 aba 6 ba 3 bac 4 cb 3 c 6 2 ''' n = int(sys.stdin.readline()) # n = int('6\n') crossword = sys.stdin.readline()[:-1] # crossword = 'abacba\n'[:-1] m = int(sys.stdin.readline()) # m = int('5\n') adj = [[] for _ in range(n+2)] # foo m_words = ["aba 6\n", "ba 3\n", "bac 4\n", "cb 3\n", "c 6"] # print(len(cost)) for idx in range(m): word, p = sys.stdin.readline().split() # word, p = m_words[idx].split() p = int(p) i = 0 while i + len(word) <= n: if match(crossword, i, word): u, v = i + 1, i + 1 + len(word) # print((u, v)) add_edge(adj, u, v, 1, 0, -p) i += 1 x = int(sys.stdin.readline()) # x = int('2\n') for i in range(n + 1): u, v = i, i + 1 # print((u, v)) add_edge(adj, u, v, x, 0, 0) return adj def bellman_ford(adj, potencial): for _ in range(len(adj)): for u in range(len(adj)): for e in adj[u]: reduced_cost = potencial[e.u] + e.cost - potencial[e.v] if e.cap > 0 and reduced_cost < 0: potencial[e.v] += reduced_cost def dijkstra(adj, potencial, dist, pi, s, t): oo = float('inf') for u in range(len(adj)): dist[u] = +oo pi[u] = None dist[s] = 0 heap = [(0, s)] while heap: du, u = heappop(heap) if dist[u] < du: continue if u == t: break for e in adj[u]: reduced_cost = potencial[e.u] + e.cost - potencial[e.v] if e.flow < e.cap and dist[e.v] > dist[e.u] + reduced_cost: dist[e.v] = dist[e.u] + reduced_cost heappush(heap, (dist[e.v], e.v)) pi[e.v] = e def min_cost_max_flow(adj): min_cost, max_flow = 0, 0 potencial, oo = [0] * len(adj), float('inf') dist, pi = [+oo] * len(adj), [None] * len(adj) bellman_ford(adj, potencial) s, t = 0, len(adj) - 1 while True: dijkstra(adj, potencial, dist, pi, s, t) if dist[t] == +oo: break for u in range(len(adj)): if dist[u] < dist[t]: potencial[u] += dist[u] - dist[t] limit, v = +oo, t while v: e = pi[v] limit = min(limit, e.cap - e.flow) v = e.u v = t while v: e = pi[v] e.flow += limit try: adj[v][e.rev].flow -= limit except: adj[v][e.rev].flow -= limit v = e.u min_cost += limit * (potencial[t] - potencial[s]) max_flow += limit # path = [] # v = t # while v: # path.append(v) # v = pi[v].u # path.reverse() # print(path) return min_cost, max_flow adj = read_input() # print({ # 'len(adj)': len(adj), # 'len(cap)': len(cap), # 'len(cost)': len(cost) # }) # print({ 'adj': adj}) # print({ 'cap': cap}) # print({ 'cost': cost}) min_cost, _ = min_cost_max_flow(adj) print(-min_cost) ```
output
1
50,114
6
100,229
Provide tags and a correct Python 3 solution for this coding contest problem. You have recently fallen through a hole and, after several hours of unconsciousness, have realized you are in an underground city. On one of your regular, daily walks through the unknown, you have encountered two unusually looking skeletons called Sanz and P’pairus, who decided to accompany you and give you some puzzles for seemingly unknown reasons. One day, Sanz has created a crossword for you. Not any kind of crossword, but a 1D crossword! You are given m words and a string of length n. You are also given an array p, which designates how much each word is worth β€” the i-th word is worth pi points. Whenever you find one of the m words in the string, you are given the corresponding number of points. Each position in the crossword can be used at most x times. A certain word can be counted at different places, but you cannot count the same appearance of a word multiple times. If a word is a substring of another word, you can count them both (presuming you haven’t used the positions more than x times). In order to solve the puzzle, you need to tell Sanz what’s the maximum achievable number of points in the crossword. There is no need to cover all postions, just get the maximal score! Crossword and words contain only lowercase English letters. Input The first line of the input contains a single integer n (1 ≀ n ≀ 500) β€” the length of the crossword. The second line contains the crossword string. The third line contains a single integer m (1 ≀ m ≀ 100) β€” the number of given words, and next m lines contain description of words: each line will have a string representing a non-empty word (its length doesn't exceed the length of the crossword) and integer pi (0 ≀ pi ≀ 100). Last line of the input will contain x (1 ≀ x ≀ 100) β€” maximum number of times a position in crossword can be used. Output Output single integer β€” maximum number of points you can get. Example Input 6 abacba 2 aba 6 ba 3 3 Output 12 Note For example, with the string "abacba", words "aba" (6 points) and "ba" (3 points), and x = 3, you can get at most 12 points - the word "aba" appears once ("abacba"), while "ba" appears two times ("abacba"). Note that for x = 1, you could get at most 9 points, since you wouldn’t be able to count both "aba" and the first appearance of "ba".
instruction
0
50,115
6
100,230
Tags: flows Correct Solution: ``` import sys from heapq import heappop, heappush class Edge: def __init__(self, u, v, cap, flow, cost, rev): self.u = u self.v = v self.cap = cap self.flow = flow self.cost = cost self.rev = rev def add_edge(adj, u, v, capv, flowv, costv): adj[u].append(Edge(u, v, capv, flowv, costv, len(adj[v]))) adj[v].append(Edge(v, u, 0, flowv, -costv, len(adj[u])-1)) def match(crossword, cw_idx, word): for k in range(len(word)): if crossword[cw_idx + k] != word[k]: return False return True def read_input(): n = int(sys.stdin.readline()) crossword = sys.stdin.readline()[:-1] m = int(sys.stdin.readline()) adj = [[] for _ in range(n+2)] for _ in range(m): word, p = sys.stdin.readline().split() p = int(p) i = 0 while i + len(word) <= n: if match(crossword, i, word): u, v = i + 1, i + 1 + len(word) add_edge(adj, u, v, 1, 0, -p) i += 1 x = int(sys.stdin.readline()) for i in range(n + 1): u, v = i, i + 1 add_edge(adj, u, v, x, 0, 0) return adj def bellman_ford(adj): potential = [0] * len(adj) for _ in range(len(adj)): for u in range(len(adj)): for e in adj[u]: reduced_cost = potential[e.u] + e.cost - potential[e.v] if e.cap > 0 and reduced_cost < 0: potential[e.v] += reduced_cost return potential def dijkstra(adj, potential, s, t): oo = float('inf') dist, pi = [+oo] * len(adj), [None] * len(adj) dist[s] = 0 heap = [(0, s)] while heap: du, u = heappop(heap) if dist[u] < du: continue if u == t: break for e in adj[u]: reduced_cost = potential[e.u] + e.cost - potential[e.v] if e.cap - e.flow > 0 and dist[e.v] > dist[e.u] + reduced_cost: dist[e.v] = dist[e.u] + reduced_cost heappush(heap, (dist[e.v], e.v)) pi[e.v] = e return dist, pi def min_cost_max_flow(adj): min_cost, max_flow = 0, 0 oo = float('inf') potential = bellman_ford(adj) s, t = 0, len(adj) - 1 while True: dist, pi = dijkstra(adj, potential, s, t) if dist[t] == +oo: break for u in range(len(adj)): if dist[u] < dist[t]: potential[u] += dist[u] - dist[t] limit, v = +oo, t while v: e = pi[v] limit = min(limit, e.cap - e.flow) v = e.u v = t while v: e = pi[v] e.flow += limit adj[v][e.rev].flow -= limit v = e.u min_cost += limit * (potential[t] - potential[s]) max_flow += limit return min_cost, max_flow adj = read_input() min_cost, _ = min_cost_max_flow(adj) print(-min_cost) ```
output
1
50,115
6
100,231
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language. Input This program has only one test, and it's empty (it doesn't give your program anything to read). Output Output the name of the mysterious language. Examples
instruction
0
50,750
6
101,500
Tags: *special Correct Solution: ``` print('INTERCAL') ```
output
1
50,750
6
101,501
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language. Input This program has only one test, and it's empty (it doesn't give your program anything to read). Output Output the name of the mysterious language. Examples
instruction
0
50,751
6
101,502
Tags: *special Correct Solution: ``` #!/usr/bin/env python from __future__ import division, print_function import math import os import sys from fractions import * from sys import * from io import BytesIO, IOBase from itertools import * from collections import * # sys.setrecursionlimit(10**5) if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip # sys.setrecursionlimit(10**6) # 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def out(var): sys.stdout.write(str(var)) # for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) def fsep(): return map(float, inp().split()) def inpu(): return int(inp()) # ----------------------------------------------------------------- def regularbracket(t): p = 0 for i in t: if i == "(": p += 1 else: p -= 1 if p < 0: return False else: if p > 0: return False else: return True # ------------------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <= key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # ------------------------------reverse string(pallindrome) def reverse1(string): pp = "" for i in string[::-1]: pp += i if pp == string: return True return False # --------------------------------reverse list(paindrome) def reverse2(list1): l = [] for i in list1[::-1]: l.append(i) if l == list1: return True return False def mex(list1): # list1 = sorted(list1) p = max(list1) + 1 for i in range(len(list1)): if list1[i] != i: p = i break return p def sumofdigits(n): n = str(n) s1 = 0 for i in n: s1 += int(i) return s1 def perfect_square(n): s = math.sqrt(n) if s == int(s): return True return False # -----------------------------roman def roman_number(x): if x > 15999: return value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] symbol = ["F", "MF", "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] roman = "" i = 0 while x > 0: div = x // value[i] x = x % value[i] while div: roman += symbol[i] div -= 1 i += 1 return roman def soretd(s): for i in range(1, len(s)): if s[i - 1] > s[i]: return False return True # print(soretd("1")) # --------------------------- def countRhombi(h, w): ct = 0 for i in range(2, h + 1, 2): for j in range(2, w + 1, 2): ct += (h - i + 1) * (w - j + 1) return ct def countrhombi2(h, w): return ((h * h) // 4) * ((w * w) // 4) # --------------------------------- def binpow(a, b): if b == 0: return 1 else: res = binpow(a, b // 2) if b % 2 != 0: return res * res * a else: return res * res # ------------------------------------------------------- def binpowmodulus(a, b, m): a %= m res = 1 while (b > 0): if (b & 1): res = res * a % m a = a * a % m b >>= 1 return res # ------------------------------------------------------------- def coprime_to_n(n): result = n i = 2 while (i * i <= n): if (n % i == 0): while (n % i == 0): n //= i result -= result // i i += 1 if (n > 1): result -= result // n return result # -------------------prime def prime(x): if x == 1: return False else: for i in range(2, int(math.sqrt(x)) + 1): if (x % i == 0): return False else: return True def luckynumwithequalnumberoffourandseven(x, n, a): if x >= n and str(x).count("4") == str(x).count("7"): a.append(x) else: if x < 1e12: luckynumwithequalnumberoffourandseven(x * 10 + 4, n, a) luckynumwithequalnumberoffourandseven(x * 10 + 7, n, a) return a def luckynuber(x, n, a): p = set(str(x)) if len(p) <= 2: a.append(x) if x < n: luckynuber(x + 1, n, a) return a #------------------------------------------------------interactive problems def interact(type, x): if type == "r": inp = input() return inp.strip() else: print(x, flush=True) #------------------------------------------------------------------zero at end of factorial of a number def findTrailingZeros(n): # Initialize result count = 0 # Keep dividing n by # 5 & update Count while (n >= 5): n //= 5 count += n return count #-----------------------------------------------merge sort # Python program for implementation of MergeSort def mergeSort(arr): if len(arr) > 1: # Finding the mid of the array mid = len(arr) // 2 # Dividing the array elements L = arr[:mid] # into 2 halves R = arr[mid:] # Sorting the first half mergeSort(L) # Sorting the second half mergeSort(R) i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 #-----------------------------------------------lucky number with two lucky any digits res = set() def solve(p, l, a, b,n):#given number if p > n or l > 10: return if p > 0: res.add(p) solve(p * 10 + a, l + 1, a, b,n) solve(p * 10 + b, l + 1, a, b,n) # problem """ n = int(input()) for a in range(0, 10): for b in range(0, a): solve(0, 0) print(len(res)) """ #----------------------------------------------- # endregion------------------------------ """ def main(): n = inpu() cnt=0 c = n if n % 7 == 0: print("7" * (n // 7)) else: while(c>0): c-=4 cnt+=1 if c%7==0 and c>=0: #print(n,n%4) print("4"*(cnt)+"7"*(c//7)) break else: if n % 4 == 0: print("4" * (n // 4)) else: print(-1) if __name__ == '__main__': main() """ """ def main(): n,t = sep() arr = lis() i=0 cnt=0 min1 = min(arr) while(True): if t>=arr[i]: cnt+=1 t-=arr[i] i+=1 else: i+=1 if i==n: i=0 if t<min1: break print(cnt) if __name__ == '__main__': main() """ # Python3 program to find all subsets # by backtracking. # In the array A at every step we have two # choices for each element either we can # ignore the element or we can include the # element in our subset def subsetsUtil(A, subset, index,d): print(*subset) s = sum(subset) d.append(s) for i in range(index, len(A)): # include the A[i] in subset. subset.append(A[i]) # move onto the next element. subsetsUtil(A, subset, i + 1,d) # exclude the A[i] from subset and # triggers backtracking. subset.pop(-1) return d def subsetSums(arr, l, r,d, sum=0): if l > r: d.append(sum) return subsetSums(arr, l + 1, r,d, sum + arr[l]) # Subset excluding arr[l] subsetSums(arr, l + 1, r,d, sum) return d """ def main(): t = inpu() for _ in range(t): n = inpu() arr=[] subset=[] i=0 l=[] for j in range(26): arr.append(3**j) if __name__ == '__main__': main() """ """ def main(): n = int(input()) cnt=1 if n==1: print(1) else: for i in range(1,n): cnt+=i*12 print(cnt) if __name__ == '__main__': main() """ def main(): print("INTERCAL") if __name__ == '__main__': main() ```
output
1
50,751
6
101,503
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language. Input This program has only one test, and it's empty (it doesn't give your program anything to read). Output Output the name of the mysterious language. Examples
instruction
0
50,752
6
101,504
Tags: *special Correct Solution: ``` """==================================================================================== ==================================================================================== ___ _______ ___ _______ ___ ___ | /\ | | \ | | / | | | | |\ /| | / \ | | \ | | / | | | | | \ / | |___ /____\ | | \ | |/ |___| | | | \/ | | / \ | | / | |\ |\ | | | | | / \ | | / | | \ | \ | | | | ___|/ \___|___ |___/ ___|___ | \ | \ |___| | | ==================================================================================== ==================================================================================== """ # β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯ print("INTERCAL") # β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯β™₯ """==================================================================================== ==================================================================================== ___ _______ ___ _______ ___ ___ | /\ | | \ | | / | | | | |\ /| | / \ | | \ | | / | | | | | \ / | |___ /____\ | | \ | |/ |___| | | | \/ | | / \ | | / | |\ |\ | | | | | / \ | | / | | \ | \ | | | | ___|/ \___|___ |___/ ___|___ | \ | \ |___| | | ==================================================================================== ==================================================================================== """ ```
output
1
50,752
6
101,505
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language. Input This program has only one test, and it's empty (it doesn't give your program anything to read). Output Output the name of the mysterious language. Examples
instruction
0
50,753
6
101,506
Tags: *special Correct Solution: ``` n=input();print("INTERCAL") ```
output
1
50,753
6
101,507
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language. Input This program has only one test, and it's empty (it doesn't give your program anything to read). Output Output the name of the mysterious language. Examples
instruction
0
50,754
6
101,508
Tags: *special Correct Solution: ``` n=input() print("INTERCAL") ```
output
1
50,754
6
101,509
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language. Input This program has only one test, and it's empty (it doesn't give your program anything to read). Output Output the name of the mysterious language. Examples
instruction
0
50,755
6
101,510
Tags: *special Correct Solution: ``` #Fun.... print('INTERCAL') ```
output
1
50,755
6
101,511
Provide tags and a correct Python 3 solution for this coding contest problem. Little penguin Polo adores strings. But most of all he adores strings of length n. One day he wanted to find a string that meets the following conditions: 1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. 2. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si β‰  si + 1(1 ≀ i < n). 3. Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist. String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes. Input A single line contains two positive integers n and k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26) β€” the string's length and the number of distinct letters. Output In a single line print the required string. If there isn't such string, print "-1" (without the quotes). Examples Input 7 4 Output ababacd Input 4 7 Output -1
instruction
0
50,792
6
101,584
Tags: greedy Correct Solution: ``` def main(): n, k = map(int, input().split()) if n < k or k == 1 < n: print(-1) elif (n - k) & 1: print('ab' * ((n - k + 1) // 2) + 'acdefghijklmnopqrstuvwxyz'[:k - 1]) else: print('ab' * ((n - k) // 2) + 'abcdefghijklmnopqrstuvwxyz'[:k]) if __name__ == '__main__': main() ```
output
1
50,792
6
101,585
Provide tags and a correct Python 3 solution for this coding contest problem. Little penguin Polo adores strings. But most of all he adores strings of length n. One day he wanted to find a string that meets the following conditions: 1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. 2. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si β‰  si + 1(1 ≀ i < n). 3. Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist. String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes. Input A single line contains two positive integers n and k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26) β€” the string's length and the number of distinct letters. Output In a single line print the required string. If there isn't such string, print "-1" (without the quotes). Examples Input 7 4 Output ababacd Input 4 7 Output -1
instruction
0
50,794
6
101,588
Tags: greedy Correct Solution: ``` n,k=map(int,input().split()) if k>n: print(-1) elif n==1 and k==1: print("a") elif k==1: print(-1) else: ans="" k=k-2 n=n-k z=99 if n%2==0: ans+="ab"*(n//2) while(k>0): ans+=chr(z) z+=1 k-=1 else: x=99 ans+="ab"*(n//2) ans+="a" while(k>0): ans += chr(x) x+= 1 k-=1 print(ans) ```
output
1
50,794
6
101,589
Provide tags and a correct Python 3 solution for this coding contest problem. You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. Input First line contains an integer n (6 ≀ n ≀ 8) – the length of the string. Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). Output Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). Examples Input 7 j...... Output jolteon Input 7 ...feon Output leafeon Input 7 .l.r.o. Output flareon Note Here's a set of names in a form you can paste into your solution: ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}
instruction
0
50,862
6
101,724
Tags: brute force, implementation, strings Correct Solution: ``` n = int(input()) s = input() l = ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] for given in l: if len(given) != len(s): continue istrue = 1 for i in range(0, n): if given[i] != s[i] and s[i] != '.': istrue = 0 break if (istrue): print (given) ```
output
1
50,862
6
101,725
Provide tags and a correct Python 3 solution for this coding contest problem. You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. Input First line contains an integer n (6 ≀ n ≀ 8) – the length of the string. Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). Output Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). Examples Input 7 j...... Output jolteon Input 7 ...feon Output leafeon Input 7 .l.r.o. Output flareon Note Here's a set of names in a form you can paste into your solution: ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}
instruction
0
50,863
6
101,726
Tags: brute force, implementation, strings Correct Solution: ``` '''input 7 .l.r.o. ''' n = int(input()) s = input() l = [i for i in ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] if len(i) == n] for x in l: for y in range(n): if all(s[y] == x[y] for y in range(n) if s[y] != "."): print(x) break ```
output
1
50,863
6
101,727
Provide tags and a correct Python 3 solution for this coding contest problem. You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. Input First line contains an integer n (6 ≀ n ≀ 8) – the length of the string. Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). Output Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). Examples Input 7 j...... Output jolteon Input 7 ...feon Output leafeon Input 7 .l.r.o. Output flareon Note Here's a set of names in a form you can paste into your solution: ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}
instruction
0
50,864
6
101,728
Tags: brute force, implementation, strings Correct Solution: ``` n = int(input()) s = input() a = ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] for i in a: if (len(i) != len(s)): continue b = True for j in range(len(s)): if (s[j] != '.' and i[j] != '.' and s[j] != i[j]): b = False if b: print(i) exit(0) ```
output
1
50,864
6
101,729
Provide tags and a correct Python 3 solution for this coding contest problem. You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. Input First line contains an integer n (6 ≀ n ≀ 8) – the length of the string. Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). Output Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). Examples Input 7 j...... Output jolteon Input 7 ...feon Output leafeon Input 7 .l.r.o. Output flareon Note Here's a set of names in a form you can paste into your solution: ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}
instruction
0
50,865
6
101,730
Tags: brute force, implementation, strings Correct Solution: ``` #!/usr/bin/env python3 import re def main(): input() p = re.compile(input()) pokemons = ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] pokemons = sorted(pokemons, key=len) for x in pokemons: if p.match(x): print(x) break if __name__ == '__main__': main() ```
output
1
50,865
6
101,731
Provide tags and a correct Python 3 solution for this coding contest problem. You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. Input First line contains an integer n (6 ≀ n ≀ 8) – the length of the string. Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). Output Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). Examples Input 7 j...... Output jolteon Input 7 ...feon Output leafeon Input 7 .l.r.o. Output flareon Note Here's a set of names in a form you can paste into your solution: ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}
instruction
0
50,866
6
101,732
Tags: brute force, implementation, strings Correct Solution: ``` l_6 = ["espeon"] l_7 = ["jolteon", "flareon", "umbreon", "leafeon", "glaceon", "sylveon"] l_8 = ["vaporeon"] input_length = input() input_string = input() if input_length == "6": print(l_6[0]) elif input_length == "8": print(l_8[0]) else: for x in l_7: for y in range(0,7): if(input_string[y] != '.' and input_string[y] != x[y]): break if (y == 6): print(x) ```
output
1
50,866
6
101,733
Provide tags and a correct Python 3 solution for this coding contest problem. You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. Input First line contains an integer n (6 ≀ n ≀ 8) – the length of the string. Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). Output Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). Examples Input 7 j...... Output jolteon Input 7 ...feon Output leafeon Input 7 .l.r.o. Output flareon Note Here's a set of names in a form you can paste into your solution: ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}
instruction
0
50,867
6
101,734
Tags: brute force, implementation, strings Correct Solution: ``` def match(s, p): if len(s) != len(p): return False for chs, chp in zip(s, p): if chs != '.' and chs != chp: return False return True n = int(input()) s = input() for p in ['vaporeon', 'jolteon', 'flareon', 'espeon', 'umbreon', 'leafeon', 'glaceon', 'sylveon'\ ]: if match(s, p): print(p) ```
output
1
50,867
6
101,735
Provide tags and a correct Python 3 solution for this coding contest problem. You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. Input First line contains an integer n (6 ≀ n ≀ 8) – the length of the string. Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). Output Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). Examples Input 7 j...... Output jolteon Input 7 ...feon Output leafeon Input 7 .l.r.o. Output flareon Note Here's a set of names in a form you can paste into your solution: ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}
instruction
0
50,868
6
101,736
Tags: brute force, implementation, strings Correct Solution: ``` import sys def get_single_int (): return int (sys.stdin.readline ().strip ()) def get_string (): return sys.stdin.readline ().strip () def get_ints (): return map (int, sys.stdin.readline ().strip ().split ()) def get_list (): return list (map (int, sys.stdin.readline ().strip ().split ())) #code starts here def unique (n) : if n == 8: print ("vaporeon") else: print ("espeon") def same (names): for j in names: if j [i] != s [i]: try: names_copy.remove (j) except: continue n = get_single_int () s = get_string () names = [ "jolteon", "flareon", "umbreon", "leafeon", "glaceon", "sylveon"] names_copy = [ "jolteon", "flareon", "umbreon", "leafeon", "glaceon", "sylveon"] if (n == 6 or n == 8): unique (n) else : for i in range (7): if s [i] == '.': continue else: same (names) print (names_copy [0]) ```
output
1
50,868
6
101,737
Provide tags and a correct Python 3 solution for this coding contest problem. You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. Input First line contains an integer n (6 ≀ n ≀ 8) – the length of the string. Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). Output Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). Examples Input 7 j...... Output jolteon Input 7 ...feon Output leafeon Input 7 .l.r.o. Output flareon Note Here's a set of names in a form you can paste into your solution: ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}
instruction
0
50,869
6
101,738
Tags: brute force, implementation, strings Correct Solution: ``` def prov(s2): global s1 if len(s1)!=len(s2): return False for i in range(len(s1)): if s1[i]!=s2[i] and s1[i]!='.': return False print(s2) exit(0) n=int(input()) s1=input().strip() b=["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] for i in b: prov(i) ```
output
1
50,869
6
101,739
Provide a correct Python 3 solution for this coding contest problem. Boolean Expression Compressor You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning. The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule: > <E> ::= `0` | `1` | `a` | `b` | `c` | `d` | `-`<E> | `(`<E>`^`<E>`)` | `(`<E>`*`<E>`)` Letters `a`, `b`, `c` and `d` represent Boolean variables that have values of either `0` or `1`. Operators are evaluated as shown in the Table below. In other words, `-` means negation (NOT), `^` means exclusive disjunction (XOR), and `*` means logical conjunction (AND). Table: Evaluations of operators <image> Write a program that calculates the length of the shortest expression that evaluates equal to the given expression with whatever values of the four variables. For example, `0`, that is the first expression in the sample input, cannot be shortened further. Therefore the shortest length for this expression is 1. For another example, `(a*(1*b))`, the second in the sample input, always evaluates equal to `(a*b)` and `(b*a)`, which are the shortest. The output for this expression, thus, should be `5`. Input The input consists of multiple datasets. A dataset consists of one line, containing an expression conforming to the grammar described above. The length of the expression is less than or equal to 16 characters. The end of the input is indicated by a line containing one Β‘`.`Β’ (period). The number of datasets in the input is at most 200. Output For each dataset, output a single line containing an integer which is the length of the shortest expression that has the same value as the given expression for all combinations of values in the variables. Sample Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output for the Sample Input 1 5 2 1 13 Example Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output 1 5 2 1 13
instruction
0
51,248
6
102,496
"Correct Solution: ``` a=65280; b=61680; c=52428; d=43690; e=65535 QS = [[] for i in range(17)] QS[1] = [a, b, c, d] L = {a: 1, b: 1, c: 1, d: 1, e: 1, e: 1, 0: 1} H = [] get = L.get push = H.append for l in range(1, 16): Q = QS[l] li = 13-l; l3 = l+3; l1 = l+1 pop = Q.pop pushQN = QS[l1].append while Q: p = pop() if L[p] < l: continue if l1 < get(p ^ e, 17): L[p ^ e] = l1 l < 12 and pushQN(p ^ e) if l < 13: for q, r in H: if r < li: if l3+r < get(p & q, 17): L[p & q] = l3+r; QS[l3+r].append(p & q) if l3+r < get(p ^ q, 17): L[p ^ q] = l3+r; QS[l3+r].append(p ^ q) elif r == li: if p & q not in L: L[p & q] = 16 if p ^ q not in L: L[p ^ q] = 16 else: break if l < 7: push((p, l)) print(*map(L.__getitem__, eval("e&"+",e&".join(open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]))),sep='\n') ```
output
1
51,248
6
102,497
Provide a correct Python 3 solution for this coding contest problem. Boolean Expression Compressor You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning. The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule: > <E> ::= `0` | `1` | `a` | `b` | `c` | `d` | `-`<E> | `(`<E>`^`<E>`)` | `(`<E>`*`<E>`)` Letters `a`, `b`, `c` and `d` represent Boolean variables that have values of either `0` or `1`. Operators are evaluated as shown in the Table below. In other words, `-` means negation (NOT), `^` means exclusive disjunction (XOR), and `*` means logical conjunction (AND). Table: Evaluations of operators <image> Write a program that calculates the length of the shortest expression that evaluates equal to the given expression with whatever values of the four variables. For example, `0`, that is the first expression in the sample input, cannot be shortened further. Therefore the shortest length for this expression is 1. For another example, `(a*(1*b))`, the second in the sample input, always evaluates equal to `(a*b)` and `(b*a)`, which are the shortest. The output for this expression, thus, should be `5`. Input The input consists of multiple datasets. A dataset consists of one line, containing an expression conforming to the grammar described above. The length of the expression is less than or equal to 16 characters. The end of the input is indicated by a line containing one Β‘`.`Β’ (period). The number of datasets in the input is at most 200. Output For each dataset, output a single line containing an integer which is the length of the shortest expression that has the same value as the given expression for all combinations of values in the variables. Sample Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output for the Sample Input 1 5 2 1 13 Example Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output 1 5 2 1 13
instruction
0
51,249
6
102,498
"Correct Solution: ``` def calc(s): def parse(a, b, c, d): nonlocal cur g = s[cur]; cur += 1 if g == '-': return 1 ^ parse(a, b, c, d) if g == '(': p = parse(a, b, c, d) cmd = s[cur]; cur += 1 q = parse(a, b, c, d) cur += 1 # ')' return p ^ q if cmd == '^' else p & q return eval(g) res = 0 for b in range(16): cur = 0 if parse(*map(int, format(b, '04b'))): res += 1 << b return res base = "abcd10" L = {} for e in base: state = calc(e) L[state] = 1 ALL = 2**16-1 MAX = 10**18 for i in range(6): R = dict(L) for p in R: if R[p] < 16: L[p ^ ALL] = min(L.get(p ^ ALL, MAX), R[p] + 1) if R[p]+3 < 16: for q in R: if R[p] + R[q] + 3 <= 16: L[p & q] = min(L.get(p & q, MAX), R[p] + R[q] + 3) L[p ^ q] = min(L.get(p ^ q, MAX), R[p] + R[q] + 3) while 1: s = input() if s == '.': break print(L[calc(s)]) ```
output
1
51,249
6
102,499
Provide a correct Python 3 solution for this coding contest problem. Boolean Expression Compressor You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning. The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule: > <E> ::= `0` | `1` | `a` | `b` | `c` | `d` | `-`<E> | `(`<E>`^`<E>`)` | `(`<E>`*`<E>`)` Letters `a`, `b`, `c` and `d` represent Boolean variables that have values of either `0` or `1`. Operators are evaluated as shown in the Table below. In other words, `-` means negation (NOT), `^` means exclusive disjunction (XOR), and `*` means logical conjunction (AND). Table: Evaluations of operators <image> Write a program that calculates the length of the shortest expression that evaluates equal to the given expression with whatever values of the four variables. For example, `0`, that is the first expression in the sample input, cannot be shortened further. Therefore the shortest length for this expression is 1. For another example, `(a*(1*b))`, the second in the sample input, always evaluates equal to `(a*b)` and `(b*a)`, which are the shortest. The output for this expression, thus, should be `5`. Input The input consists of multiple datasets. A dataset consists of one line, containing an expression conforming to the grammar described above. The length of the expression is less than or equal to 16 characters. The end of the input is indicated by a line containing one Β‘`.`Β’ (period). The number of datasets in the input is at most 200. Output For each dataset, output a single line containing an integer which is the length of the shortest expression that has the same value as the given expression for all combinations of values in the variables. Sample Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output for the Sample Input 1 5 2 1 13 Example Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output 1 5 2 1 13
instruction
0
51,250
6
102,500
"Correct Solution: ``` a=65280; b=61680; c=52428; d=43690; e=65535 L = {el: 1 for el in [a, b, c, d, e, 0]} for i in range(6): R = sorted(L.items(), key=lambda x: x[1]) for p, l in R: if l < 16: L[p ^ e] = min(L.get(p ^ e, 16), l+1) if l+3 < 16: for q, r in R: if l+r+3 <= 16: L[p & q] = min(L.get(p & q, 16), l+r+3) L[p ^ q] = min(L.get(p ^ q, 16), l+r+3) else: break else: break print(*(L[e & eval(s)] for s in open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]),sep='\n') ```
output
1
51,250
6
102,501
Provide a correct Python 3 solution for this coding contest problem. Boolean Expression Compressor You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning. The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule: > <E> ::= `0` | `1` | `a` | `b` | `c` | `d` | `-`<E> | `(`<E>`^`<E>`)` | `(`<E>`*`<E>`)` Letters `a`, `b`, `c` and `d` represent Boolean variables that have values of either `0` or `1`. Operators are evaluated as shown in the Table below. In other words, `-` means negation (NOT), `^` means exclusive disjunction (XOR), and `*` means logical conjunction (AND). Table: Evaluations of operators <image> Write a program that calculates the length of the shortest expression that evaluates equal to the given expression with whatever values of the four variables. For example, `0`, that is the first expression in the sample input, cannot be shortened further. Therefore the shortest length for this expression is 1. For another example, `(a*(1*b))`, the second in the sample input, always evaluates equal to `(a*b)` and `(b*a)`, which are the shortest. The output for this expression, thus, should be `5`. Input The input consists of multiple datasets. A dataset consists of one line, containing an expression conforming to the grammar described above. The length of the expression is less than or equal to 16 characters. The end of the input is indicated by a line containing one Β‘`.`Β’ (period). The number of datasets in the input is at most 200. Output For each dataset, output a single line containing an integer which is the length of the shortest expression that has the same value as the given expression for all combinations of values in the variables. Sample Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output for the Sample Input 1 5 2 1 13 Example Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output 1 5 2 1 13
instruction
0
51,251
6
102,502
"Correct Solution: ``` a=65280; b=61680; c=52428; d=43690; e=65535 def calc(s): res = eval(s.replace("-", "~").replace("*", "&").replace("1", "e")) return e ^ ~res if res < 0 else res base = [a, b, c, d, e, 0] L = {el: 1 for el in base} for i in range(6): R = dict(L) for p in R: if R[p] < 16: L[p ^ e] = min(L.get(p ^ e, 16), R[p] + 1) if R[p]+3 < 16: for q in R: if R[p] + R[q] + 3 <= 16: L[p & q] = min(L.get(p & q, 16), R[p] + R[q] + 3) L[p ^ q] = min(L.get(p ^ q, 16), R[p] + R[q] + 3) while 1: s = input() if s == '.': break print(L[calc(s)]) ```
output
1
51,251
6
102,503
Provide a correct Python 3 solution for this coding contest problem. Boolean Expression Compressor You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning. The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule: > <E> ::= `0` | `1` | `a` | `b` | `c` | `d` | `-`<E> | `(`<E>`^`<E>`)` | `(`<E>`*`<E>`)` Letters `a`, `b`, `c` and `d` represent Boolean variables that have values of either `0` or `1`. Operators are evaluated as shown in the Table below. In other words, `-` means negation (NOT), `^` means exclusive disjunction (XOR), and `*` means logical conjunction (AND). Table: Evaluations of operators <image> Write a program that calculates the length of the shortest expression that evaluates equal to the given expression with whatever values of the four variables. For example, `0`, that is the first expression in the sample input, cannot be shortened further. Therefore the shortest length for this expression is 1. For another example, `(a*(1*b))`, the second in the sample input, always evaluates equal to `(a*b)` and `(b*a)`, which are the shortest. The output for this expression, thus, should be `5`. Input The input consists of multiple datasets. A dataset consists of one line, containing an expression conforming to the grammar described above. The length of the expression is less than or equal to 16 characters. The end of the input is indicated by a line containing one Β‘`.`Β’ (period). The number of datasets in the input is at most 200. Output For each dataset, output a single line containing an integer which is the length of the shortest expression that has the same value as the given expression for all combinations of values in the variables. Sample Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output for the Sample Input 1 5 2 1 13 Example Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output 1 5 2 1 13
instruction
0
51,252
6
102,504
"Correct Solution: ``` a=65280; b=61680; c=52428; d=43690; e=65535 from heapq import heappush, heappop base = [a, b, c, d, e, 0] Q = [(1, el) for el in base] L = {el: 1 for el in base} H = [] while Q: l, p = heappop(Q) if L[p] < l: continue if l+1 < L.get(p ^ e, 17): L[p^e] = l+1 if l+1 < 16: heappush(Q, (l+1, p^e)) if l+3 < 16: for q, r in H: if l+r+3 <= 16: if l+r+3 < L.get(p & q, 17): L[p & q] = l+r+3 if l+r+3 < 16: heappush(Q, (l+r+3, p & q)) if l+r+3 < L.get(p ^ q, 17): L[p ^ q] = l+r+3 if l+r+3 < 16: heappush(Q, (l+r+3, p ^ q)) else: break if l < 7: H.append((p, l)) print(*(L[e & eval(s)] for s in open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]),sep='\n') ```
output
1
51,252
6
102,505
Provide a correct Python 3 solution for this coding contest problem. Boolean Expression Compressor You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning. The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule: > <E> ::= `0` | `1` | `a` | `b` | `c` | `d` | `-`<E> | `(`<E>`^`<E>`)` | `(`<E>`*`<E>`)` Letters `a`, `b`, `c` and `d` represent Boolean variables that have values of either `0` or `1`. Operators are evaluated as shown in the Table below. In other words, `-` means negation (NOT), `^` means exclusive disjunction (XOR), and `*` means logical conjunction (AND). Table: Evaluations of operators <image> Write a program that calculates the length of the shortest expression that evaluates equal to the given expression with whatever values of the four variables. For example, `0`, that is the first expression in the sample input, cannot be shortened further. Therefore the shortest length for this expression is 1. For another example, `(a*(1*b))`, the second in the sample input, always evaluates equal to `(a*b)` and `(b*a)`, which are the shortest. The output for this expression, thus, should be `5`. Input The input consists of multiple datasets. A dataset consists of one line, containing an expression conforming to the grammar described above. The length of the expression is less than or equal to 16 characters. The end of the input is indicated by a line containing one Β‘`.`Β’ (period). The number of datasets in the input is at most 200. Output For each dataset, output a single line containing an integer which is the length of the shortest expression that has the same value as the given expression for all combinations of values in the variables. Sample Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output for the Sample Input 1 5 2 1 13 Example Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output 1 5 2 1 13
instruction
0
51,253
6
102,506
"Correct Solution: ``` a=65280; b=61680; c=52428; d=43690; e=65535 from heapq import heappush, heappop base = [a, b, c, d, e, 0] Q = [(1, el) for el in base] L = {el: 1 for el in base} H = [] get = L.get push = H.append while Q: l, p = heappop(Q) if L[p] < l: continue if l+1 < get(p ^ e, 17): L[p ^ e] = l+1 if l+1 < 16: heappush(Q, (l+1, p ^ e)) if l+3 < 16: for q, r in H: if l+r+3 <= 16: if l+r+3 < get(p & q, 17): L[p & q] = l+r+3 if l+r+3 < 16: heappush(Q, (l+r+3, p & q)) if l+r+3 < get(p ^ q, 17): L[p ^ q] = l+r+3 if l+r+3 < 16: heappush(Q, (l+r+3, p ^ q)) else: break if l < 7: push((p, l)) print(*map(L.__getitem__, eval("e&%s"%",e&".join(open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]))),sep='\n') ```
output
1
51,253
6
102,507
Provide a correct Python 3 solution for this coding contest problem. Boolean Expression Compressor You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning. The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule: > <E> ::= `0` | `1` | `a` | `b` | `c` | `d` | `-`<E> | `(`<E>`^`<E>`)` | `(`<E>`*`<E>`)` Letters `a`, `b`, `c` and `d` represent Boolean variables that have values of either `0` or `1`. Operators are evaluated as shown in the Table below. In other words, `-` means negation (NOT), `^` means exclusive disjunction (XOR), and `*` means logical conjunction (AND). Table: Evaluations of operators <image> Write a program that calculates the length of the shortest expression that evaluates equal to the given expression with whatever values of the four variables. For example, `0`, that is the first expression in the sample input, cannot be shortened further. Therefore the shortest length for this expression is 1. For another example, `(a*(1*b))`, the second in the sample input, always evaluates equal to `(a*b)` and `(b*a)`, which are the shortest. The output for this expression, thus, should be `5`. Input The input consists of multiple datasets. A dataset consists of one line, containing an expression conforming to the grammar described above. The length of the expression is less than or equal to 16 characters. The end of the input is indicated by a line containing one Β‘`.`Β’ (period). The number of datasets in the input is at most 200. Output For each dataset, output a single line containing an integer which is the length of the shortest expression that has the same value as the given expression for all combinations of values in the variables. Sample Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output for the Sample Input 1 5 2 1 13 Example Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output 1 5 2 1 13
instruction
0
51,254
6
102,508
"Correct Solution: ``` a=65280; b=61680; c=52428; d=43690; e=65535 QS = [[] for i in range(17)] QS[1] = [a, b, c, d] L = {a: 1, b: 1, c: 1, d: 1, e: 1, e: 1, 0: 1} H = [] get = L.get push = H.append for l in range(1, 16): Q = QS[l] QN = QS[l+1] while Q: p = Q.pop() if L[p] < l: continue if l+1 < get(p ^ e, 17): L[p ^ e] = l+1 l < 15 and QN.append(p ^ e) if l < 13: li = 13-l; l3 = 3+l for q, r in H: if r < li: k = p & q if r < get(k, 17)-l3: L[k] = l3+r; QS[l3+r].append(k) k = p ^ q if r < get(k, 17)-l3: L[k] = l3+r; QS[l3+r].append(k) elif r == li: if p & q not in L: L[p & q] = 16 if p ^ q not in L: L[p ^ q] = 16 else: break if l < 7: push((p, l)) print(*map(L.__getitem__, eval("e&"+",e&".join(open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]))),sep='\n') ```
output
1
51,254
6
102,509
Provide a correct Python 3 solution for this coding contest problem. Boolean Expression Compressor You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning. The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule: > <E> ::= `0` | `1` | `a` | `b` | `c` | `d` | `-`<E> | `(`<E>`^`<E>`)` | `(`<E>`*`<E>`)` Letters `a`, `b`, `c` and `d` represent Boolean variables that have values of either `0` or `1`. Operators are evaluated as shown in the Table below. In other words, `-` means negation (NOT), `^` means exclusive disjunction (XOR), and `*` means logical conjunction (AND). Table: Evaluations of operators <image> Write a program that calculates the length of the shortest expression that evaluates equal to the given expression with whatever values of the four variables. For example, `0`, that is the first expression in the sample input, cannot be shortened further. Therefore the shortest length for this expression is 1. For another example, `(a*(1*b))`, the second in the sample input, always evaluates equal to `(a*b)` and `(b*a)`, which are the shortest. The output for this expression, thus, should be `5`. Input The input consists of multiple datasets. A dataset consists of one line, containing an expression conforming to the grammar described above. The length of the expression is less than or equal to 16 characters. The end of the input is indicated by a line containing one Β‘`.`Β’ (period). The number of datasets in the input is at most 200. Output For each dataset, output a single line containing an integer which is the length of the shortest expression that has the same value as the given expression for all combinations of values in the variables. Sample Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output for the Sample Input 1 5 2 1 13 Example Input 0 (a*(1*b)) (1^a) (-(-a*-b)*a) (a^(b^(c^d))) . Output 1 5 2 1 13
instruction
0
51,255
6
102,510
"Correct Solution: ``` a=65280; b=61680; c=52428; d=43690; e=65535 from heapq import heappush, heappop base = [a, b, c, d, e, 0] Q = [(1, el) for el in base] L = {el: 1 for el in base} H = [] while Q: l, p = heappop(Q) if L[p] < l: continue if l+1 < L.get(p ^ e, 17): L[p ^ e] = l+1 if l+1 < 16: heappush(Q, (l+1, p ^ e)) if l+3 < 16: for q, r in H: if l+r+3 <= 16: if l+r+3 < L.get(p & q, 17): L[p & q] = l+r+3 if l+r+3 < 16: heappush(Q, (l+r+3, p & q)) if l+r+3 < L.get(p ^ q, 17): L[p ^ q] = l+r+3 if l+r+3 < 16: heappush(Q, (l+r+3, p ^ q)) else: break if l < 7: H.append((p, l)) print(*map(L.__getitem__, eval("e&%s"%",e&".join(open(0).read().replace(*"-~").replace(*"*&").replace(*"1e").split()[:-1]))),sep='\n') ```
output
1
51,255
6
102,511