text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0 Tags: dp Correct Solution: ``` def main(): n,m,b,mod=map(int,input().split()) arr=list(map(int,input().split())) dp=[[0 for _ in range(b+1)] for _ in range(m+1)] dp[0]=[1]*(b+1) for item in arr: for x in range(1,m+1): for y in range(item,b+1): dp[x][y]=(dp[x][y]+dp[x-1][y-item])%mod print(dp[m][b]) main() ```
101,600
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0 Submitted Solution: ``` import sys import copy input=sys.stdin.readline n,m,b,mod=map(int,input().split()) a=list(map(int,input().split())) dp=[[0]*(m+1) for i in range(b+1)] dp[0][0]=1 for i in range(n): for j in range(a[i],b+1): for k in range(1,m+1): dp[j][k]=(dp[j][k]+dp[j-a[i]][k-1])%mod ans=0 for i in range(b+1): ans+=dp[i][m] ans%=mod print(ans) ``` Yes
101,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0 Submitted Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n,m,b,mod=map(int,input().split()) arr=list(map(int,input().split())) dp=[[0 for _ in range(b+1)] for _ in range(m+1)] dp[0]=[1]*(b+1) for item in arr: for x in range(1,m+1): for y in range(item,b+1): dp[x][y]=(dp[x][y]+dp[x-1][y-item])%mod print(dp[m][b]) #---------------------------------------------------------------------------------------- # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ``` Yes
101,602
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0 Submitted Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n,m,b,mod=map(int,input().split()) arr=list(map(int,input().split())) dp=[[0 for _ in range(b+1)] for _ in range(m+1)] dp[0]=[1]*(b+1) for item in arr: for x in range(1,m+1): for y in range(item,b+1): dp[x][y]+=dp[x-1][y-item] dp[x][y]%=mod print(dp[m][b]) #---------------------------------------------------------------------------------------- # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ``` Yes
101,603
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0 Submitted Solution: ``` n, m, b, mod = map(int, input().split()) a = list(map(int, input().split())) dp = [[0 for i in range(m + 1)] for j in range(b + 1)] dp[0][0] = 1 for i in range(n): for j in range(a[i], b + 1): for k in range(m): dp[j][k + 1] = (dp[j][k + 1] + dp[j - a[i]][k]) % mod res = 0 for i in range(b + 1): res = (res + dp[i][m]) % mod print(res) ``` Yes
101,604
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0 Submitted Solution: ``` import sys input=sys.stdin.buffer.readline n,lines,bugs,mod=map(int,input().split()) arr=list(map(int,input().split())) dp=[[0 for i in range(bugs+1)] for j in range(lines+1)] for i in range(n): if arr[i] <=bugs: dp[1][arr[i]] += 1 for j in range(lines): for k in range(bugs): if dp[j][k] >0 and k+arr[i] <=bugs: dp[j+1][k+arr[i]] =(dp[j+1][k+arr[i]]+dp[j][k]) % mod print(sum(dp[lines][:bugs+1])%mod) ``` No
101,605
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0 Submitted Solution: ``` n, m, b, mod = map(int, input().split()) a = list(map(int, input().split())) dp = [[0 for col in range(b + 1)]for row in range(n)] for i in range(n): dp[i][0] = 1 for i in range(b + 1): if i % a[0] == 0: dp[0][i] = 1 for i in range(1, n): for j in range(1, b + 1): for k in range((j // a[i]) + 1): dp[i][j] = dp[i - 1][j] if k > 0: dp[i][j] = (dp[i][j] + dp[i - 1][j - k * a[i]]) % mod ans = 0 for i in range(b + 1): ans = (ans + dp[n - 1][i]) % mod print(ans) ``` No
101,606
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0 Submitted Solution: ``` import sys input=sys.stdin.buffer.readline n,lines,bugs,mod=map(int,input().split()) arr=list(map(int,input().split())) dp=[[0 for i in range(bugs+1)] for j in range(lines+1)] for i in range(n): if arr[i] <=bugs: dp[1][arr[i]] =(dp[1][arr[i]]+1) % mod for j in range(lines): for k in range(bugs): if dp[j][k] >0 and k+arr[i] <=bugs: dp[j+1][k+arr[i]] =(dp[j+1][k+arr[i]]+dp[j][k]) % mod print(sum(dp[lines][:bugs+1])%mod) ``` No
101,607
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0 Submitted Solution: ``` import sys input=sys.stdin.readline n,m,b,mod=map(int,input().split()) a=list(map(int,input().split())) dp1=[[0]*(b+1) for i in range(m+1)] dp2=[[0]*(b+1) for i in range(m+1)] dp1[0][0]=1 a=[0]+a for i in range(1,n+1): for j in range(m+1): for k in range(b+1): if k-a[i]>=0: dp2[j][k]=(dp1[j][k]+dp2[j-1][k-a[i]])%mod else: dp2[j][k]=dp1[j][k]%mod dp1=dp2 print(sum(dp2[m])%mod) ``` No
101,608
Provide tags and a correct Python 3 solution for this coding contest problem. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Tags: data structures, expression parsing, implementation Correct Solution: ``` def main(): alpha = "QWERTYUIOPLKJHGFDSAZXCVBNM" s = input() n = len(s) i = 0 st = [] ans = 0 while i < n: j = i if s[i] in alpha: while j+1 < n and s[j+1] in alpha: j += 1 name = s[i:j+1] i = j ans += st.count(name) st.append(name) elif s[i] == '.': st.pop(-1) i += 1 print(ans) if __name__ == '__main__': main() ```
101,609
Provide tags and a correct Python 3 solution for this coding contest problem. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Tags: data structures, expression parsing, implementation Correct Solution: ``` s = input() a = [] cnt = 0 s = ':' + s s1 = '' flag = False for i in range(len(s)): if flag: if s[i] != '.' and s[i] != ':' and s[i] != ',': s1 += s[i] continue else: a.append(s1) flag = False for j in range(len(a) - 1): if a[j] == a[-1]: cnt += 1 if s[i] != '.' and s[i] != ':' and s[i] != ',': flag = True s1 = s[i] elif s[i] == '.': a.pop() print(cnt) # Made By Mostafa_Khaled ```
101,610
Provide tags and a correct Python 3 solution for this coding contest problem. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Tags: data structures, expression parsing, implementation Correct Solution: ``` #!/usr/bin/env python3 tree = input().strip() def get_answer(tree, start_index = 0, prev = []): colon_index = tree.find(':', start_index) period_index = tree.find('.', start_index) name_end_index = colon_index if ((colon_index != -1) and (colon_index < period_index)) else period_index name = tree[start_index:name_end_index] answer = prev.count(name) if ((colon_index == -1) or (period_index < colon_index)): return (answer, period_index+1) else: # Recurse prev_names = prev + [name] next_start = colon_index while tree[next_start] != '.': (sub_answer, next_start) = get_answer(tree, next_start+1, prev_names) answer += sub_answer return (answer, next_start+1) print(get_answer(tree)[0]) ```
101,611
Provide tags and a correct Python 3 solution for this coding contest problem. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Tags: data structures, expression parsing, implementation Correct Solution: ``` def main(): alpha = "QWERTYUIOPLKJHGFDSAZXCVBNM" s = input() n = len(s) i = 0 st = ["root-0"] name = "" ans = 0 first = True while i < n: j = i if s[i] in alpha: while j+1 < n and s[j+1] in alpha: j += 1 name = s[i:j+1] first = True i = j ans += st.count(name) elif s[i] == ":": first = True st.append(name) elif s[i] == ',': first = True elif s[i] == '.' and first: first = False else: st.pop(-1) i += 1 print(ans) if __name__ == '__main__': main() ```
101,612
Provide tags and a correct Python 3 solution for this coding contest problem. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Tags: data structures, expression parsing, implementation Correct Solution: ``` import sys from array import array # noqa: F401 from collections import Counter def input(): return sys.stdin.buffer.readline().decode('utf-8') class Employee(object): def __init__(self, name: str): self.name = name self.sub = [] def add_sub(self, sub: 'Employee'): self.sub.append(sub) def __repr__(self): return self.name stack = [Employee('*** God ***')] # type: list[Employee] s = input().rstrip() n, l = len(s), 0 while l < n: if s[l] == '.': stack.pop() l += 1 continue if s[l] == ',': l += 1 continue r = l while 65 <= ord(s[r]) <= 90: r += 1 e = Employee(s[l:r]) if stack: stack[-1].add_sub(e) if s[r] == ':': stack.append(e) l = r + 1 def rec(e: Employee): count = 0 name_dict = Counter() for sub in e.sub: cnt, d = rec(sub) count += cnt for k, v in d.items(): name_dict[k] += v count += name_dict[e.name] name_dict[e.name] += 1 return count, name_dict print(rec(stack[0])[0]) ```
101,613
Provide tags and a correct Python 3 solution for this coding contest problem. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Tags: data structures, expression parsing, implementation Correct Solution: ``` ######directed def dfs(graph,n,currnode,match): visited=[False for x in range(n+1)] stack=[currnode] ans=0 while stack: currnode=stack[-1] if visited[currnode]==False: visited[currnode]=True if arr[currnode]==match:ans+=1 if currnode in graph: for neighbour in graph[currnode]: if visited[neighbour]==False: visited[neighbour]=True stack.append(neighbour) if arr[neighbour]==match:ans+=1 break #####if we remove break it becomes bfs else: stack.pop() ####we are backtracking to previous node which is in our stack else: stack.pop() return ans def buildgraph(arr): graph={} currnode=0 graph[0]=[] parent=[None for x in range(len(arr))] i=2 while i in range(1,len(arr)): if arr[i] not in look: if currnode in graph: graph[currnode].append(i) else: graph[currnode]=[i] parent[i]=currnode if arr[i+1]==":": currnode=i i+=2 else: if arr[i]==".": currnode=parent[currnode] i+=1 return graph,parent ###main code s=input() arr=[] dict={} look={".",":",","} name="" for i in range(len(s)): if s[i] not in look: name+=s[i] else: if name!="": arr.append(name) name="" arr.append(s[i]) else: arr.append(s[i]) if len(arr)>2: count=0 graph,parent=buildgraph(arr) for i in range(len(arr)): if arr[i] not in look: count+=dfs(graph,len(arr),i,arr[i]) count-=1 print(count) else: print(0) ```
101,614
Provide tags and a correct Python 3 solution for this coding contest problem. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Tags: data structures, expression parsing, implementation Correct Solution: ``` s = input() a = [] cnt = 0 s = ':' + s s1 = '' flag = False for i in range(len(s)): if flag: if s[i] != '.' and s[i] != ':' and s[i] != ',': s1 += s[i] continue else: a.append(s1) flag = False for j in range(len(a) - 1): if a[j] == a[-1]: cnt += 1 if s[i] != '.' and s[i] != ':' and s[i] != ',': flag = True s1 = s[i] elif s[i] == '.': a.pop() print(cnt) ```
101,615
Provide tags and a correct Python 3 solution for this coding contest problem. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Tags: data structures, expression parsing, implementation Correct Solution: ``` import re a,ans=[],0 for x in re.split('[:,]',input()): dl=x.count(".") if dl==0: ans+=a.count(x) a+=[x] else: x=x[:-dl] ans+=a.count(x) a+=[x] a=a[:-dl] print(ans) ```
101,616
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Submitted Solution: ``` from collections import defaultdict, Counter def dfs(cur, counter, adj_list, visited): neighbhours = [] if cur in adj_list.keys(): neighbhours = adj_list[cur] # print("visting", cur) # input() cur = cur.split('-')[0] ans = 0 ans += counter[cur] counter[cur] += 1 for p in neighbhours: if not visited[p]: ans += dfs(p, counter, adj_list, visited) counter[cur] -= 1 return ans def main(): #sys.stdin = open('input.txt', 'r') #sys.stdout = open('output.txt', 'w') s = input() n = len(s) alpha = "QWERTYUIOPLKJHGFDSAZXCVBNM" adj_list = defaultdict(lambda : []) Counter_dict = {"root": 0} visited = {"root": False} i = 0 st = ["root-0"] name = "" ind = 0 while i < n: # print(i) # input() j = i if s[i] in alpha: while j+1 < n and s[j+1] in alpha: j += 1 name = s[i:j+1] ind += 1 adj_list[st[-1]].append(name + "-" + str(ind)) Counter_dict[name] = 0 visited[name+"-"+str(ind)] = False first = True i = j elif s[i] == ":": first = True st.append(name+"-"+str(ind)) elif s[i] == ',': first = True elif s[i] == '.' and first: first = False else: st.pop(-1) i += 1 # print("stack:", *st) adj_list = dict(adj_list) # for key in adj_list.keys(): # print(key, adj_list[key]) # print("counter", Counter_dict) # print('visited', visited) ans = dfs("root-0", Counter_dict, adj_list, visited) print(ans) if __name__ == '__main__': main() ``` Yes
101,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Submitted Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz' M=10**9+7 EPS=1e-6 def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() for _ in range(1): s=input() n=len(s) i=0 stack=[] count=defaultdict(int) i=0 ans=0 while(i<n): # print(stack) if(s[i] in '.'): count[stack.pop()]-=1 i+=1 elif(s[i] in ':,'): i+=1 pass else: name=s[i] i+=1 while(i<n and s[i] not in',:.'): name+=s[i] i+=1 ans+=count[name] count[name]+=1 stack.append(name) print(ans) ``` Yes
101,618
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Submitted Solution: ``` def P(): n=a[0];a.pop(0);d={n:1};r=0 while a[0]!='.': a.pop(0);l,t=P();r+=l for k in t.keys(): d[k]=d.get(k,0)+t[k] if k==n:r+=t[k] a.pop(0) return r,d a=[] x='' for i in input(): if i in ':.,': if x:a+=[x] a+=[i];x='' else:x+=i print(P()[0]) ``` Yes
101,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: * employee ::= name. | name:employee1,employee2, ... ,employeek. * name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. <image> Input The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. Output Print a single number β€” the number of uncomfortable situations in the company. Examples Input MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... Output 3 Input A:A.. Output 1 Input A:C:C:C:C..... Output 6 Submitted Solution: ``` from collections import defaultdict, Counter def dfs(cur, counter, adj_list, visited): neighbhours = [] if cur in adj_list.keys(): neighbhours = adj_list[cur] # print("visting", cur) # input() cur = cur.split('-')[0] ans = 0 ans += counter[cur] counter[cur] += 1 for p in neighbhours: if not visited[p]: ans += dfs(p, counter, adj_list, visited) counter[cur] -= 1 return ans def main(): #sys.stdin = open('input.txt', 'r') #sys.stdout = open('output.txt', 'w') s = input() n = len(s) alpha = "QWERTYUIOPLKJHGFDSAZXCVBNM" adj_list = defaultdict(lambda : []) Counter_dict = {"root": 0} visited = {"root": False} i = 0 st = ["root-0"] name = "" ind = 1 while i < n: # print(i) # input() j = i if s[i] in alpha: while j+1 < n and s[j+1] in alpha: j += 1 name = s[i:j+1] adj_list[st[-1]].append(name + "-" + str(ind)) first = True i = j Counter_dict[name] = 0 visited[name+"-"+str(ind)] = False elif s[i] == ":": first = True st.append(name+"-"+str(ind)) ind += 1 elif s[i] == ',': first = True elif s[i] == '.' and first: first = False else: st.pop(-1) i += 1 # print("stack:", *st) adj_list = dict(adj_list) # for key in adj_list.keys(): # print(key, adj_list[key]) # print("counter", Counter_dict) # print('visited', visited) ans = dfs("root-0", Counter_dict, adj_list, visited) print(ans) if __name__ == '__main__': main() ``` No
101,620
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Tags: implementation, math Correct Solution: ``` i = input x=int(i()) v1=int(i()) v2=int(i()) print(v1*x/(v1+v2)) ```
101,621
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Tags: implementation, math Correct Solution: ``` m=input() l=int(m) n=input() p=int(n) o=input() q=int(o) a=l/(p+q) print(a*p) print("\n") ```
101,622
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Tags: implementation, math Correct Solution: ``` l = int(input()) vg = int(input()) vv = int(input()) tm = l/(vg + vv) sm = tm * vg print(sm) ```
101,623
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Tags: implementation, math Correct Solution: ``` import sys from collections import deque read = lambda: list(map(int, sys.stdin.readline().split())) l,= read() p, = read() q, = read() print (l*p/(p+q)) ```
101,624
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Tags: implementation, math Correct Solution: ``` a = int(input()) b = int(input()) c = int(input()) print(b * a / (b + c)) ```
101,625
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Tags: implementation, math Correct Solution: ``` length = int(input()) p = int(input()) q = int(input()) print((length)/(p+q)*p) ```
101,626
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Tags: implementation, math Correct Solution: ``` l = int(input())#meters p = int(input()) #meters/sec q = int(input()) t1 = 0 if (p + q > 0): t1 = l / (p + q) print(t1 * p) ```
101,627
Provide tags and a correct Python 3 solution for this coding contest problem. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Tags: implementation, math Correct Solution: ``` ''' Author: Sofen Hoque Anonta ''' import re import sys import math import itertools import collections def inputArray(TYPE= int): return [TYPE(x) for x in input().split()] def solve(): d= int(input()) p= int(input()) q= int(input()) print(p*d/(p+q)) if __name__ == '__main__': # sys.stdin= open('F:/input.txt') solve() ```
101,628
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Submitted Solution: ``` l = int(input()) speedg = int(input()) speedn = int(input()) print(l / (speedg + speedn) * speedg) ``` Yes
101,629
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Submitted Solution: ``` n=int(input()) m=int(input()) p=int(input()) print(m/(p+m)*n) ``` Yes
101,630
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Submitted Solution: ``` l = int(input()) p = int(input()) q = int(input()) print(l*(p/(p+q))) ``` Yes
101,631
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Submitted Solution: ``` d=int(input()) h=int(input()) o=int(input()) print(d*(h/(h+o))) ``` Yes
101,632
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Submitted Solution: ``` cd=int(input()) p=int(input()) q=int(input()) if(p==q): print(cd/2) elif(p>q): z=(p*cd)/100 print(z) elif(p<q): z=(q*cd)/100 print(z) ``` No
101,633
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Submitted Solution: ``` l = int(input()) p = int (input()) q = int(input()) t = l / (p + q) ans = p * t print(int(ans)) ``` No
101,634
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Submitted Solution: ``` l = int (input()) p = int (input()) q = int (input()) print ( p*l // (p+q)) ``` No
101,635
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second. The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse. Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight. Input The first line of the input contains a single integer l (1 ≀ l ≀ 1 000) β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500) β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively. Output Print a single real number β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 100 50 50 Output 50 Input 199 60 40 Output 119.4 Note In the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor. Submitted Solution: ``` l =int( input()); q=int(input()); p=int(input()); print( (l/q+p)*q); ``` No
101,636
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1]. This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them. Input The first line contains integer n (1 ≀ n ≀ 106) β€” the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of permutation p. Output If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≀ qi ≀ n) β€” the elements of the permutation q. If there are several solutions print any of them. Examples Input 4 2 1 4 3 Output 3 4 2 1 Input 4 2 1 3 4 Output -1 Input 5 2 3 4 5 1 Output 4 5 1 2 3 Tags: combinatorics, constructive algorithms, dfs and similar, graphs, math Correct Solution: ``` import math import sys input = sys.stdin.readline n = int(input()) a = [int(_) - 1 for _ in input().split()] vis = [False] * n cycles = [[] for _ in range(n + 1)] for i in range(n): if vis[i]: continue cur = i cycle = [] while not vis[cur]: vis[cur] = True cycle.append(cur) cur = a[cur] cycles[len(cycle)].append(cycle) p = [0] * n for i in range(n + 1): if i % 2 == 1: for j in cycles[i]: for k in range(i): p[j[k]] = j[(k + (i + 1) // 2) % i] else: if len(cycles[i]) % 2 == 1: print(-1) exit(0) for j in range(0, len(cycles[i]), 2): for k in range(i): p[cycles[i][j][k]] = cycles[i][j + 1][k] p[cycles[i][j + 1][k]] = cycles[i][j][(k + 1) % i] print(' '.join(map(lambda i : str(i + 1), p))) ```
101,637
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1]. This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them. Input The first line contains integer n (1 ≀ n ≀ 106) β€” the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of permutation p. Output If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≀ qi ≀ n) β€” the elements of the permutation q. If there are several solutions print any of them. Examples Input 4 2 1 4 3 Output 3 4 2 1 Input 4 2 1 3 4 Output -1 Input 5 2 3 4 5 1 Output 4 5 1 2 3 Tags: combinatorics, constructive algorithms, dfs and similar, graphs, math Correct Solution: ``` import sys import bisect from bisect import bisect_left as lb input_=lambda: sys.stdin.readline().strip("\r\n") from math import log from math import gcd from math import atan2,acos from random import randint sa=lambda :input_() sb=lambda:int(input_()) sc=lambda:input_().split() sd=lambda:list(map(int,input_().split())) se=lambda:float(input_()) sf=lambda:list(input_()) flsh=lambda: sys.stdout.flush() #sys.setrecursionlimit(10**6) mod=10**9+7 gp=[] cost=[] dp=[] mx=[] ans1=[] ans2=[] special=[] specnode=[] a=0 kthpar=[] def dfs(root,par): if par!=-1: dp[root]=dp[par]+1 for i in range(1,20): if kthpar[root][i-1]!=-1: kthpar[root][i]=kthpar[kthpar[root][i-1]][i-1] for child in gp[root]: if child==par:continue kthpar[child][0]=root dfs(child,root) def hnbhai(): n=sb() a=[0]+sd() ans=[-1]*(n+1) d={} visited=[0]*(n+1) for i in range(1,n+1): if visited[i]==0: g=[] abe=i while not visited[abe]: visited[abe]=1 g.append(abe) abe=a[abe] if len(g)%2: mid=(len(g)+1)//2 for i in range(len(g)): ans[g[i]]=g[(i+mid)%len(g)] else: if d.get(len(g)): temp=d[len(g)] for i in range(len(g)): ans[g[i]]=temp[(i+1)%len(g)] ans[temp[i]]=g[i] del d[len(g)] else: d[len(g)]=g if len(d): print(-1) return print(*ans[1:]) for _ in range(1): hnbhai() ```
101,638
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1]. This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them. Input The first line contains integer n (1 ≀ n ≀ 106) β€” the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of permutation p. Output If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≀ qi ≀ n) β€” the elements of the permutation q. If there are several solutions print any of them. Examples Input 4 2 1 4 3 Output 3 4 2 1 Input 4 2 1 3 4 Output -1 Input 5 2 3 4 5 1 Output 4 5 1 2 3 Tags: combinatorics, constructive algorithms, dfs and similar, graphs, math Correct Solution: ``` #### IMPORTANT LIBRARY #### ############################ ### DO NOT USE import random --> 250ms to load the library ############################ ### In case of extra libraries: https://github.com/cheran-senthil/PyRival ###################### ####### IMPORT ####### ###################### from functools import cmp_to_key from collections import deque, Counter from heapq import heappush, heappop from math import log, ceil ###################### #### STANDARD I/O #### ###################### import sys import os 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") 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) def print(*args, **kwargs): 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() def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def ii(): return int(inp()) def si(): return str(inp()) def li(lag = 0): l = list(map(int, inp().split())) if lag != 0: for i in range(len(l)): l[i] += lag return l def mi(lag = 0): matrix = list() for i in range(n): matrix.append(li(lag)) return matrix def lsi(): #string list return list(map(str, inp().split())) def print_list(lista, space = " "): print(space.join(map(str, lista))) ###################### ### BISECT METHODS ### ###################### def bisect_left(a, x): """i tale che a[i] >= x e a[i-1] < x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] < x: left = mid+1 else: right = mid return left def bisect_right(a, x): """i tale che a[i] > x e a[i-1] <= x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] > x: right = mid else: left = mid+1 return left def bisect_elements(a, x): """elementi pari a x nell'Γ‘rray sortato""" return bisect_right(a, x) - bisect_left(a, x) ###################### ### MOD OPERATION #### ###################### MOD = 10**9 + 7 maxN = 5 FACT = [0] * maxN INV_FACT = [0] * maxN def add(x, y): return (x+y) % MOD def multiply(x, y): return (x*y) % MOD def power(x, y): if y == 0: return 1 elif y % 2: return multiply(x, power(x, y-1)) else: a = power(x, y//2) return multiply(a, a) def inverse(x): return power(x, MOD-2) def divide(x, y): return multiply(x, inverse(y)) def allFactorials(): FACT[0] = 1 for i in range(1, maxN): FACT[i] = multiply(i, FACT[i-1]) def inverseFactorials(): n = len(INV_FACT) INV_FACT[n-1] = inverse(FACT[n-1]) for i in range(n-2, -1, -1): INV_FACT[i] = multiply(INV_FACT[i+1], i+1) def coeffBinom(n, k): if n < k: return 0 return multiply(FACT[n], multiply(INV_FACT[k], INV_FACT[n-k])) ###################### #### GRAPH ALGOS ##### ###################### # ZERO BASED GRAPH def create_graph(n, m, undirected = 1, unweighted = 1): graph = [[] for i in range(n)] if unweighted: for i in range(m): [x, y] = li(lag = -1) graph[x].append(y) if undirected: graph[y].append(x) else: for i in range(m): [x, y, w] = li(lag = -1) w += 1 graph[x].append([y,w]) if undirected: graph[y].append([x,w]) return graph def create_tree(n, unweighted = 1): children = [[] for i in range(n)] if unweighted: for i in range(n-1): [x, y] = li(lag = -1) children[x].append(y) children[y].append(x) else: for i in range(n-1): [x, y, w] = li(lag = -1) w += 1 children[x].append([y, w]) children[y].append([x, w]) return children def dist(tree, n, A, B = -1): s = [[A, 0]] massimo, massimo_nodo = 0, 0 distanza = -1 v = [-1] * n while s: el, dis = s.pop() if dis > massimo: massimo = dis massimo_nodo = el if el == B: distanza = dis for child in tree[el]: if v[child] == -1: v[child] = 1 s.append([child, dis+1]) return massimo, massimo_nodo, distanza def diameter(tree): _, foglia, _ = dist(tree, n, 0) diam, _, _ = dist(tree, n, foglia) return diam def dfs(graph, n, A): v = [-1] * n s = [[A, 0]] v[A] = 0 while s: el, dis = s.pop() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges def bfs(graph, n, A): v = [-1] * n s = deque() s.append([A, 0]) v[A] = 0 while s: el, dis = s.popleft() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges #FROM A GIVEN ROOT, RECOVER THE STRUCTURE def parents_children_root_unrooted_tree(tree, n, root = 0): q = deque() visited = [0] * n parent = [-1] * n children = [[] for i in range(n)] q.append(root) while q: all_done = 1 visited[q[0]] = 1 for child in tree[q[0]]: if not visited[child]: all_done = 0 q.appendleft(child) if all_done: for child in tree[q[0]]: if parent[child] == -1: parent[q[0]] = child children[child].append(q[0]) q.popleft() return parent, children # CALCULATING LONGEST PATH FOR ALL THE NODES def all_longest_path_passing_from_node(parent, children, n): q = deque() visited = [len(children[i]) for i in range(n)] downwards = [[0,0] for i in range(n)] upward = [1] * n longest_path = [1] * n for i in range(n): if not visited[i]: q.append(i) downwards[i] = [1,0] while q: node = q.popleft() if parent[node] != -1: visited[parent[node]] -= 1 if not visited[parent[node]]: q.append(parent[node]) else: root = node for child in children[node]: downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse = True)[0:2] s = [node] while s: node = s.pop() if parent[node] != -1: if downwards[parent[node]][0] == downwards[node][0] + 1: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1]) else: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0]) longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1 for child in children[node]: s.append(child) return longest_path ### TBD SUCCESSOR GRAPH 7.5 ### TBD TREE QUERIES 10.2 da 2 a 4 ### TBD ADVANCED TREE 10.3 ### TBD GRAPHS AND MATRICES 11.3.3 e 11.4.3 e 11.5.3 (ON GAMES) ###################### ## END OF LIBRARIES ## ###################### def f(n, a): visited = [0] * n cicli = [] for i in range(n): ciclo = [] j = i if visited[j] == 0: visited[j] = 1 while a[j] != i: ciclo.append(j) j = a[j] visited[j] = 1 ciclo.append(j) cicli.append(ciclo) q = [0] * n tot = {} for c in cicli: if len(c) % 2 == 1: i = len(c) // 2 j = len(c) - 1 while q[c[j]] == 0: q[c[j]] = c[i] + 1 i += 1 j += 1 i %= len(c) j %= len(c) else: k = len(c) if k not in tot: tot[k] = [] tot[k].append(c) for k in tot: if len(tot[k]) % 2 == 1: return [-1] else: for i in range(0, len(tot[k])//2): p1 = tot[k][2*i] p2 = tot[k][2*i+1] for i in range(len(p1)): q[p1[i]] = p2[i] + 1 q[p2[i]] = p1[(i+1) % len(p1)] + 1 return q n = ii() a = li(-1) print_list(f(n, a)) ```
101,639
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1]. This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them. Input The first line contains integer n (1 ≀ n ≀ 106) β€” the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of permutation p. Output If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≀ qi ≀ n) β€” the elements of the permutation q. If there are several solutions print any of them. Examples Input 4 2 1 4 3 Output 3 4 2 1 Input 4 2 1 3 4 Output -1 Input 5 2 3 4 5 1 Output 4 5 1 2 3 Tags: combinatorics, constructive algorithms, dfs and similar, graphs, math Correct Solution: ``` import sys #import random from bisect import bisect_right as rb from collections import deque #sys.setrecursionlimit(10**8) from queue import PriorityQueue from math import * input_ = lambda: sys.stdin.readline().strip("\r\n") ii = lambda : int(input_()) il = lambda : list(map(int, input_().split())) ilf = lambda : list(map(float, input_().split())) ip = lambda : input_() fi = lambda : float(input_()) ap = lambda ab,bc,cd : ab[bc].append(cd) li = lambda : list(input_()) pr = lambda x : print(x) prinT = lambda x : print(x) f = lambda : sys.stdout.flush() mod = 10**9 + 7 n = ii() a = [0] + il() def dfs (i) : vis[i] = 1 g.append(i) if (vis[a[i]] == 0) : dfs(a[i]) g = [] d = {} vis = [0 for i in range (n+2)] ans = [0 for i in range (n+1)] for i in range (1,n+1) : if (vis[i] == 0) : i1 = i while True : vis[i1] = 1 g.append(i1) if (vis[a[i1]] == 0) : i1 = a[i1] else : break l = len(g) if (l%2) : x = (l+1)//2 for j in range (l) : ans[g[j]] = g[(x+j)%l] elif (d.get(l)) : v = d[l] for j in range (l) : ans[g[j]] = v[(j+1)%l] ans[v[j]] = g[j] del d[l] else : d[l] = g g = [] for i in d : print(-1) exit(0) print(*ans[1:]) ```
101,640
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1]. This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them. Input The first line contains integer n (1 ≀ n ≀ 106) β€” the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of permutation p. Output If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≀ qi ≀ n) β€” the elements of the permutation q. If there are several solutions print any of them. Examples Input 4 2 1 4 3 Output 3 4 2 1 Input 4 2 1 3 4 Output -1 Input 5 2 3 4 5 1 Output 4 5 1 2 3 Submitted Solution: ``` import sys #import random from bisect import bisect_right as rb from collections import deque #sys.setrecursionlimit(10**6) from queue import PriorityQueue from math import * input_ = lambda: sys.stdin.readline().strip("\r\n") ii = lambda : int(input_()) il = lambda : list(map(int, input_().split())) ilf = lambda : list(map(float, input_().split())) ip = lambda : input_() fi = lambda : float(input_()) ap = lambda ab,bc,cd : ab[bc].append(cd) li = lambda : list(input_()) pr = lambda x : print(x) prinT = lambda x : print(x) f = lambda : sys.stdout.flush() mod = 10**9 + 7 n = ii() a = [0] + il() def dfs (i) : vis[i] = 1 g.append(i) if (vis[a[i]] == 0) : dfs(a[i]) g = [] d = {} vis = [0 for i in range (n+2)] ans = [0 for i in range (n+1)] if (n != 10**4) : for i in range (1,n+1) : if (vis[i] == 0) : dfs(i) l = len(g) if (l%2) : x = (l+1)//2 for j in range (l) : ans[g[j]] = g[(x+j)%l] elif (d.get(l)) : v = d[l] for j in range (l) : ans[g[j]] = v[(j+1)%l] ans[v[j]] = g[j] del d[l] else : d[l] = g g = [] for i in d : print(-1) exit(0) print(*ans[1:]) ``` No
101,641
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1]. This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them. Input The first line contains integer n (1 ≀ n ≀ 106) β€” the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of permutation p. Output If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≀ qi ≀ n) β€” the elements of the permutation q. If there are several solutions print any of them. Examples Input 4 2 1 4 3 Output 3 4 2 1 Input 4 2 1 3 4 Output -1 Input 5 2 3 4 5 1 Output 4 5 1 2 3 Submitted Solution: ``` n = int(input()) c = input() c = c.split(" ") c = [int(p) - 1 for p in c] visited = [0 for p in range(0,n,1)] cycle_st = [] for i in range(0,n,1): if visited[i] != 1: cycle = [] cycle.append([i,c[i]]) visited[i] = 1 d = c[i] while visited[d] != 1: cycle.append([d,c[d]]) visited[d] = 1 d = c[d] cycle_st.append(cycle) used = [ 1 for p in range(0,len(cycle_st),1)] posssible = True have_cycle = True i = 0 j = 0 for i in range(len(cycle_st)): if used[i]: have_cycle = False if(len(cycle_st[i]) % 2 == 1): for j in range(len(cycle_st[i])): if cycle_st[i][j][0] == cycle_st[i][j - 1][1]: q = i-i//2 else: q = -1 visited[cycle_st[i][j][0]] = cycle_st[i][j+q][1] else: for j in range(i + 1,len(cycle_st),1): if used[j] and len(cycle_st[i]) == len(cycle_st[j]): have_cycle = True for k in range(len(cycle_st[i])): visited[cycle_st[i][k][0]] = cycle_st[j][k - 1][0] visited[cycle_st[j][k - 1][0]] = cycle_st[i][k - 1][0] used[j] = 0 break if not have_cycle: posssible = False break if not posssible: print(-1) else: for p in visited: print(str(p + 1)) ``` No
101,642
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1]. This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them. Input The first line contains integer n (1 ≀ n ≀ 106) β€” the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of permutation p. Output If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≀ qi ≀ n) β€” the elements of the permutation q. If there are several solutions print any of them. Examples Input 4 2 1 4 3 Output 3 4 2 1 Input 4 2 1 3 4 Output -1 Input 5 2 3 4 5 1 Output 4 5 1 2 3 Submitted Solution: ``` n = int(input()) if n == 5: print('4 5 1 2 3') else: c = input() c = c.split(" ") c = [int(p) - 1 for p in c] visited = [0 for p in range(0,n,1)] cycle_st = [] for i in range(0,n,1): if visited[i] != 1: cycle = [] cycle.append([i,c[i]]) visited[i] = 1 d = c[i] while visited[d] != 1: cycle.append([d,c[d]]) visited[d] = 1 d = c[d] cycle_st.append(cycle) used = [ 1 for p in range(0,len(cycle_st),1)] posssible = True have_cycle =True i = 0 j = 0 for i in range(len(cycle_st)): if used[i]: have_cycle = False if(len(cycle_st[i]) % 2 == 1): for j in range(len(cycle_st[i])): visited[cycle_st[i][j][0]] = cycle_st[i][j-1][1] else: for j in range(i+1,len(cycle_st),1): if used[j] and len(cycle_st[i]) == len(cycle_st[j]): have_cycle = True for k in range(len(cycle_st[i])): visited[cycle_st[i][k][0]] = cycle_st[j][k-1][0] visited[cycle_st[j][k-1][0]] = cycle_st[i][k-1][0] used[j] = 0 break if not have_cycle: posssible = False break if not posssible: print(-1) else: for p in visited: print(str(p+1)) ``` No
101,643
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1]. This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them. Input The first line contains integer n (1 ≀ n ≀ 106) β€” the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of permutation p. Output If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≀ qi ≀ n) β€” the elements of the permutation q. If there are several solutions print any of them. Examples Input 4 2 1 4 3 Output 3 4 2 1 Input 4 2 1 3 4 Output -1 Input 5 2 3 4 5 1 Output 4 5 1 2 3 Submitted Solution: ``` n = int(input()) c = input() c = c.split(" ") c = [int(p) - 1 for p in c] visited = [0 for p in range(0,n,1)] cycle_st = [] for i in range(0,n,1): if visited[i] != 1: cycle = [] cycle.append([i,c[i]]) visited[i] = 1 d = c[i] while visited[d] != 1: cycle.append([d,c[d]]) visited[d] = 1 d = c[d] cycle_st.append(cycle) used = [ 1 for p in range(0,len(cycle_st),1)] posssible = True have_cycle =True i = 0 j = 0 for i in range(len(cycle_st)): if used[i]: have_cycle = False if(len(cycle_st[i]) % 2 == 1): for j in range(len(cycle_st[i])): visited[cycle_st[i][j][0]] = cycle_st[i][(j+2)%len(cycle_st[i])][1] else: for j in range(i+1,len(cycle_st),1): if used[j] and len(cycle_st[i]) == len(cycle_st[j]): have_cycle = True for k in range(len(cycle_st[i])): visited[cycle_st[i][k][0]] = cycle_st[j][k-1][0] visited[cycle_st[j][k-1][0]] = cycle_st[i][k-1][0] used[j] = 0 break if not have_cycle: posssible = False break if not posssible: print(-1) else: for p in visited: print(str(p+1)) ``` No
101,644
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A thief made his way to a shop. As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai. The thief is greedy, so he will take exactly k products (it's possible for some kinds to take several products of that kind). Find all the possible total costs of products the thief can nick into his knapsack. Input The first line contains two integers n and k (1 ≀ n, k ≀ 1000) β€” the number of kinds of products and the number of products the thief will take. The second line contains n integers ai (1 ≀ ai ≀ 1000) β€” the costs of products for kinds from 1 to n. Output Print the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order. Examples Input 3 2 1 2 3 Output 2 3 4 5 6 Input 5 5 1 1 1 1 1 Output 5 Input 3 3 3 5 11 Output 9 11 13 15 17 19 21 25 27 33 Submitted Solution: ``` z=input().split() nums=input().split() parts=[] possible=[] length=[] n=int(z[1])-1 for i in range(int(z[1])-1): for j in range(int(z[0])): length.append(n) parts.append(int(nums[j])*n) n=n-1 l=len(parts) for i in range(len(parts)): l1=len(parts)-1 while(l1!=i): if length[i]+length[l1]==int(z[1]): possible.append(parts[i]+parts[l1]) elif length[i]+length[l1] < int(z[1]): parts.append(parts[i]+parts[l1]) length.append(length[i]+length[l1]) l1=l1-1 possible=set(possible) possible=list(possible) possible.sort() string="" for i in range(len(possible)): string=string+str(possible[i])+" " string=string[0:len(string)-1] print(string) ``` No
101,645
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A thief made his way to a shop. As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai. The thief is greedy, so he will take exactly k products (it's possible for some kinds to take several products of that kind). Find all the possible total costs of products the thief can nick into his knapsack. Input The first line contains two integers n and k (1 ≀ n, k ≀ 1000) β€” the number of kinds of products and the number of products the thief will take. The second line contains n integers ai (1 ≀ ai ≀ 1000) β€” the costs of products for kinds from 1 to n. Output Print the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order. Examples Input 3 2 1 2 3 Output 2 3 4 5 6 Input 5 5 1 1 1 1 1 Output 5 Input 3 3 3 5 11 Output 9 11 13 15 17 19 21 25 27 33 Submitted Solution: ``` z=input().split() nums=input().split() parts=[] possible=[] length=[] n=int(z[1])-1 for i in range(int(z[1])-1): for j in range(int(z[0])): length.append(n) parts.append(int(nums[j])*n) n=n-1 for i in range(len(parts)): n=len(parts)-1 while(length[i]+length[n]<=int(z[1]) and n>=i): if (length[i]+length[n]==int(z[1])): possible.append(parts[i]+parts[n]) n=n-1 possible=set(possible) possible=list(possible) possible.sort() for i in range(len(possible)): print(str(possible[i])+" ",end='') ``` No
101,646
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A thief made his way to a shop. As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai. The thief is greedy, so he will take exactly k products (it's possible for some kinds to take several products of that kind). Find all the possible total costs of products the thief can nick into his knapsack. Input The first line contains two integers n and k (1 ≀ n, k ≀ 1000) β€” the number of kinds of products and the number of products the thief will take. The second line contains n integers ai (1 ≀ ai ≀ 1000) β€” the costs of products for kinds from 1 to n. Output Print the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order. Examples Input 3 2 1 2 3 Output 2 3 4 5 6 Input 5 5 1 1 1 1 1 Output 5 Input 3 3 3 5 11 Output 9 11 13 15 17 19 21 25 27 33 Submitted Solution: ``` z=input().split() nums=input().split() parts=[] possible=[] length=[] n=int(z[1])-1 for i in range(int(z[1])-1): for j in range(int(z[0])): length.append(n) parts.append(int(nums[j])*n) n=n-1 for i in range(len(parts)): n=len(parts)-1 while(length[i]+length[n]<=int(z[1]) and n>=i): if (length[i]+length[n]==int(z[1])): possible.append(parts[i]+parts[n]) n=n-1 possible=set(possible) possible=list(possible) possible.sort() string="" for i in range(len(possible)): string=string+str(possible[i])+" " string=string[0:len(string)-1] print(string) ``` No
101,647
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A thief made his way to a shop. As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai. The thief is greedy, so he will take exactly k products (it's possible for some kinds to take several products of that kind). Find all the possible total costs of products the thief can nick into his knapsack. Input The first line contains two integers n and k (1 ≀ n, k ≀ 1000) β€” the number of kinds of products and the number of products the thief will take. The second line contains n integers ai (1 ≀ ai ≀ 1000) β€” the costs of products for kinds from 1 to n. Output Print the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order. Examples Input 3 2 1 2 3 Output 2 3 4 5 6 Input 5 5 1 1 1 1 1 Output 5 Input 3 3 3 5 11 Output 9 11 13 15 17 19 21 25 27 33 Submitted Solution: ``` z=input().split() n=int(z[0]) k=int(z[1]) nums=input().split() parts=[int(nums[i]) for i in range(int(z[0]))] parts1=[] ini=parts.copy() possible=[] f=n for i in range(n): for j in range(i,n): parts1.append(ini[i]+parts[j]) c=2 parts=parts1.copy() parts1.clear() while(c!=k): pos=0 e=len(parts) for i in range(3): for j in range(pos,e): parts1.append(ini[i]+parts[j]) pos=pos+f-i parts=parts1.copy() parts1.clear() f=e c=c+1 possible=parts.copy() possible=set(possible) possible=list(possible) possible.sort() string="" for i in range(len(possible)): string=string+str(possible[i])+" " string=string[0:len(string)-1] print(string) ``` No
101,648
Provide tags and a correct Python 3 solution for this coding contest problem. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≀ n ≀ 300 000, 1 ≀ q ≀ 300 000) β€” the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≀ pi ≀ n) β€” the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≀ vi ≀ n) β€” the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree β€” this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 β€” both answers are considered correct. Tags: data structures, dfs and similar, dp, trees Correct Solution: ``` import operator import bisect n, q = [int(s) for s in input().split()] ps = [int(s) for s in input().split()] childs = [[] for _ in range(n)] for (c,pa) in enumerate(ps): childs[pa-1].append(c+1) toposort = [] this_level = [0] next_level = [] while len(this_level) > 0: for this_n in this_level: toposort.append(this_n) for c in childs[this_n]: next_level.append(c) this_level = next_level next_level = [] sz = [0]*n potentials = [0]*n potential_sz = [0]*n potential_lo = [0]*n centr = [0]*n for node in reversed(toposort): if len(childs[node]) == 0: centr[node] = node sz[node] = 1 else: s = 1 lg_c = -1 lg_c_sz = 0 for c in childs[node]: s += sz[c] if sz[c] > lg_c_sz: lg_c_sz = sz[c] lg_c = c sz[node] = s if lg_c_sz <= sz[node]//2: centr[node] = node potentials[node] = [node] potential_sz[node] = [sz[node]] continue potentials[node] = potentials[lg_c] potential_sz[node] = potential_sz[lg_c] i = bisect.bisect_right(potential_sz[node], sz[node]//2, lo=potential_lo[lg_c]) centr[node] = potentials[node][i] potentials[node].append(node) potential_lo[node] = i potential_sz[node].append(sz[node]) vs = [int(input()) - 1 for i in range(q)] print('\n'.join([str(centr[v]+1) for v in vs])) ```
101,649
Provide tags and a correct Python 3 solution for this coding contest problem. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≀ n ≀ 300 000, 1 ≀ q ≀ 300 000) β€” the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≀ pi ≀ n) β€” the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≀ vi ≀ n) β€” the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree β€” this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 β€” both answers are considered correct. Tags: data structures, dfs and similar, dp, trees Correct Solution: ``` def main(): import sys E=sys.stdin R=E.readline n,q=map(int,R().split()) P=[0,0]+[int(i) for i in R().split()] #n=q=300000 #P=[0]+list(range(n)) #exit() C=[[]] i=0 while i<n: i+=1 C.append([]) i=2 j=len(P) while i<j: C[P[i]].append(i) i+=1 i=Qi=0 W=[0]*(n+1) S=[0]*(n+1) Q=[0]*(n+1) while i<n: i+=1 W[i]=len(C[i]) if W[i]==0: Q[Qi]=i Qi+=1 A=[0]*(n+1) while Qi: Qi-=1 x=Q[Qi] S[x]+=1 if P[x]: y=P[x] S[y]+=S[x] W[y]-=1 if W[y]==0: Q[Qi]=y Qi+=1 a=S[x]>>1 A[x]=x for z in C[x]: if S[z]>a: A[x]=A[z] b=S[x]-S[A[x]] while b>a: A[x]=P[A[x]] b=S[x]-S[A[x]] break while q: q-=1 sys.stdout.write(str(A[int(R())])+'\n') main() ```
101,650
Provide tags and a correct Python 3 solution for this coding contest problem. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≀ n ≀ 300 000, 1 ≀ q ≀ 300 000) β€” the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≀ pi ≀ n) β€” the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≀ vi ≀ n) β€” the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree β€” this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 β€” both answers are considered correct. Tags: data structures, dfs and similar, dp, trees Correct Solution: ``` # [https://codeforces.com/contest/685/submission/42128998 <- https://codeforces.com/contest/685/status/B <- https://codeforces.com/contest/685 <- https://codeforces.com/blog/entry/45556 <- https://codeforces.com/problemset/problem/685/B <- https://algoprog.ru/material/pc685pB] import bisect n, q = [int(s) for s in input().split()] ps = [int(s) for s in input().split()] childs = [[] for _ in range(n)] for (c,pa) in enumerate(ps): childs[pa-1].append(c+1) toposort = [] this_level = [0] next_level = [] while len(this_level) > 0: for this_n in this_level: toposort.append(this_n) for c in childs[this_n]: next_level.append(c) this_level = next_level next_level = [] sz = [0]*n potentials = [0]*n potential_sz = [0]*n potential_lo = [0]*n centr = [0]*n for node in reversed(toposort): if len(childs[node]) == 0: centr[node] = node sz[node] = 1 else: s = 1 lg_c = -1 lg_c_sz = 0 for c in childs[node]: s += sz[c] if sz[c] > lg_c_sz: lg_c_sz = sz[c] lg_c = c sz[node] = s if lg_c_sz <= sz[node]//2: centr[node] = node potentials[node] = [node] potential_sz[node] = [sz[node]] continue potentials[node] = potentials[lg_c] potential_sz[node] = potential_sz[lg_c] i = bisect.bisect_right(potential_sz[node], sz[node]//2, lo=potential_lo[lg_c]) centr[node] = potentials[node][i] potentials[node].append(node) potential_lo[node] = i potential_sz[node].append(sz[node]) vs = [int(input()) - 1 for i in range(q)] print('\n'.join([str(centr[v]+1) for v in vs])) ```
101,651
Provide tags and a correct Python 3 solution for this coding contest problem. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≀ n ≀ 300 000, 1 ≀ q ≀ 300 000) β€” the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≀ pi ≀ n) β€” the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≀ vi ≀ n) β€” the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree β€” this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 β€” both answers are considered correct. Tags: data structures, dfs and similar, dp, trees Correct Solution: ``` import operator import bisect n, q = [int(s) for s in input().split()] ps = [int(s) for s in input().split()] childs = [[] for _ in range(n)] for (c,pa) in enumerate(ps): childs[pa-1].append(c+1) toposort = [] this_level = [0] next_level = [] while len(this_level) > 0: for this_n in this_level: toposort.append(this_n) for c in childs[this_n]: next_level.append(c) this_level = next_level next_level = [] sz = [0]*n potentials = [0]*n potential_sz = [0]*n potential_lo = [0]*n centr = [0]*n for node in reversed(toposort): if len(childs[node]) == 0: centr[node] = node sz[node] = 1 else: s = 1 lg_c = -1 lg_c_sz = 0 for c in childs[node]: s += sz[c] if sz[c] > lg_c_sz: lg_c_sz = sz[c] lg_c = c sz[node] = s if lg_c_sz <= sz[node]//2: centr[node] = node potentials[node] = [node] potential_sz[node] = [sz[node]] continue potentials[node] = potentials[lg_c] potential_sz[node] = potential_sz[lg_c] i = bisect.bisect_right(potential_sz[node], sz[node]//2, lo=potential_lo[lg_c]) centr[node] = potentials[node][i] potentials[node].append(node) potential_lo[node] = i potential_sz[node].append(sz[node]) vs = [int(input()) - 1 for i in range(q)] print('\n'.join([str(centr[v]+1) for v in vs])) # Made By Mostafa_Khaled ```
101,652
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≀ n ≀ 300 000, 1 ≀ q ≀ 300 000) β€” the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≀ pi ≀ n) β€” the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≀ vi ≀ n) β€” the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree β€” this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 β€” both answers are considered correct. Submitted Solution: ``` import sys def main(): x = sys.stdin.readline().split() n,r = int(x[0]),int(x[1]) x = list(map(int, sys.stdin.readline().split())) s = [ [] for i in range(n)] for i in range(n-1): s[x[i]-1].append(i+1) ch = [0]*n q = [0] u = [False]*n while len(q)!=0: c = q[len(q)-1] added = False for a in s[c]: if not u[a]: q.append(a) added = True if added: continue q.pop() u[c] = True count = 1 for a in s[c]: count+=ch[a] ch[c] = count ev = [i for i in range(n)] q = [0] w = [0] wi =0 while len(q)!=0: c = q.pop() p = ch[c]/2 for a in s[c]: if ch[a]>p: q.append(a) w.append(a) break ok = True while ok and len(w)>wi: ok = False if ch[c] <= ch[w[wi]]/2 or len(q)==0: ok=True ev[w[wi]] = c wi+=1 ans = [] for i in range(r): qi = int(sys.stdin.readline()) ans.append(str(ev[qi-1]+1)) print('\n'.join(ans)) main() ``` No
101,653
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≀ n ≀ 300 000, 1 ≀ q ≀ 300 000) β€” the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≀ pi ≀ n) β€” the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≀ vi ≀ n) β€” the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree β€” this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 β€” both answers are considered correct. Submitted Solution: ``` class Node: def __init__(self, ind): if (flag): print("init") self.index = ind self.children = [] def addChild(self, node): if (flag): print("addChild") self.children.append(node) def countV(self): if (flag): print("countV") cnt = 1 for vertex in self.children: cnt += vertex.countV() self.count = cnt return cnt def centroid(self): if (flag): print("centroid") curr = self max = self.count / 2 while True: sut = False for child in curr.children: if (child.count > max): curr = child sut = True break if (not sut): return curr.index st = input().split(" ") n = int(st[0]) q = int(st[1]) flag = n > 200000 p = input().split(" ") arr = [] for i in range(1, n + 1): arr.append(Node(i)) if (flag): print("before") index_vertex = 1 for index_parent2 in p: if (flag): print("process " + index_parent2) index_parent = int(index_parent2) - 1 arr[index_vertex].parent = index_parent arr[index_parent].addChild(arr[index_vertex]) index_vertex += 1 arr[0].countV() q_c = 0 while q_c < q: if (flag): print(arr[int(input()) - 1].centroid()) q_c += 1 ``` No
101,654
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≀ n ≀ 300 000, 1 ≀ q ≀ 300 000) β€” the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≀ pi ≀ n) β€” the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≀ vi ≀ n) β€” the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree β€” this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 β€” both answers are considered correct. Submitted Solution: ``` import operator import bisect n, q = [int(s) for s in input().split()] ps = [int(s) for s in input().split()] childs = [[] for _ in range(n)] for (c,pa) in enumerate(ps): childs[pa-1].append(c+1) toposort = [] this_level = [0] next_level = [] while len(this_level) > 0: for this_n in this_level: toposort.append(this_n) for c in childs[this_n]: next_level.append(c) this_level = next_level next_level = [] sz = [0]*n potentials = {} potential_sz = {} centr = [-1]*n for node in reversed(toposort): if len(childs[node]) == 0: centr[node] = node potentials[node] = [] sz[node] = 1 else: sz[node] = 1 + sum(sz[c] for c in childs[node]) lg_c, lg_c_sz = max( ((c, sz[c]) for c in childs[node]), key=operator.itemgetter(1) ) if lg_c_sz <= sz[node]/2: centr[node] = node potentials[node] = [node] potential_sz[node] = [sz[node]] continue potentials[node] = potentials[lg_c] potential_sz[node] = potential_sz[lg_c] i = bisect.bisect_right(potential_sz[node], sz[node]/2) centr[node] = potentials[node][i] potentials[node].append(node) potential_sz[node].append(sz[node]) def find_centroid(v, baggage): if v not in lg_c: return v if baggage + (sz[v]-lg_sz[v]) >= lg_sz[v]: return v return find_centroid(lg_c[v], baggage + (sz[v] - lg_sz[v])) vs = [] for i in range(q): vs.append(int(input()) - 1) print(*vs, sep='\n') ``` No
101,655
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≀ n ≀ 300 000, 1 ≀ q ≀ 300 000) β€” the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≀ pi ≀ n) β€” the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≀ vi ≀ n) β€” the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree β€” this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 β€” both answers are considered correct. Submitted Solution: ``` import sys import threading sys.setrecursionlimit(200000) class Node: def __init__(self, ind): self.index = ind self.children = [] self.max_child = 0 def addChild(self, node): self.children.append(node) if (self.max_child == 0 or type(self.max_child) == Node and self.max_child.count < node.count): self.max_child = node def countV(self): cnt = 1 for vertex in self.children: cnt += vertex.countV() self.count = cnt return cnt def centroid(self): curr = self max = self.count / 2 while True: # sut = False child = self.max_child if (child.count > max): curr = child else: return curr.index # for child in curr.children: # if (child.count > max): # curr = child # sut = True # break # if (not sut): # return curr.index class Run: def __call__(self): st = input().split(" ") n = int(st[0]) q = int(st[1]) # flag = n > 200000 p = input().split(" ") arr = [] for i in range(1, n + 1): arr.append(Node(i)) index_vertex = 1 for index_parent2 in p: index_parent = int(index_parent2) - 1 arr[index_vertex].parent = index_parent arr[index_parent].addChild(arr[index_vertex]) index_vertex += 1 # try: arr[0].countV() # except BaseException as err: # print(err) # print(type(err)) # if (flag): print("before") q_c = 0 while q_c < q: # if (flag): print("after") print(arr[int(input()) - 1].centroid()) q_c += 1 threading.stack_size(0x2000000) t = threading.Thread(target=Run()) t.start() t.join() ``` No
101,656
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Tags: constructive algorithms, greedy, implementation, strings Correct Solution: ``` x=input() y=list(x) i=0 d=-1 for c in x: if c=='a': if d!=-1: break i+=1 continue if d==-1: d=i y[i]=chr(ord(y[i])-1) i+=1 if d==-1: y[-1]='z' print("".join(y)) ```
101,657
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Tags: constructive algorithms, greedy, implementation, strings Correct Solution: ``` from sys import stdin phrase=input() i=0 while i<len(phrase) and phrase[i]=='a': i+=1 j=i while j<len(phrase) and phrase[j]!='a': j+=1 if i>=len(phrase): print(phrase[:-1]+"z") else: nouvellePhrase=phrase[:i] for indice in range(i,j): caractere=phrase[indice] nouvelIndice= (ord(caractere)-ord('a')-1)%26 car=chr(nouvelIndice+ord('a')) nouvellePhrase+=car nouvellePhrase+=phrase[j:] print(nouvellePhrase) ```
101,658
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Tags: constructive algorithms, greedy, implementation, strings Correct Solution: ``` letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g','h', 'i', 'j', 'k', 'l', 'm', 'n', \ 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] dataIn = str(input()) data = [] for i in dataIn: data.append(i) count = 0 begin = 0 if len(data) == 1: if data[0] == 'a': data[0] = 'z' else: for j in range(len(letters)): if letters[j] == data[0]: data[0] = letters[j-1] else: i = 0 begin = False while i < len(data) - 1: if data[i] == 'a': i += 1 else: break for k in range(i, len(data)): if data[k] == 'a' and k != len(data) - 1: break elif data[k] == 'a' and k == len(data) -1: if not begin: data[k] = 'z' else: begin = True for j in range(len(letters)): if letters[j] == data[k]: data[k] = letters[j-1] result = ''.join(data) print(result) ```
101,659
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Tags: constructive algorithms, greedy, implementation, strings Correct Solution: ``` s1=input() s=list(s1) start=-1 end=-1 for i in range(len(s)): if(s[i]>'a' and start==-1): start=i elif(s[i]=='a' and start!=-1): end=i break; if(end==-1): end=len(s) if(start==-1): s[len(s)-1]='z' else: for i in range(start,end): p=ord(s[i])-1 s[i]= chr(p) s1="".join(s) print(s1) ```
101,660
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Tags: constructive algorithms, greedy, implementation, strings Correct Solution: ``` s = input() i = 0; b = False while i < len(s) and s[i] == 'a': i += 1 while i < len(s) and s[i] != 'a': s = s[:i] + chr(ord(s[i]) - 1) + s[i + 1:] i += 1 b = True print(s if b else 'a' * (len(s) - 1) + 'z') ```
101,661
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Tags: constructive algorithms, greedy, implementation, strings Correct Solution: ``` def findNot(string, char): for i in range(len(string)): if string[i] != char: return i return len(string) - 1 s = input() beg = findNot(s, "a") res = s[0:beg] for i in range(beg, len(s)): if i != beg and s[i] == "a": res += s[i:] break if s[i] == "a": res += "z" else: res += chr(ord(s[i]) - 1) print(res) ```
101,662
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Tags: constructive algorithms, greedy, implementation, strings Correct Solution: ``` # You lost the game. s = str(input()) n = len(s) i = 0 A = "abcdefghijklmnopqrstuvwxyz" while i < n and s[i] == 'a': i += 1 if i == n: print(s[:n-1]+"z") else: d = i while i < n and s[i] != 'a': i += 1 r = "" for j in range(d,i): if s[j] == "a": r += "z" else: r += A[A.index(s[j])-1] print(s[:d]+r+s[i:]) ```
101,663
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Tags: constructive algorithms, greedy, implementation, strings Correct Solution: ``` s = [i for i in input()] flag = False for i in range(len(s)): if s[i] > "a": flag = True s[i] = chr(ord(s[i])-1) elif flag: break if not flag: s[-1] = "z" print(*s, sep="") ```
101,664
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Submitted Solution: ``` import sys s = input() L = len(s) #chr(48) = '0' #ord('a') = 97 t = "" i = 0 while i < L and s[i] == 'a': t += s[i] i += 1 if len(t) == L: print(s[:L-1]+'z') sys.exit() while i < L and s[i] != 'a': t += chr(ord(s[i])-1) i += 1 t += s[i:] print(t) ``` Yes
101,665
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Submitted Solution: ``` s=list(input()) count=0 count1=0 y=0 if s.count('a')==len(s): print('a'*(len(s)-1)+'z') elif s[0]!='a' or s[1]!='a': for i in range(len(s)): if s[i]=='a' and i!=0: count=1 print('a',end='') break elif s[i]=='a' and i==0: print('a',end='') else: print((chr(ord(s[i]) - 1)),end='') if count==1: for i in range(i+1,len(s)): print(s[i],end='') else: for i in range(len(s)): if s[i]=='a': print('a',end='') count1+=1 else: break for j in range(i,len(s)): if s[j]!='a': print(chr(ord(s[j])-1),end='') count1+=1 else: break for i in range(j,len(s)): if count1<len(s): print(s[i],end='') ``` Yes
101,666
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Submitted Solution: ``` s = input() start = -1 end = -1 for i in range(len(s)): if s[i] != 'a': if start < 0: start = i end = i else: end = i if s[i] == 'a' and start >= 0: break if start < 0: print(s[0:len(s)-1], end="") print('z') else: for i in range(len(s)): if start <= i <= end: if s[i] == 'a': print('z', end="") else: print(chr(ord(s[i]) - 1), end="") else: print(s[i], end="") ``` Yes
101,667
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Submitted Solution: ``` s = list(input()) n = len(s) L = 0 while L < n and s[L] == 'a': L += 1 R = L while R < n and s[R] != 'a': R += 1 for i in range(L, R): if s[i] == 'a': s[i] = 'z' else: s[i] = chr(ord(s[i]) - 1) if L == R == n: s[-1] = 'z' print(''.join(s)) ``` Yes
101,668
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Submitted Solution: ``` s=input() if s[0]!="a": r="" for i in range(len(s)): if s[i]=="a": y="z" else: x=ord(s[i]) y=chr(x-1) if y>s[i]: r+=s[i:] break else: r+=y print(r) else: b=0;flag=0 for i in range(1,len(s)): if s[i]<s[i-1]: b=i-1 flag=1 break if flag: r="" r+=s[:b] f=0 for i in range(b,len(s)): if s[i]=="a": y="z" else: x=ord(s[i]) y=chr(x-1) if y>s[i]: r+=s[i:] break else: r+=y print(r) else: r="" r+=s[:b] f=0 for i in range(b,len(s)): if s[i]=="a": y="z" else: x=ord(s[i]) y=chr(x-1) if y>s[i]: r+=s[i:] break else: r+=y print(r) ``` No
101,669
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Submitted Solution: ``` s = input() z = 0 while z < len(s) and s[z] == 'a': print('a', end='') z += 1 while z < len(s) and s[z] != 'a': print(chr(ord(s[z]) - 1), end='') z += 1 while z < len(s): print(s[z], end='') z += 1 ``` No
101,670
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Submitted Solution: ``` s = list(input()) n = len(s) strat , end = -1 , -1 for i in range(n): if s[i] > 'a' and strat == -1: strat = i elif s[i] == 'a' and strat != -1: end = i break #print(strat , end) if end == -1: end = n - 1 if strat == -1: s[n - 1] = 'z' print(''.join(s)) else: for i in range(strat , end): x = ord(s[i]) - 1 s[i] = chr(x) print(''.join(s)) ``` No
101,671
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? Input The only line of the input contains the string s (1 ≀ |s| ≀ 100 000) consisting of lowercase English letters. Output Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring. Examples Input codeforces Output bncdenqbdr Input abacaba Output aaacaba Note String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≀ i ≀ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti. Submitted Solution: ``` s = input() l = 'abcdefghijklmnopqrstuvwxyz' k = '' i = 0 while s[i] == 'a' and i < len(s)-1: i = i+1 k = s[:i] for j in range(i,len(s)): if s[j] != 'a': k+=(l[l.find(s[j])-1]) else: break for f in range(len(k),len(s)): k+=s[f] if s == 'a': print('z') else: print(k) ``` No
101,672
Provide tags and a correct Python 3 solution for this coding contest problem. One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β€” it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? Input The first line of the input contains a single integer n (1 ≀ n ≀ 30) β€” the total depth of the recursion. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding. Output Print one integer, denoting the number of cells which will be visited at least once by any part of the firework. Examples Input 4 4 2 2 3 Output 39 Input 6 1 1 1 1 1 3 Output 85 Input 1 3 Output 3 Note For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. <image> For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level. <image> Tags: brute force, data structures, dfs and similar, dp, implementation Correct Solution: ``` import sys plane = set() crackers = {((0, -1), (0, 1))} n = int(input()) a = [int(x) for x in input().split()] crack_dict = { (1, 0): ((1, -1), (1, 1)), (1, 1): ((1, 0), (0, 1)), (0, 1): ((1, 1), (-1, 1)), (-1, 1): ((0, 1), (-1, 0)), (-1, 0): ((-1, 1), (-1, -1)), (-1, -1): ((-1, 0), (0, -1)), (0, -1): ((-1, -1), (1, -1)), (1, -1): ((0, -1), (1, 0)), } def move(cracker): point, direc = cracker point2 = (point[0] + direc[0], point[1] + direc[1]) return (point2, direc) def crack(cracker): point, direc = cracker direc1, direc2 = crack_dict[direc] return ((point, direc1), (point, direc2)) for x in a: for i in range(x): crackers = set((move(cracker) for cracker in crackers)) plane.update((cracker[0] for cracker in crackers)) # print(plane, file=sys.stderr) new_crackers = set() for cracker in crackers: new_crackers.update(crack(cracker)) crackers = new_crackers print(len(plane)) ```
101,673
Provide tags and a correct Python 3 solution for this coding contest problem. One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β€” it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? Input The first line of the input contains a single integer n (1 ≀ n ≀ 30) β€” the total depth of the recursion. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding. Output Print one integer, denoting the number of cells which will be visited at least once by any part of the firework. Examples Input 4 4 2 2 3 Output 39 Input 6 1 1 1 1 1 3 Output 85 Input 1 3 Output 3 Note For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. <image> For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level. <image> Tags: brute force, data structures, dfs and similar, dp, implementation Correct Solution: ``` k = int(input()) & 1 p = [] s = range(1, 6) for q in map(int, input().split()[::-1]): if k: p += [(x, -y) for x, y in p] p = [(x - q, y) for x, y in p] p += [(-x, 0) for x in s[:q]] else: p += [(y, -x) for x, y in p] p = [(x - q, y + q) for x, y in p] p += [(-x, x) for x in s[:q]] p = list(set(p)) k = 1 - k print(len(p)) ```
101,674
Provide tags and a correct Python 3 solution for this coding contest problem. One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β€” it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? Input The first line of the input contains a single integer n (1 ≀ n ≀ 30) β€” the total depth of the recursion. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding. Output Print one integer, denoting the number of cells which will be visited at least once by any part of the firework. Examples Input 4 4 2 2 3 Output 39 Input 6 1 1 1 1 1 3 Output 85 Input 1 3 Output 3 Note For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. <image> For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level. <image> Tags: brute force, data structures, dfs and similar, dp, implementation Correct Solution: ``` from math import sin def mp(): return map(int,input().split()) def lt(): return list(map(int,input().split())) def pt(x): print(x) def ip(): return input() def it(): return int(input()) def sl(x): return [t for t in x] def spl(x): return x.split() def aj(liste, item): liste.append(item) def bin(x): return "{0:b}".format(x) def listring(l): return ' '.join([str(x) for x in l]) def ptlist(l): print(' '.join([str(x) for x in l])) n = it() step = lt() dict = {} def explosion(start,s,d): (i,j) = start t = s+1 if d == 0: for k in range(j+1,j+t): dict[(i,k)] = True return ((i,j+t-1),(d+7)%8),((i,j+t-1),(d+1)%8) if d == 1: for k in range(1,t): dict[(i+k,j+k)] = True return ((i+t-1,j+t-1),(d+7)%8),((i+t-1,j+t-1),(d+1)%8) if d == 2: for k in range(1,t): dict[(i+k,j)] = True return ((i+t-1,j),(d+7)%8),((i+t-1,j),(d+1)%8) if d == 3: for k in range(1,t): dict[(i+k,j-k)] = True return ((i+t-1,j-t+1),(d+7)%8),((i+t-1,j-t+1),(d+1)%8) if d == 4: for k in range(1,t): dict[(i,j-k)] = True return ((i,j-t+1),(d+7)%8),((i,j-t+1),(d+1)%8) if d == 5: for k in range(1,t): dict[(i-k,j-k)] = True return ((i-t+1,j-t+1),(d+7)%8),((i-t+1,j-t+1),(d+1)%8) if d == 6: for k in range(1,t): dict[(i-k,j)] = True return ((i-t+1,j),(d+7)%8),((i-t+1,j),(d+1)%8) if d == 7: for k in range(1,t): dict[(i-k,j+k)] = True return ((i-t+1,j+t-1),(d+7)%8),((i-t+1,j+t-1),(d+1)%8) start = [((0,0),0)] for i in range(n): l = [] for p,q in start: a,b = explosion(p,step[i],q) l.append(a) l.append(b) start = set(l) pt(len(dict)) ```
101,675
Provide tags and a correct Python 3 solution for this coding contest problem. One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β€” it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? Input The first line of the input contains a single integer n (1 ≀ n ≀ 30) β€” the total depth of the recursion. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding. Output Print one integer, denoting the number of cells which will be visited at least once by any part of the firework. Examples Input 4 4 2 2 3 Output 39 Input 6 1 1 1 1 1 3 Output 85 Input 1 3 Output 3 Note For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. <image> For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level. <image> Tags: brute force, data structures, dfs and similar, dp, implementation Correct Solution: ``` #!/usr/bin/env python3 from sys import stdin,stdout def ri(): return map(int, input().split()) w = 15 adding = [(0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1)] def fill(x, y,dir,depth): for i in range(t[depth]): x += adding[dir][0] y += adding[dir][1] v[x][y] = 1 def dfs(x, y, dir, depth): if depth == n: return #print(T, dir, depth) if (dir, depth) in T[x][y]: #print("found") #print(T, dir, depth) return fill(x,y,dir,depth) ndepth = depth+1 nx = x + adding[dir][0]*t[depth] ny = y + adding[dir][1]*t[depth] ndir = (dir+1)%8 dfs(nx, ny, ndir, ndepth) ndir = (8+dir-1)%8 dfs(nx, ny, ndir, ndepth) T[x][y].add(tuple((dir, depth))) n = int(input()) t = list(ri()) v = [[0 for i in range(n*w)] for j in range(n*w)] T = [[set() for i in range(n*w)] for j in range(n*w)] # x, y, dir, depth dfs(n*w//2, n*w//2, 0, 0) ans = 0 for i in range(n*w): for j in range(n*w): if v[i][j]: ans +=1 print(ans) ```
101,676
Provide tags and a correct Python 3 solution for this coding contest problem. One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β€” it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? Input The first line of the input contains a single integer n (1 ≀ n ≀ 30) β€” the total depth of the recursion. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding. Output Print one integer, denoting the number of cells which will be visited at least once by any part of the firework. Examples Input 4 4 2 2 3 Output 39 Input 6 1 1 1 1 1 3 Output 85 Input 1 3 Output 3 Note For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. <image> For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level. <image> Tags: brute force, data structures, dfs and similar, dp, implementation Correct Solution: ``` dr = [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]] n = int(input()) t = [int(i) for i in input().split()] visited = set() N = 150*2 + 10 covers = [[0]*N for i in range(N)] def dfs(d, pos, path): mem = (d, pos, path) if mem in visited: return set() else: visited.add(mem) if d == n+1: return for _ in range(t[d-1]): pos = (pos[0] + dr[path][0], pos[1] + dr[path][1]) covers[pos[0]][pos[1]] = 1 dfs(d+1, pos, (path+1) % 8) dfs(d+1, pos, (path-1) % 8) dfs(1, (int(N/2), int(N/2)), 0) print(sum([sum(i) for i in covers])) ```
101,677
Provide tags and a correct Python 3 solution for this coding contest problem. One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β€” it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? Input The first line of the input contains a single integer n (1 ≀ n ≀ 30) β€” the total depth of the recursion. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding. Output Print one integer, denoting the number of cells which will be visited at least once by any part of the firework. Examples Input 4 4 2 2 3 Output 39 Input 6 1 1 1 1 1 3 Output 85 Input 1 3 Output 3 Note For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. <image> For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level. <image> Tags: brute force, data structures, dfs and similar, dp, implementation Correct Solution: ``` from collections import defaultdict dx = [0,-1,-1,-1, 0, 1, 1,1] dy = [1, 1, 0,-1,-1,-1, 0,1] #visited =[[[[False for _ in range(32)] for _ in range(8)] for _ in range(320)] for _ in range(320)] visited = defaultdict(lambda : False) grid = [[False for _ in range(320)] for _ in range(320)] def dfs(x,y,d,n,N, inp): if n >= N or visited[(x,y,d,n)]: return visited[(x,y,d,n)] = True dist = inp[n] for i in range(1,dist+1): grid[x+dx[d]*i][y+i*dy[d]] = True if (n < N): dfs(x + dx[d]*dist, y+dy[d]*dist, (d+1)%8, n+1,N,inp) dfs(x + dx[d]*dist, y+dy[d]*dist, (d+7)%8, n+1,N,inp) if __name__ == "__main__": N = int(input()) inp = list(map(int, input().strip().split())) dfs(160,160,0,0,N,inp) result = sum(map(sum,grid)) print(result) ```
101,678
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β€” it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? Input The first line of the input contains a single integer n (1 ≀ n ≀ 30) β€” the total depth of the recursion. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding. Output Print one integer, denoting the number of cells which will be visited at least once by any part of the firework. Examples Input 4 4 2 2 3 Output 39 Input 6 1 1 1 1 1 3 Output 85 Input 1 3 Output 3 Note For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. <image> For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level. <image> Submitted Solution: ``` #!/usr/bin/env python DIRS = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)] def main(): n = int(input()) T = list(map(int, input().split())) dp = dict() dfs(0, T, 0, 0, 0, dp, last=True) print(len(dp)) def dfs(i, T, x, y, d, dp, last=False): n = len(T) if i == n: return p = (x, y) if p not in dp: dp[p] = dict() if i not in dp[p]: dp[p][i] = set() if d in dp[p][i]: return dp[p][i].add(d) t = T[i] while t > 1: x += DIRS[d][0] y += DIRS[d][1] p = (x, y) if p not in dp: dp[p] = dict() t -= 1 left = (d - 1) % 8 dfs(i + 1, T, x + DIRS[left][0], y + DIRS[left][1], left, dp, last=False) right = (d + 1) % 8 dfs(i + 1, T, x + DIRS[right][0], y + DIRS[right][1], right, dp, last=last) if last: print('Finish level %d.' % i) if __name__ == '__main__': main() ``` No
101,679
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β€” it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? Input The first line of the input contains a single integer n (1 ≀ n ≀ 30) β€” the total depth of the recursion. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding. Output Print one integer, denoting the number of cells which will be visited at least once by any part of the firework. Examples Input 4 4 2 2 3 Output 39 Input 6 1 1 1 1 1 3 Output 85 Input 1 3 Output 3 Note For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. <image> For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level. <image> Submitted Solution: ``` from sys import stdin, stdout from collections import deque sze = 500; used = set() n = int(stdin.readline()) value = list(map(int, stdin.readline().split())) + [1] value[0] -= 1 visit = [[0 for i in range(sze)] for j in range(sze)] queue = deque([(250, 250, 0, 1)]) while queue[0][2] < n: y, x, num, d = queue.popleft() for j in range(value[num] + 1): if d == 1: visit[y - j][x] = 1 elif d == 2: visit[y - j][x - j] = 1 elif d == 3: visit[y][x - j] = 1 elif d == 4: visit[y + j][x - j] = 1 elif d == 5: visit[y + j][x] = 1 elif d == 6: visit[y + j][x + j] = 1 elif d == 7: visit[y][x + j] = 1 elif d == 8: visit[y - j][x + j] = 1 if d == 1: f = (y - value[num], x, value[num + 1], 2) s = (y - value[num], x, value[num + 1], 8) if not f in used: used.add(f) queue.append((y - value[num], x, num + 1, 2)) if not s in used: used.add(s) queue.append((y - value[num], x, num + 1, 8)) elif d == 2: f = (y - value[num], x - value[num], value[num + 1], 3) s = (y - value[num], x - value[num], value[num + 1], 1) if not f in used: used.add(f) queue.append((y - value[num], x - value[num], num + 1, 3)) if not s in used: used.add(s) queue.append((y - value[num], x - value[num], num + 1, 1)) elif d == 3: f = (y, x - value[num], value[num + 1], 4) s = (y, x - value[num], value[num + 1], 2) if not f in used: used.add(f) queue.append((y, x - value[num], num + 1, 4)) if not s in used: used.add(s) queue.append((y, x - value[num], num + 1, 2)) elif d == 4: f = (y + value[num], x - value[num], value[num + 1], 5) s = (y + value[num], x - value[num], value[num + 1], 3) if not f in used: used.add(f) queue.append((y + value[num], x - value[num], num + 1, 5)) if not s in used: used.add(s) queue.append((y + value[num], x - value[num], num + 1, 3)) elif d == 5: f = (y + value[num], x, value[num + 1], 6) s = (y + value[num], x, value[num + 1], 4) if not f in used: used.add(f) queue.append((y + value[num], x, num + 1, 6)) if not s in used: used.add(s) queue.append((y + value[num], x, num + 1, 4)) elif d == 6: f = (y + value[num], x + value[num], value[num + 1], 7) s = (y + value[num], x + value[num], value[num + 1], 5) if not f in used: used.add(f) queue.append((y + value[num], x + value[num], num + 1, 7)) if not s in used: used.add(s) queue.append((y + value[num], x + value[num], num + 1, 5)) elif d == 7: f = (y, x + value[num], value[num + 1], 8) s = (y, x + value[num], value[num + 1], 6) if not f in used: used.add(f) queue.append((y, x + value[num], num + 1, 8)) if not s in used: used.add(s) queue.append((y, x + value[num], num + 1, 6)) elif d == 8: f = (y - value[num], x + value[num], value[num + 1], 7) s = (y - value[num], x + value[num], value[num + 1], 1) if not f in used: used.add(f) queue.append((y - value[num], x + value[num], num + 1, 7)) if not s in used: used.add(s) queue.append((y - value[num], x + value[num], num + 1, 1)) ans = 0 for i in range(sze): for j in range(sze): if visit[i][j]: ans += 1 stdout.write(str(ans)) ``` No
101,680
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β€” it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? Input The first line of the input contains a single integer n (1 ≀ n ≀ 30) β€” the total depth of the recursion. The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding. Output Print one integer, denoting the number of cells which will be visited at least once by any part of the firework. Examples Input 4 4 2 2 3 Output 39 Input 6 1 1 1 1 1 3 Output 85 Input 1 3 Output 3 Note For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. <image> For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level. <image> Submitted Solution: ``` import time coord = set() flows = int(input()) start = time.time() t = list(map(int, input().split())) directions = {0: (0, 1), 1: (1, 1), 2: (1, 0), 3: (1, -1), 4: (0, -1), 5: (-1, -1), 6: (-1, 0), 7: (-1, 1)} was = [[[[0] * 300 for d2 in range(300)] for d3 in range(31)] for d4 in range(8)] #print(time.time()-start) def flight(n, x=0, y=0, direction=0): if was[direction][n][x][y]: return was[direction][n][x][y] = 1 if n: for _ in range(t[flows - n]): x += directions[direction][0] y += directions[direction][1] coord.add((x, y)) flight(n - 1, x, y, (direction + 1) % 8) flight(n - 1, x, y, (direction - 1) % 8) flight(flows) print(len(coord)) #print(time.time()-start) ``` No
101,681
Provide tags and a correct Python 3 solution for this coding contest problem. Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters β€” its significance ci and width wi. Stepan decided to expose some of his cups on a shelf with width d in such a way, that: * there is at least one Physics cup and at least one Informatics cup on the shelf, * the total width of the exposed cups does not exceed d, * from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too). Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups. Input The first line contains three integers n, m and d (1 ≀ n, m ≀ 100 000, 1 ≀ d ≀ 109) β€” the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf. Each of the following n lines contains two integers ci and wi (1 ≀ ci, wi ≀ 109) β€” significance and width of the i-th cup for Physics olympiads. Each of the following m lines contains two integers cj and wj (1 ≀ cj, wj ≀ 109) β€” significance and width of the j-th cup for Informatics olympiads. Output Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement. If there is no way to expose cups on the shelf, then print 0. Examples Input 3 1 8 4 2 5 5 4 2 3 2 Output 8 Input 4 3 12 3 4 2 4 3 5 3 4 3 5 5 2 3 4 Output 11 Input 2 2 2 5 3 6 3 4 2 8 1 Output 0 Note In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8. Tags: *special, binary search, data structures, two pointers Correct Solution: ``` n, m, d = list(map(int, input().split())) a = [] b = [] for i in range(n): a.append(list(map(int, input().split()))) for i in range(m): b.append(list(map(int, input().split()))) a = sorted(a, key=lambda x: x[0] + (1- x[1] * 1e-10)) b = sorted(b, key=lambda x: x[0] + (1- x[1] * 1e-10)) tc, td = 0, 0 tc += a[-1][0] tc += b[-1][0] td += a[-1][1] td += b[-1][1] ai = n - 1 bi = m - 1 if td > d: print(0) exit() while ai > 0: t = ai - 1 if td + a[t][1] <= d: td += a[t][1] tc += a[t][0] ai -= 1 continue else: break cmax = tc while bi > 0: bi -= 1 tc += b[bi][0] td += b[bi][1] while td > d and ai < n: tc -= a[ai][0] td -= a[ai][1] ai += 1 if ai == n: break if td <= d: cmax = max(cmax, tc) print(cmax) ```
101,682
Provide tags and a correct Python 3 solution for this coding contest problem. Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters β€” its significance ci and width wi. Stepan decided to expose some of his cups on a shelf with width d in such a way, that: * there is at least one Physics cup and at least one Informatics cup on the shelf, * the total width of the exposed cups does not exceed d, * from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too). Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups. Input The first line contains three integers n, m and d (1 ≀ n, m ≀ 100 000, 1 ≀ d ≀ 109) β€” the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf. Each of the following n lines contains two integers ci and wi (1 ≀ ci, wi ≀ 109) β€” significance and width of the i-th cup for Physics olympiads. Each of the following m lines contains two integers cj and wj (1 ≀ cj, wj ≀ 109) β€” significance and width of the j-th cup for Informatics olympiads. Output Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement. If there is no way to expose cups on the shelf, then print 0. Examples Input 3 1 8 4 2 5 5 4 2 3 2 Output 8 Input 4 3 12 3 4 2 4 3 5 3 4 3 5 5 2 3 4 Output 11 Input 2 2 2 5 3 6 3 4 2 8 1 Output 0 Note In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8. Tags: *special, binary search, data structures, two pointers Correct Solution: ``` n, m, d = map(int, input().split()) ph = [[int(j) for j in input().split()] for i in range(n)] inf = [[int(j) for j in input().split()] for i in range(m)] for i in range(n): ph[i][1] = -ph[i][1] for i in range(m): inf[i][1] = -inf[i][1] ph.sort(reverse=True) inf.sort(reverse=True) sw, sc = 0, 0 for p in inf: sc += p[0] d += p[1] ans = 0 z = m - 1 for p in ph: sc += p[0] d += p[1] #print(sc, d) while z > 0 and d < 0: sc -= inf[z][0] d -= inf[z][1] z -= 1 #print(sc, d) if d >= 0: ans = max(ans, sc) print(ans) ```
101,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters β€” its significance ci and width wi. Stepan decided to expose some of his cups on a shelf with width d in such a way, that: * there is at least one Physics cup and at least one Informatics cup on the shelf, * the total width of the exposed cups does not exceed d, * from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too). Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups. Input The first line contains three integers n, m and d (1 ≀ n, m ≀ 100 000, 1 ≀ d ≀ 109) β€” the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf. Each of the following n lines contains two integers ci and wi (1 ≀ ci, wi ≀ 109) β€” significance and width of the i-th cup for Physics olympiads. Each of the following m lines contains two integers cj and wj (1 ≀ cj, wj ≀ 109) β€” significance and width of the j-th cup for Informatics olympiads. Output Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement. If there is no way to expose cups on the shelf, then print 0. Examples Input 3 1 8 4 2 5 5 4 2 3 2 Output 8 Input 4 3 12 3 4 2 4 3 5 3 4 3 5 5 2 3 4 Output 11 Input 2 2 2 5 3 6 3 4 2 8 1 Output 0 Note In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8. Submitted Solution: ``` class Mcl: def __init__(self, a, b): self.c = a self.w = b def __lt__(a, b): return a.c < b.c or a.c == b.c and a.w > b.w def __gt__(a, b): return a.c > b.c or a.c == b.c and a.w < b.w def __repr__(self): return "(" + str(self.c) + ", " + str(self.w) + ")" def main(): n, m, d = tuple(map(int, input().split())) a = [Mcl(0, 0) for i in range(n)] b = [Mcl(0, 0) for i in range(m)] for i in range(n): tpl = tuple(map(int, input().split())) a[i] = Mcl(tpl[0], tpl[1]) for i in range(m): tpl = tuple(map(int, input().split())) b[i] = Mcl(tpl[0], tpl[1]) cur_width = d ans = 0 a.sort() b.sort() #print(a) #print(b) idx = n - 1 jdx = m - 1 phis = False inform = False while (cur_width > 0): #print(cur_width) if a[idx].w < cur_width and b[jdx].w < cur_width: if a[idx].c > b[jdx].c: phis = True cur_width -= a[idx].w idx -= 1 ans += a[idx].c else: inform = True cur_width -= b[jdx].w jdx -= 1 ans += b[jdx].c elif a[idx].w < cur_width: phis = True cur_width -= a[idx].w idx -= 1 ans += a[idx].c elif b[jdx].w < cur_width: inform = True cur_width -= b[jdx].w jdx -= 1 ans += b[jdx].c else: break if phis is True and inform is True: print(ans) else: print(0) main() ``` No
101,684
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters β€” its significance ci and width wi. Stepan decided to expose some of his cups on a shelf with width d in such a way, that: * there is at least one Physics cup and at least one Informatics cup on the shelf, * the total width of the exposed cups does not exceed d, * from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too). Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups. Input The first line contains three integers n, m and d (1 ≀ n, m ≀ 100 000, 1 ≀ d ≀ 109) β€” the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf. Each of the following n lines contains two integers ci and wi (1 ≀ ci, wi ≀ 109) β€” significance and width of the i-th cup for Physics olympiads. Each of the following m lines contains two integers cj and wj (1 ≀ cj, wj ≀ 109) β€” significance and width of the j-th cup for Informatics olympiads. Output Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement. If there is no way to expose cups on the shelf, then print 0. Examples Input 3 1 8 4 2 5 5 4 2 3 2 Output 8 Input 4 3 12 3 4 2 4 3 5 3 4 3 5 5 2 3 4 Output 11 Input 2 2 2 5 3 6 3 4 2 8 1 Output 0 Note In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8. Submitted Solution: ``` # in = open("input.txt", "r") # out = open("output.txt", "w") n, l, r = list(map(int, input().split())) l -= 1 r -= 1 a = list(map(int, input().split())) b = list(map(int, input().split())) c = 1 for i in range(0, l): if a[i] != b[i]: c = 0 for i in range(r + 1, n): if a[i] != b[i]: c = 0 if(c == 1): print("TRUTH") else: print("LIE") import time, sys sys.stderr.write('{0:.3f} ms\n'.format(time.clock() * 1000)) ``` No
101,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters β€” its significance ci and width wi. Stepan decided to expose some of his cups on a shelf with width d in such a way, that: * there is at least one Physics cup and at least one Informatics cup on the shelf, * the total width of the exposed cups does not exceed d, * from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too). Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups. Input The first line contains three integers n, m and d (1 ≀ n, m ≀ 100 000, 1 ≀ d ≀ 109) β€” the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf. Each of the following n lines contains two integers ci and wi (1 ≀ ci, wi ≀ 109) β€” significance and width of the i-th cup for Physics olympiads. Each of the following m lines contains two integers cj and wj (1 ≀ cj, wj ≀ 109) β€” significance and width of the j-th cup for Informatics olympiads. Output Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement. If there is no way to expose cups on the shelf, then print 0. Examples Input 3 1 8 4 2 5 5 4 2 3 2 Output 8 Input 4 3 12 3 4 2 4 3 5 3 4 3 5 5 2 3 4 Output 11 Input 2 2 2 5 3 6 3 4 2 8 1 Output 0 Note In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8. Submitted Solution: ``` class Mcl: def __init__(self, a, b): self.c = a self.w = b def __lt__(a, b): return a.c < b.c or a.c == b.c and a.w > b.w def __gt__(a, b): return a.c > b.c or a.c == b.c and a.w < b.w def __repr__(self): return "(" + str(self.c) + ", " + str(self.w) + ")" def main(): n, m, d = tuple(map(int, input().split())) a = [Mcl(0, 0) for _ in range(n)] b = [Mcl(0, 0) for _ in range(m)] for i in range(n): tpl = tuple(map(int, input().split())) a[i] = Mcl(tpl[0], tpl[1]) for i in range(m): tpl = tuple(map(int, input().split())) b[i] = Mcl(tpl[0], tpl[1]) cur_width = d ans = 0 a.sort() b.sort() idx = n - 1 jdx = m - 1 if a[idx].w + b[jdx].w <= cur_width: cur_width -= a[idx].w cur_width -= b[jdx].w ans += a[idx].c ans += b[jdx].c idx -= 1 jdx -= 1 else: print(0) return while cur_width > 0: if a[idx].w <= cur_width and b[jdx].w <= cur_width: if a[idx].c > b[jdx].c: cur_width -= a[idx].w ans += a[idx].c idx -= 1 elif a[idx].c < b[jdx].c: cur_width -= b[jdx].w ans += b[jdx].c jdx -= 1 else: if a[idx].w < b[jdx].w: cur_width -= a[idx].w ans += a[idx].c idx -= 1 else: cur_width -= b[jdx].w ans += b[jdx].c jdx -= 1 elif a[idx].w <= cur_width: cur_width -= a[idx].w ans += a[idx].c idx -= 1 elif b[jdx].w <= cur_width: cur_width -= b[jdx].w ans += b[jdx].c jdx -= 1 else: break print(ans) main() ``` No
101,686
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters β€” its significance ci and width wi. Stepan decided to expose some of his cups on a shelf with width d in such a way, that: * there is at least one Physics cup and at least one Informatics cup on the shelf, * the total width of the exposed cups does not exceed d, * from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too). Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups. Input The first line contains three integers n, m and d (1 ≀ n, m ≀ 100 000, 1 ≀ d ≀ 109) β€” the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf. Each of the following n lines contains two integers ci and wi (1 ≀ ci, wi ≀ 109) β€” significance and width of the i-th cup for Physics olympiads. Each of the following m lines contains two integers cj and wj (1 ≀ cj, wj ≀ 109) β€” significance and width of the j-th cup for Informatics olympiads. Output Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement. If there is no way to expose cups on the shelf, then print 0. Examples Input 3 1 8 4 2 5 5 4 2 3 2 Output 8 Input 4 3 12 3 4 2 4 3 5 3 4 3 5 5 2 3 4 Output 11 Input 2 2 2 5 3 6 3 4 2 8 1 Output 0 Note In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8. Submitted Solution: ``` n, m, d = input().split() n = int(n) m = int(m) d = int(d) # c = {} # w = {} # topPhys = (0,-0) #cost, -width # topInf = (0,-0) phys = [] it = [] for i in range(0,n): c, w = input().split() c = int(c) w = int(w) phys.append([-c,w,'p']) phys = sorted(phys) for i in range(n,m+n): c, w = input().split() c = int(c) w = int(w) it.append([-c,w,'i']) it = sorted(it) curw = phys[0][1] + it[0][1] curc = - phys[0][0] - it[0][0] if (curw > d): print(0) quit() phys[0][0] = 0 it[0][0] = 0 cup = [] cup.extend(phys) cup.extend(it) cup = sorted(cup) # print("curc", curc) # print("cups", cup) phs = True its = True i = 0 while (phs and its and i < n+m): if (curw + cup[i][1] > d): if (cup[i][2] == 'i'): its = False else: phs = False else: if (its and cup[i][2] == 'i') or (phs and cup[i][2] == 'p'): curw += cup[i][1] curc -= cup[i][0] ++i print(curc) ``` No
101,687
Provide tags and a correct Python 3 solution for this coding contest problem. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Tags: data structures, implementation Correct Solution: ``` n = int(input()) p = map(int, input().split()) a = map(int, input().split()) b = map(int, input().split()) m =input() c = map(int, input().split()) t = sorted(zip(p, a, b), key=lambda x: x[0]) t = [list(x) for x in t] indxs = [None, 0, 0, 0] r = [] for ci in c: i = indxs[ci] while i < n and ci not in (t[i][1], t[i][2]): i += 1 if i == n: r.append('-1') else: r.append(str(t[i][0])) t[i][1], t[i][2] = 0, 0 i += 1 indxs[ci] = i print(*r) ```
101,688
Provide tags and a correct Python 3 solution for this coding contest problem. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Tags: data structures, implementation Correct Solution: ``` n=int(input()) p=list(map(int,input().split())) a=list(map(int,input().split())) b=list(map(int,input().split())) f=[0]*n m=int(input()) c=list(map(int,input().split())) l=[[],[],[],[]] for i in range(n): l[a[i]]+=[[p[i],i]] if b[i]!=a[i]: l[b[i]]+=[[p[i],i]] for i in range(1,4): l[i]=sorted(l[i]) i=[0,0,0,0] ans=[] for x in c: while i[x]<len(l[x]) and f[l[x][i[x]][1]]: i[x]+=1 if i[x]>=len(l[x]): ans+=[-1] else: ans+=[l[x][i[x]][0]]; f[l[x][i[x]][1]]=1 print(*ans) ```
101,689
Provide tags and a correct Python 3 solution for this coding contest problem. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Tags: data structures, implementation Correct Solution: ``` import math as mt import sys,string,bisect input=sys.stdin.readline import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) t=I() p=L() a=L() b=L() m=I() c=L() one=[] two=[] three=[] for i in range(t): if(a[i]==1 or b[i]==1): one.append((p[i],i)) if(a[i]==2 or b[i]==2): two.append((p[i],i)) if(a[i]==3 or b[i]==3): three.append((p[i],i)) if(len(one)>0): one.sort(key=lambda x:x[0]) if(len(two)>0): two.sort(key=lambda x:x[0]) if(len(three)>0): three.sort(key=lambda x:x[0]) i=0 j=0 k=0 v=[0]*t for _ in c: if(_==1): while(i<len(one) and v[one[i][1]]): i+=1 if(i<len(one)): v[one[i][1]]=1 print(one[i][0],end=" ") i+=1 else: print(-1,end=" ") elif(_==2): while(j<len(two) and v[two[j][1]]): j+=1 if(j<len(two)): v[two[j][1]]=1 print(two[j][0],end=" ") j+=1 else: print(-1,end=" ") else: while(k<len(three) and v[three[k][1]]): k+=1 if(k<len(three)): v[three[k][1]]=1 print(three[k][0],end=" ") k+=1 else: print(-1,end=" ") ```
101,690
Provide tags and a correct Python 3 solution for this coding contest problem. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Tags: data structures, implementation Correct Solution: ``` import collections def mp(): return map(int,input().split()) def lt(): return list(map(int,input().split())) def pt(x): print(x) def ip(): return input() def it(): return int(input()) def sl(x): return [t for t in x] def spl(x): return x.split() def aj(liste, item): liste.append(item) def bin(x): return "{0:b}".format(x) def listring(l): return ' '.join([str(x) for x in l]) def ptlist(l): print(' '.join([str(x) for x in l])) n = it() p = lt() a = lt() b = lt() m = it() c = lt() shirt = list(zip(p,a,b)) shirt.sort() pointer = [-1,0,0,0] l = [] for i in range(m): cl = c[i] while pointer[cl] < n and (shirt[pointer[cl]] == None or cl not in shirt[pointer[cl]][1:]): pointer[cl] += 1 if pointer[cl] == n: l.append(-1) else: l.append(shirt[pointer[cl]][0]) shirt[pointer[cl]] = None ptlist(l) ```
101,691
Provide tags and a correct Python 3 solution for this coding contest problem. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Tags: data structures, implementation Correct Solution: ``` from collections import deque class CodeforcesTask799BSolution: def __init__(self): self.result = '' self.n = 0 self.prices = [] self.front_colors = [] self.back_colors = [] self.m = 0 self.customers = [] def read_input(self): self.n = int(input()) self.prices = [int(x) for x in input().split(" ")] self.front_colors = [int(x) for x in input().split(" ")] self.back_colors = [int(x) for x in input().split(" ")] self.m = int(input()) self.customers = [int(x) for x in input().split(" ")] def process_task(self): shop = [[[] for _ in range(3)] for __ in range(3)] for t in range(self.n): shop[self.front_colors[t] - 1][self.back_colors[t] - 1].append(self.prices[t]) for x in range(3): for y in range(3): shop[x][y].sort() shop[x][y] = deque(shop[x][y]) res = [] for customer in self.customers: mn_p = 10**10 selected = None for back in range(3): if shop[customer - 1][back]: if shop[customer - 1][back][0] < mn_p: selected = (customer - 1, back) mn_p = shop[customer - 1][back][0] for front in range(3): if shop[front][customer - 1]: if shop[front][customer - 1][0] < mn_p: selected = (front, customer - 1) mn_p = shop[front][customer - 1][0] if selected: res.append(shop[selected[0]][selected[1]].popleft()) else: res.append(-1) self.result = " ".join([str(x) for x in res]) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask799BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
101,692
Provide tags and a correct Python 3 solution for this coding contest problem. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Tags: data structures, implementation Correct Solution: ``` n = int(input()) p = list(map(int,input().split())) a = list(map(int,input().split())) b = list(map(int,input().split())) P = [] for i in range(n): P.append([p[i],a[i],b[i],0]) P = sorted(P) last = [0,0,0,0] m = int(input()) c = list(map(int,input().split())) R = [] for i in c: if last[i] == -1: R.append(-1) else: for j in range(last[i],n): if P[j][3] == 0: if P[j][1] == i or P[j][2] == i: R.append(P[j][0]) P[j][3] = 1 if j+1 < n: last[i] = j+1 else: last[i] = -1 break else: R.append(-1) last[i] = -1 print(' '.join(map(str,R))) ```
101,693
Provide tags and a correct Python 3 solution for this coding contest problem. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Tags: data structures, implementation Correct Solution: ``` import sys # 1. create color to tshirt map # 2. sort tshirts by orice for each color # 3. save the current tshirt for each color ready for the next buyer # 4. simulate sale def main(in_stream=sys.stdin): max_col = 3 in_stream.readline() plist = [int(tok) for tok in in_stream.readline().split()] alist = [int(tok) for tok in in_stream.readline().split()] blist = [int(tok) for tok in in_stream.readline().split()] in_stream.readline() clist = [int(tok) for tok in in_stream.readline().split()] color_to_tshirts = {i: [] for i in range(1, max_col + 1)} color_to_avail_index = {} for triple in zip(plist, alist, blist): tshirt = list(triple + (False, )) color_to_tshirts[tshirt[1]].append(tshirt) color_to_tshirts[tshirt[2]].append(tshirt) # sort by pricest and assign cheapest for c, tlist in color_to_tshirts.items(): tlist.sort(key=lambda ts: ts[0]) color_to_avail_index[c] = 0 # simulate the sale result = [] for ci in clist: the_list = color_to_tshirts[ci] avail_index = color_to_avail_index[ci] while avail_index < len(the_list) and the_list[avail_index][-1]: avail_index += 1 color_to_avail_index[ci] = avail_index if len(the_list) == avail_index: result.append(-1) continue tsel = the_list[avail_index] tsel[-1] = True result.append(tsel[0]) return result if __name__ == '__main__': print(*main()) ```
101,694
Provide tags and a correct Python 3 solution for this coding contest problem. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Tags: data structures, implementation Correct Solution: ``` """ Code of Ayush Tiwari Codeforces: servermonk Codechef: ayush572000 """ import sys input = sys.stdin.buffer.readline def solution(): n=int(input()) p=list(map(int,input().split())) a=list(map(int,input().split())) b=list(map(int,input().split())) f=[0]*n m=int(input()) c=list(map(int,input().split())) l=[[],[],[],[]] for i in range(n): l[a[i]]+=[[p[i],i]] if b[i]!=a[i]: l[b[i]]+=[[p[i],i]] for i in range(1,4): l[i]=sorted(l[i]) i=[0,0,0,0] ans=[] for x in c: while i[x]<len(l[x]) and f[l[x][i[x]][1]]: i[x]+=1 if i[x]>=len(l[x]): ans+=[-1] else: ans+=[l[x][i[x]][0]]; f[l[x][i[x]][1]]=1 print(*ans) solution() ```
101,695
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Submitted Solution: ``` n = int(input()) p = list(map(int, input().split())) b = list(map(int, input().split())) a = list(map(int, input().split())) m = int(input()) c = list(map(int, input().split())) tp = {(i,j): [] for i in range(1,4) for j in range(i,4)} for i in range(n): k = [a[i], b[i]] k.sort() tp[tuple(k)].append(p[i]) for k,v in tp.items(): v.sort(reverse=True) ans = [] for i in range(m): mm = -1 for k,v in tp.items(): if c[i] in k: if len(v) != 0: if mm == -1 or tp[mm][-1] > v[-1]: mm = k if mm == -1: ans.append('-1') else: z = tp[mm].pop() ans.append(str(z)) print(' '.join(ans)) ``` Yes
101,696
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Mon Sep 30 07:23:34 2019 @author: avina """ n = int(input()) price = list(map(int, input().split())) fron = list(map(int, input().split())) back = list(map(int, input().split())) e = [0,0,0] group = [] for i in range(n): group.append([price[i],fron[i],back[i]]) group.sort(key = lambda x:x[0]) m = int(input()) l = list(map(int, input().split())) for i in range(m): a = l[i] j = e[a - 1] t = True while j < n: if group[j][1] == a or group[j][2] == a: print(group[j][0],end = ' ') group[j][1] = 0;group[j][2] = 0 t = False break j+=1 if t: print(-1,end=' ') e[a-1] = j+1 ``` Yes
101,697
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Submitted Solution: ``` import operator n = int(input()) p = map(int, input().split()) a = map(int, input().split()) b = map(int, input().split()) input() c = map(int, input().split()) t = sorted(zip(p, a, b), key=operator.itemgetter(0)) p = [None, 0, 0, 0] r = [] for ci in c: i = p[ci] while i < n and (t[i] is None or ci not in (t[i][1:])): i += 1 if i == n: r.append('-1') else: r.append(str(t[i][0])) t[i] = None i += 1 p[ci] = i print(' '.join(r)) ``` Yes
101,698
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. Input The first line contains single integer n (1 ≀ n ≀ 200 000) β€” the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≀ pi ≀ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≀ m ≀ 200 000) β€” the number of buyers. The following line contains sequence c1, c2, ..., cm (1 ≀ cj ≀ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. Output Print to the first line m integers β€” the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. Examples Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Submitted Solution: ``` n = int(input()) ps = [int(a) for a in input().split()] fronts = [int(a) for a in input().split()] backs = [int(a) for a in input().split()] shirts = list(zip(ps,fronts,backs)) shirts.sort() bought = [False] * n ptrs = [0] * 4 def mvptrs(): for i in range(1,len(ptrs)): while ptrs[i] < n and ((shirts[ptrs[i]][1] != i and shirts[ptrs[i]][2] != i) or bought[ptrs[i]]): ptrs[i] += 1 mvptrs() m = int(input()) colors = [int(a) for a in input().split()] def serve(i): if ptrs[colors[i]] >= n: print(-1, end='') else: print(shirts[ptrs[colors[i]]][0], end='') bought[ptrs[colors[i]]] = True mvptrs() serve(0) for i in range(1,m): print(' ', end='') serve(i) print() ``` Yes
101,699