text
stringlengths
198
433k
conversation_id
int64
0
109k
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: ``` shirt_num = int(input()) price_shirt = input().split() upper_shirt = input().split() down_shirt = input().split() shop_num = int(input()) love_color = input().split() dict_color = {} for i in range(shirt_num): dict_color[price_shirt[i]] = upper_shirt[i], down_shirt[i] price = 0 ans = "" for i in range(shop_num): for (key, value) in dict_color.items(): if love_color[i] in value and price == 0: price = key elif price != 0 and key<price: price = key if price == 0: ans+="-1 " break del dict_color[price] ans += str(price) + " " price = 0 print(ans) ``` No
101,700
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 heapq n = int(input()) color = [[] for x in range(4)] p = list(map(int,input().split())) f = list(map(int,input().split())) b = list(map(int,input().split())) cost = [0 for _ in range((10))] buy = int(input()) ans = [] buyColor = list(map(int,input().split())) done = [] heapq.heapify(done) for i in range(1,4): heapq.heapify(color[i]) for i in range(n): front = f[i] back = b[i] if front!=back: heapq.heappush(color[front],p[i]) heapq.heappush(color[back],p[i]) else: heapq.heappush(color[front],p[i]) for need in buyColor: while(1): if len(color[need])>0: pay = heapq.heappop(color[need]) if len(done)>0: l=0 h = len(done)-1 while(l!=h and done[h]!=pay): next = (l+h)//2 if done[next]<pay: l = next+1 else: h = next else: done.append(pay) h = 0 ans.append(pay) break if done[h]!= pay: ans.append(pay) done.append(pay) break else: ans.append(-1) break print(*ans) ``` No
101,701
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()) Price = list(map(int, input().split())) A = list(map(int, input().split())) B = list(map(int, input().split())) m = int(input()) Color = list(map(int, input().split())) Res = [] for i in Color: Buy = [] for a in range(len(Price)): if A[a] == i: Buy.append(a) if B[a] == i: if Buy == []: Buy.append(a) elif Buy[-1] != a: Buy.append(a) K = [] for b in Buy: K.append(Price[b]) if K ==[]: Res.append(-1) else: Res.append(min(K)) Price.remove(min(K)) print(" ".join(map(str, Res))) ``` No
101,702
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: ``` def preferences(p, a, b, c): ans = [] for i in range(len(c)): cost = -1 j_container = -1 for j in range(len(p)): if cost == -1: if (a[j] == c[i] or b[j] == c[i]) and p[j] != -1: cost = p[j] j_container = j else: if (a[j] == c[i] or b[j] == c[i]) and p[j] < cost and p[j] != -1: cost = p[j] j_container = j ans.append(cost) p[j_container] = -1 return ans if __name__ == '__main__': n = int(input()) p = [int(i) for i in input().split()] a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] m = int(input()) c = [int(i) for i in input().split()] out = preferences(p, a, b, c) print(" ".join(str(x) for x in out)) ``` No
101,703
Provide tags and a correct Python 3 solution for this coding contest problem. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Tags: data structures, implementation, math Correct Solution: ``` from sys import stdin def main(): n = int(stdin.readline()) a = list(map(int, stdin.readline().split())) inf = [0] * (n + 1) curr = 0 d = 0 for i in range(n): curr += abs(i + 1 - a[i]) if a[i] > i + 1: d += 1 inf[a[i] - i - 1] += 1 elif a[i] <= i + 1: d -= 1 if a[i] == i + 1: inf[0] += 1 else: inf[a[i] + n - i - 1] += 1 best = curr num = 0 for i in range(n): curr -= d curr -= 1 curr = curr - abs(a[n - i - 1] - n) + abs(a[n - i - 1] - 1) d += 2 d -= inf[i + 1] * 2 if curr < best: best = curr num = i + 1 print(best, num) main() ```
101,704
Provide tags and a correct Python 3 solution for this coding contest problem. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Tags: data structures, implementation, math Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) t = [0] * 2 * n s = 0 for i in range(n): d = a[i] - i - 1 s += abs(d) if d > 0: t[d] += 1 p = sum(t) r = (s, 0) for i in range(1, n): d = a[n - i] - 1 s += d - p << 1 t[d + i] += d > 0 p += (d > 0) - t[i] if s < r[0]: r = (s, i) print(*r) ```
101,705
Provide tags and a correct Python 3 solution for this coding contest problem. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Tags: data structures, implementation, math Correct Solution: ``` n = int(input()) data = input().split() #print(str(n) + " " + str(data)) data = list(map(lambda x: int(x), data)) res = 0 ires = 0 neg = 0 when = [0] * n for i in range(n): data[i] = i + 1 - data[i] res += abs(data[i]) if data[i] <= 0: neg += 1 a = -data[i] if a < 0: a = a + n when[a] += 1 #print(when) ares = res #print(str(res) + " " + str(ires) + " " + str(neg)) for i in range(n): neg -= when[i] ares -= neg ares += (n - neg) x = data[n - i - 1] + i + 1 ares -= x ares += n - x #print(str(res) + " " + str(ires) + " " + str(ares) + " " + str(i) + " " + str(neg)) neg += 1 if ares < res: res = ares ires = i + 1 print(str(res) + " " + str(ires)) ```
101,706
Provide tags and a correct Python 3 solution for this coding contest problem. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Tags: data structures, implementation, math Correct Solution: ``` def main(): n=int(input()) A=list(map(int,input().strip().split(' '))) def brutal(A): n=len(A) for i in range(n): temp=0 pos=0 neg=0 for j in range(n): temp+=abs(A[j]-(j+i)%n) if A[j]-(j+i)%n>0: pos+=1 else: neg+=1 print(temp,i,pos,neg,'ans,shift,+ve,-ve') for i in range(len(A)): A[i]-=1 ans=0 pos=0 neg=0 change=[0 for i in range(len(A))] for i in range(len(A)): ans+=abs(A[i]-i) if A[i]-i>0: pos+=1 else: neg+=1 if A[i]-i>0: change[i]=A[i]-i elif A[i]==i: change[i]=0 else: if A[i]!=0: change[i]=A[i]+n-i else: change[i]=0 MIN=ans index=0 #print(ans) collect=[[] for i in range(n)] for x in range(len(change)): collect[change[x]]+=[x] #print(collect) #print(ans,pos,neg) for s in range(1,n): ans-=abs(A[n-s]-n+1) ans+=abs(A[n-s]-0) neg-=1 ans-=pos ans+=neg if A[n-s]>0: pos+=1 else: neg+=1 pos-=len(collect[s]) neg+=len(collect[s]) #print(ans,pos,neg) if ans<MIN: MIN=ans index=s print(MIN,index) #brutal(A) main() ```
101,707
Provide tags and a correct Python 3 solution for this coding contest problem. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Tags: data structures, implementation, math Correct Solution: ``` n = int(input()) p = [int(i) - 1 for i in input().split()] chd = [0] * (n + 2) dev = 0 dd = 0 for i in range(n): shi = p[i] - i dev += abs(shi) if p[i] <= i: dd += 1 shi = n + shi chd[shi] += 2 else: dd -= 1 chd[shi] += 2 bdev = dev bsh = 0 for i in range(1, n): dev -= abs(p[-i] - (n - 1)) dev += abs(p[-i] - 0) dd -= 1 dev += dd dd -= 1 dd += chd[i] if dev < bdev: bsh = i bdev = dev print(bdev, bsh) ```
101,708
Provide tags and a correct Python 3 solution for this coding contest problem. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Tags: data structures, implementation, math Correct Solution: ``` def main(): n = int(input()) data = input().split() #print(str(n) + " " + str(data)) data = list(map(lambda x: int(x), data)) res = 0 ires = 0 neg = 0 when = [0] * n for i in range(n): data[i] = i + 1 - data[i] res += abs(data[i]) if data[i] <= 0: neg += 1 a = -data[i] if a < 0: a = a + n when[a] += 1 #print(when) ares = res #print(str(res) + " " + str(ires) + " " + str(neg)) for i in range(n): neg -= when[i] ares -= neg ares += (n - neg) x = data[n - i - 1] + i + 1 ares -= x ares += n - x #print(str(res) + " " + str(ires) + " " + str(ares) + " " + str(i) + " " + str(neg)) neg += 1 if ares < res: res = ares ires = i + 1 print(str(res) + " " + str(ires)) main() ```
101,709
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Submitted Solution: ``` I = lambda : map(int, input().split()) n, = I() if n == 975587: print(316925125798, 610904) exit(0) P = [0] + list(I()) A = [0] for i in range(1,n+1): A.append(A[i-1] + P[i]) mn = -99999999999999999999999 ans = 0 for i in range(0,n): if i*A[n-i] - (n-i)*(A[n] - A[n-i]) > mn: mn = i*A[n-i] - (n-i)*(A[n] - A[n-i]) ans = i dev = 0 for i in range(1,n+1): indx = i+ans if indx > n: indx -= n dev += abs(indx - P[i]) print(dev, ans) ``` No
101,710
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Submitted Solution: ``` I = lambda : map(int, input().split()) n, = I() P = [0] + list(I()) A = [0] for i in range(1,n+1): A.append(A[i-1] + P[i]) mn = -99999999999999999999999 ans = 0 for i in range(0,n): if i*A[n-i] - (n-i)*(A[n] - A[n-i]) > mn: mn = i*A[n-i] - (n-i)*(A[n] - A[n-i]) ans = i dev = 0 for i in range(1,n+1): indx = i+ans if indx > n: indx -= n dev += abs(indx - P[i]) print(dev, ans) ``` No
101,711
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Submitted Solution: ``` length = int(input()) string = input() numbers = string.split(" ") for x in range(length): numbers[x] = int(numbers[x]) values = [] for x in range(length): a = 0 for y in range(length): z = (y + x) % length a += abs(numbers[z] - (y + 1)) if x == 0: minimum = a b = x elif a < minimum: minimum = a b = x print("%d %d" % (minimum, b)) ``` No
101,712
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation p as <image>. Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: * k = 0: shift p1, p2, ... pn, * k = 1: shift pn, p1, ... pn - 1, * ..., * k = n - 1: shift p2, p3, ... pn, p1. Input First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them. Examples Input 3 1 2 3 Output 0 0 Input 3 2 3 1 Output 0 1 Input 3 3 2 1 Output 2 1 Note In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. Submitted Solution: ``` #!/usr/bin/env python def diff(nums): sum_ = 0 for i in range(0, len(nums)): sum_ += abs(nums[i] - i - 1) return sum_ n = int(input()) numbers = [int(x) for x in input().split()] min_p = diff(numbers) if min_p == 0: print("0 0") quit() min_n = 0 for i in range(1, n - 1): numbers_shifted = numbers[-i:] + numbers[:-i] d = diff(numbers_shifted) if d < min_p: min_p = d min_n = i print(str(min_p) + " " + str(min_n)) ``` No
101,713
Provide tags and a correct Python 3 solution for this coding contest problem. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Tags: binary search, sortings, ternary search Correct Solution: ``` def bins(sortedlist,x): n=len(sortedlist) start = 0 end = n - 1 while(start <= end): mid =int( (start + end)/2) if (x == sortedlist[mid][0]): return mid elif(x < sortedlist[mid][0]): end = mid - 1 else: start = mid + 1 if(sortedlist[mid][0]<=x): return mid else: return mid-1 n,s=map(int,input().split()) hap=[] for i in range(n): hap.append(list(map(int,input().split()))) a=0 max1=0 b=0 sla=[] slb=[] slab=[] for i in range(n): temp=hap[i][0] hap[i][0]=hap[i][1] hap[i][1]=hap[i][2] hap[i][2]=temp for i in range(n): slab.append([hap[i][0]-hap[i][1],hap[i][2]]) happi=0 for i in range(n): if(hap[i][0]>hap[i][1]): a+=hap[i][2] happi+=hap[i][2]*hap[i][0] else: b+=hap[i][2] happi+=hap[i][2]*hap[i][1] sla.sort() slb.sort() slab.sort() if((a%s + b%s)>s): print(happi) else: loc=bins(slab,0) happia=happi count=0 #print(a,b) b=b%s a=a%s left=b%s while(left>0): if(slab[loc+count][1]<left): happia+=slab[loc+count][0]*slab[loc+count][1] left-=slab[loc+count][1] else: happia+=slab[loc+count][0]*left break count-=1 left=a%s count=0 happib=happi while(loc<n and slab[loc][0]<=0): loc+=1 #print(slab[loc][0]) while(left>0): if(slab[loc+count][1]<left): happib-=slab[loc+count][0]*slab[loc+count][1] left-=slab[loc+count][1] else: happib-=slab[loc+count][0]*left break count+=1 #print(happia,happib,happi) print(max(happia,happib)) ```
101,714
Provide tags and a correct Python 3 solution for this coding contest problem. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Tags: binary search, sortings, ternary search Correct Solution: ``` n, S = map(int, input().split()) arr = [] suma = 0 happy = 0 sumb = 0 dif = [] for i in range(n): c, a, b = map(int, input().split()) if a >= b: suma += c happy += a * c else: sumb += c happy += b * c dif.append((a - b, c)) dif.sort() num = (suma + sumb - 1) // S + 1 if (suma - 1) // S + 1 + (sumb - 1) // S + 1 <= num: print(happy) else: moda = suma % S modb = sumb % S #a->b for i in range(n): if dif[i][0] >= 0: ind = i break ans1 = happy ans2 = happy first = min(S - modb, moda) if first <= moda: now = ind ans1 = 0 while first > 0: if dif[now][1] > first: ans1 += dif[now][0] * first first = 0 else: ans1 += dif[now][0] * dif[now][1] first -= dif[now][1] now += 1 #b->a second = min(S - moda, modb) if second <= modb: now = ind - 1 ans2 = 0 while second > 0: if dif[now][1] > second: ans2 -= dif[now][0] * second second = 0 else: ans2 -= dif[now][0] * dif[now][1] second -= dif[now][1] now -= 1 print(happy - min(ans1, ans2)) ```
101,715
Provide tags and a correct Python 3 solution for this coding contest problem. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Tags: binary search, sortings, ternary search Correct Solution: ``` def solve(ls): ls.sort(key=lambda q: q[1] - q[0]) m = sum(si for a, b, si in ls) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si * a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return x, y, z, n n,s = map(int,input().split()) first=[] second=[] for i in range(n): si, ai, bi = map(int,input().split()) if ai>bi: first.append((ai,bi,si)) else: second.append((bi,ai,si)) x1,y1,z1,n1 = solve(first) x2,y2,z2,n2 = solve(second) d = x1+x2 if n1+n2>s else max(x1+y2,x2+y1) print(z1+z2+d) ```
101,716
Provide tags and a correct Python 3 solution for this coding contest problem. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Tags: binary search, sortings, ternary search Correct Solution: ``` # -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random """ created by shhuan at 2017/10/3 12:35 """ N, S = map(int, input().split()) M = [] for i in range(N): M.append([int(x) for x in input().split()]) # # N, S = 100000, 100000 # M = [[random.randint(10000, 100000), random.randint(1, 100), random.randint(1, 100)] for _ in range(N)] # t0 = time.time() s = [M[i][0] for i in range(N)] a = [M[i][1] for i in range(N)] b = [M[i][2] for i in range(N)] total = sum(s) numpizza = int(math.ceil(total/S)) numslice = numpizza * S sab = sorted([(a[i]-b[i], i) for i in range(N)], reverse=True) pa = 0 pb = 0 pab = 0 maxHappiness = 0 for i in range(N): if a[i] > b[i]: pa += s[i] elif a[i] < b[i]: pb += s[i] else: pab += s[i] sa = int(math.ceil(pa/S)) * S sb = int(math.ceil(pb/S)) * S pab -= sa+sb-pa-pb pab = max(pab, 0) if sa//S + sb//S + int(math.ceil(pab/S)) == numpizza: print(sum([s[i]*(a[i] if a[i] > b[i] else b[i]) for i in range(N)])) exit(0) if pa == 0 and pb == 0: print(sum([s[i]*a[i] for i in range(N)] or [0])) exit(0) if pa == 0: print(sum([s[i]*b[i] for i in range(N)] or [0])) exit(0) if pb == 0: print(sum([s[i]*a[i] for i in range(N)] or [0])) exit(0) # print(time.time()-t0) sbak = s for pza in range(pa//S, (pa+pab)//S+2): pzb = numpizza - pza aslice = pza*S bslice = pzb*S h = 0 s = [x for x in sbak] for j in range(N): d, i = sab[j] if d > 0: if aslice >= s[i]: h += s[i]*a[i] aslice -= s[i] s[i] = 0 elif aslice > 0: h += a[i]*aslice s[i] -= aslice aslice = 0 else: break for j in range(N-1, -1, -1): d, i = sab[j] if d < 0: if bslice >= s[i]: h += s[i]*b[i] bslice -= s[i] s[i] = 0 elif bslice > 0: h += bslice * b[i] s[i] -= bslice bslice = 0 else: break if aslice == 0: for i in range(N): if s[i] != 0: h += s[i]*b[i] bslice -= s[i] elif bslice == 0: for i in range(N): if s[i] != 0: h += s[i]*a[i] aslice -= s[i] else: remain = [(s[i], a[i], b[i]) for i in range(N) if s[i] > 0 and a[i] != b[i]] for u,v,w in remain: if v > w: if aslice > 0: if aslice > u: h += u * v aslice -= u else: h += aslice * v h += (u-aslice) * w bslice -= u-aslice aslice = 0 else: h += u*w bslice -= u else: if bslice > 0: if bslice > u: h += u * w bslice -= u else: h += bslice * w h += (u - bslice) * v aslice -= u - bslice bslice = 0 else: h += u*v aslice -= u h += sum([s[i]*a[i] for i in range(N) if a[i] == b[i]] or [0]) maxHappiness = max(maxHappiness, h) print(maxHappiness) # print(time.time() - t0 ) ```
101,717
Provide tags and a correct Python 3 solution for this coding contest problem. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Tags: binary search, sortings, ternary search Correct Solution: ``` n, S = 0, 0 s = [] a = [] b = [] class node: def __init__(self, x, id): self.x = x self.id = id return def __lt__(self, p): return self.x < p.x c = [] i , f = 0, 0 ans, sum, a1, a2 = 0, 0, 0, 0 s1, s2 = 0, 0 line = input().split() n, S = int(line[0]), int(line[1]) for i in range(n): line = input().split() s.append(int(line[0])) a.append(int(line[1])) b.append(int(line[2])) if a[i] > b[i]: s1 += s[i] elif a[i] < b[i]: s2 += s[i] sum += s[i] ans += max(a[i], b[i]) * s[i] c.append(node(a[i] - b[i], i)) cnt = (sum + S - 1) // S if (s1 + S - 1) // S + (s2 + S - 1) // S <= cnt: print(ans) else: c.sort() s1 %= S s2 %= S for i in range(n): if c[i].x <= 0: f = i continue if not s1: break t = min(s[c[i].id], s1) a1 += t * c[i].x s1 -= t for i in range(f, -1, -1): if not c[i].x: continue if not s2: break t = min(s[c[i].id], s2) a2 -= t * c[i].x s2 -= t print(ans - min(a1, a2)) ```
101,718
Provide tags and a correct Python 3 solution for this coding contest problem. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Tags: binary search, sortings, ternary search Correct Solution: ``` def get_losts(persons, count): persons.sort(key = lambda p : p.lost) losts = 0 i = 0 while count > 0: df = min(count, persons[i].s) losts += df * persons[i].lost count -= df i += 1 return losts class Person: def __init__(self, _s, _a, _b, _lost): self.s = _s self.a = _a self.b = _b self.lost = _lost n, m = map(int, input().split()) s_count = 0 a_pizza = list() a_count = 0 a_points = 0 b_pizza = list() b_count = 0 b_points = 0 neutral_points = 0 neutral_count = 0 for i in range(n): s, a, b = map(int, input().split()) s_count += s if a == b: neutral_points += s*a s_count -= s neutral_count += s elif a > b: a_pizza.append(Person(s, a, b, a - b)) a_count += s a_points += s*a else: b_pizza.append(Person(s, a, b, b - a)) b_count += s b_points += s*b a_lost = a_count % m b_lost = b_count % m if a_lost + b_lost + neutral_count > m or a_lost == 0 or b_lost == 0: print(neutral_points + a_points + b_points) else: a_lost = get_losts(a_pizza, a_lost) b_lost = get_losts(b_pizza, b_lost) print(neutral_points + a_points + b_points - min(a_lost, b_lost)) ```
101,719
Provide tags and a correct Python 3 solution for this coding contest problem. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Tags: binary search, sortings, ternary search Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys #import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) 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") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=300006, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b:a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.height=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val==0: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right elif val>=1: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left def do(self,temp): if not temp: return 0 ter=temp temp.height=self.do(ter.left)+self.do(ter.right) if temp.height==0: temp.height+=1 return temp.height def query(self, xor): self.temp = self.root cur=0 i=31 while(i>-1): val = xor & (1 << i) if not self.temp: return cur if val>=1: self.opp = self.temp.right if self.temp.left: self.temp = self.temp.left else: return cur else: self.opp=self.temp.left if self.temp.right: self.temp = self.temp.right else: return cur if self.temp.height==pow(2,i): cur+=1<<(i) self.temp=self.opp i-=1 return cur #-------------------------bin trie------------------------------------------- n,s=map(int,input().split()) w=[] w1=[] sw=0 sw1=0 ans=0 qw=0 qw1=0 for i in range(n): a,b,c=map(int,input().split()) if b<c: w.append((c-b,a)) sw+=a qw+=a*(c-b) else: w1.append((b-c,a)) sw1+=a qw1+=a*(b-c) ans+=a*max(c,b) w.sort() w1.sort() tr=(sw//s)*s tr1=(sw1//s)*s for i in range(len(w)-1,-1,-1): b,a=w[i] if tr>=a: sw-=a qw-=a*b tr-=a else: sw-=tr qw-=tr*b tr=0 break for i in range(len(w1)-1,-1,-1): b,a=w1[i] if tr1>=a: sw1-=a qw1-=a*b tr1-=a else: sw1-=tr1 qw1-=tr1*b tr1=0 break if (sw+sw1)>s: print(ans) else: print(ans-min(qw,qw1)) ```
101,720
Provide tags and a correct Python 3 solution for this coding contest problem. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Tags: binary search, sortings, ternary search Correct Solution: ``` from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = map(int, counts_str) return [input() for _ in range(members_count)], parts def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*map(int, line.split())) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return a_members, b_members, other_members def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum(m.parts for m in a_members) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum(m.a_happy * m.parts for m in a_happy_members) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum(m.parts for m in b_members) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum(m.b_happy * m.parts for m in b_happy_members) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if (i + 1) < len(members): happy_members.extend(members[(i + 1):]) break return modulo_members, happy_members def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b if sum(m.parts for m in last_sorted_members) <= parts_in_one: return max( sum(m.a_happy * m.parts for m in last_sorted_members), sum(m.b_happy * m.parts for m in last_sorted_members) ) return sum(m.a_happy * m.parts for m in a + other) + sum(m.b_happy * m.parts for m in b) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members( [ '2 1 4', '2 3 1', ] ) assert count_parts(a, b, c, 3) == 14 def test5(): a, b, c = prepare_members( [ '2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1', ] ) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members( [ '2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1', ] ) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members( [ '3 3 1', '3 5 6' ] ) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members( [ '2 3 1', '1 5 6' ] ) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members( [ '2 3 4', '2 3 1', '1 1 1' ] ) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members( [ '2 2 2', '4 1 1', '5 6 6' ] ) assert count_parts(a, b, c, 3) == 38 if __name__ == "__main__": main() ```
101,721
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Submitted Solution: ``` from sys import stdin from collections import deque n,S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s,a,b = [int(x) for x in stdin.readline().split()] base += s*a tSlices += s ppl.append([b-a,s]) #print(base) if tSlices % S != 0: ppl.append([0, S-(tSlices%S)]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h,s in ppl: if totalS + s < S: totalS += s totalH += h*s else: s -= S-totalS totalH += h*(S-totalS) if totalH > 0: base += totalH else: break totalS = 0 totalH = 0 if h > 0: base += h*((s//S)*S) totalS = s%S totalH = h*(s%S) else: break print(base) ``` Yes
101,722
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Submitted Solution: ``` from math import ceil N, S = input().split() N, S = int(N), int(S) C = 0 pC = 0 nC = 0 cArr = [] for i in range(N): s, a, b = input().split() s, a, b = int(s), int(a), int(b) C += s * b cArr.append((a - b, s)) if a > b: pC += s else: nC += s cArr.sort(key=lambda k: -k[0]) tP = int(ceil((nC + pC) / S)) nP = int(pC / S) hAns = C sItr = nP * S itr = 0 while sItr > 0 and itr < N: si = min(cArr[itr][1], sItr) hAns += si * cArr[itr][0] sItr -= si itr += 1 hAns2 = C nP = int(pC / S) + 1 sItr = nP * S e = S*(tP - nP) - nC itr = 0 while itr < N and cArr[itr][0] > 0: si = min(cArr[itr][1], sItr) hAns2 += si * cArr[itr][0] sItr -= si itr += 1 if e < 0: sItr = -e while sItr > 0 and itr < N: si = min(cArr[itr][1], sItr) hAns2 += si * cArr[itr][0] sItr -= si itr += 1 print(max(hAns, hAns2)) ``` Yes
101,723
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Submitted Solution: ``` def solve(arr): arr.sort(key=lambda q: q[1] - q[0]) m = sum(si for a, b, si in arr) k = s * (m // s) n = m - k x, y, z = 0, 0, 0 for a, b, si in arr: if k >= si: k -= si z += si * a elif k > 0: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return x, y, z, n n, s = map(int, input().split()) arr1, arr2 = [], [] for i in range(n): si, ai, bi = map(int, input().split()) if ai > bi: arr1.append((ai, bi, si)) else: arr2.append((bi, ai, si)) x1, y1, z1, n1 = solve(arr1) x2, y2, z2, n2 = solve(arr2) d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1) print(z1 + z2 + d) ``` Yes
101,724
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Submitted Solution: ``` def solve(ls): ls.sort(key=lambda q: q[1] - q[0]) m = sum(si for a, b, si in ls) k = s * (m // s) n = m - k x = y = z = 0 for a, b, si in ls: if k >= si: k -= si z += si * a elif k: z += k * a x = (si - k) * a y = (si - k) * b k = 0 else: x += si * a y += si * b return x, y, z, n n,s = map(int,input().split()) first=[] second=[] for i in range(n): si, ai, bi = map(int,input().split()) if ai>bi: first.append((ai,bi,si)) else: second.append((bi,ai,si)) x1,y1,z1,n1 = solve(first) x2,y2,z2,n2 = solve(second) d = x1+x2 if n1+n2>s else max(x1+y2,x2+y1) print(z1+z2+d) # Made By Mostafa_Khaled ``` Yes
101,725
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Submitted Solution: ``` def get_losts(persons, count): persons.sort(key = lambda p : p.lost) losts = 0 i = 0 while count > 0: df = min(count, persons[i].s) losts += df * persons[i].lost count -= df i += 1 return losts class Person: def __init__(self, _s, _a, _b, _lost): self.s = _s self.a = _a self.b = _b self.lost = _lost #f = open('input.txt', 'r') n, m = map(int, input().split()) s_count = 0 a_pizza = list() a_count = 0 a_points = 0 b_pizza = list() b_count = 0 b_points = 0 neutral_points = 0 for i in range(n): s, a, b = map(int, input().split()) s_count += s if a == b: neutral_points += s*a s_count -= s elif a > b: a_pizza.append(Person(s, a, b, a - b)) a_count += s a_points += s*a else: b_pizza.append(Person(s, a, b, b - a)) b_count += s b_points += s*b a_lost = a_count % m b_lost = b_count % m if a_lost + b_lost > m or a_lost == 0 or b_lost == 0: print(neutral_points + a_points + b_points) else: a_lost = get_losts(a_pizza, a_lost) b_lost = get_losts(b_pizza, b_lost) print(neutral_points + a_points + b_points - min(a_lost, b_lost)) ``` No
101,726
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Submitted Solution: ``` import math from collections import namedtuple Student = namedtuple('Student', ['p', 'a', 'b', 'd']) def decide_on_remains(a_left, zero_left, b_left, spp): a_happ_GIV_a = sum(s.a * s.p for s in a_left) zero_happ_GIV_x = sum(s.a * s.p for s in zero_left) b_happ_GIV_b = sum(s.b * s.p for s in b_left) a_need = sum(s.p for s in a_left) zero_need = sum(s.p for s in zero_left) b_need = sum(s.p for s in b_left) if (a_need + zero_need + b_need > spp): return a_happ_GIV_a + zero_happ_GIV_x + b_happ_GIV_b else: a_happ_GIV_b = sum(s.b * s.p for s in a_left) b_happ_GIV_a = sum(s.a * s.p for s in b_left) return max(a_happ_GIV_a + zero_happ_GIV_x + b_happ_GIV_a, a_happ_GIV_b + zero_happ_GIV_x + b_happ_GIV_b) def one_side(slices_per_pizza, students, get_value): total_happ = 0 happ = 0 slices = slices_per_pizza index = 0 leftover = None for i, s in enumerate(students): h = get_value(s) p = s.p happ += p * h slices -= p if slices <= 0: total_happ += happ + slices * h happ = -slices * h slices = slices_per_pizza + slices index = i leftover = slices_per_pizza - slices if leftover is None: remain = students elif slices == slices_per_pizza: remain = [] else: remain = students[index:] s = remain[0] remain[0] = Student(leftover, s.a, s.b, s.d) return total_happ, remain def max_happiness(slices_per_pizza, students): a_students = [s for s in students if s.d > 0] a_students.sort(key=lambda s: -s.d) zero_left = [s for s in students if s.d == 0] b_students = [s for s in students if s.d < 0] b_students.sort(key=lambda s: s.d) a_happ, a_left = one_side(slices_per_pizza, a_students, lambda s: s.a) b_happ, b_left = one_side(slices_per_pizza, b_students, lambda s: s.b) total_happ = a_happ + b_happ + decide_on_remains(a_left, zero_left, b_left, slices_per_pizza) return total_happ if __name__ == "__main__": s, slices = map(int, input().split()) students = [] for _ in range(s): p, a, b = map(int, input().split()) students.append(Student(p, a, b, a - b)) print(max_happiness(slices, students)) ``` No
101,727
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Submitted Solution: ``` from collections import namedtuple Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy']) def happy_diff(m): return m.a_happy - m.b_happy def main(): input_strings_members, parts = read_input() a_members, b_members, other_members = prepare_members(input_strings_members) print(count_parts(a_members, b_members, other_members, parts)) def read_input(): counts_str = input().split() members_count, parts = map(int, counts_str) return [input() for _ in range(members_count)], parts def prepare_members(input_strings_members): a_members = [] b_members = [] other_members = [] for line in input_strings_members: m = Member(*map(int, line.split())) if happy_diff(m) > 0: a_members.append(m) elif happy_diff(m) < 0: b_members.append(m) else: other_members.append(m) return a_members, b_members, other_members def count_parts(a_members, b_members, other_members, parts_in_one): a_members.sort(key=lambda m: happy_diff(m), reverse=False) a_modulo = sum(m.parts for m in a_members) % parts_in_one a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo) a_happy = sum(m.a_happy * m.parts for m in a_happy_members) b_members.sort(key=lambda m: happy_diff(m), reverse=True) b_modulo = sum(m.parts for m in b_members) % parts_in_one b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo) b_happy = sum(m.b_happy * m.parts for m in b_happy_members) last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one) return a_happy + b_happy + last_happy def split_members_into_happy_groups(members, modulo): modulo_members = [] happy_members = [] current_modulo = 0 for i in range(len(members)): m = members[i] new_current_modulo = current_modulo + m.parts if new_current_modulo < modulo: modulo_members.append(m) current_modulo = new_current_modulo continue modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy)) if new_current_modulo > modulo: happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy)) if (i + 1) < len(members): happy_members.extend(members[(i + 1):]) break return modulo_members, happy_members def count_last_pizzas_happy(a, b, other, parts_in_one): last_sorted_members = a + other + b current_parts = 0 possible_a_members_happy = 0 other_b_members_happy = 0 for i in range(len(last_sorted_members)): m = last_sorted_members[i] new_current_parts = current_parts + m.parts if new_current_parts < parts_in_one: possible_a_members_happy += m.parts * m.a_happy current_parts = new_current_parts continue possible_a_members_happy += (parts_in_one - current_parts) * m.a_happy if new_current_parts > parts_in_one: other_b_members_happy += (new_current_parts - parts_in_one) * m.b_happy if (i + i) < len(last_sorted_members): other_b_members_happy += sum(m.parts * m.b_happy for m in last_sorted_members[(i + 1):]) break current_parts = 0 possible_b_members_happy = 0 other_a_members_happy = 0 for i in reversed(range(len(last_sorted_members))): m = last_sorted_members[i] new_current_parts = current_parts + m.parts if new_current_parts < parts_in_one: possible_b_members_happy += m.parts * m.b_happy current_parts = new_current_parts continue possible_b_members_happy += (parts_in_one - current_parts) * m.b_happy if new_current_parts > parts_in_one: other_a_members_happy = (new_current_parts - parts_in_one) * m.a_happy if i + i < len(last_sorted_members): other_a_members_happy += sum(m.parts * m.a_happy for m in last_sorted_members[:i]) break return max(possible_a_members_happy + other_b_members_happy, possible_b_members_happy + other_a_members_happy) def test1(): a, b, c = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6']) assert count_parts(a, b, c, 10) == 314 def test2(): a, b, c = prepare_members(['3 5 7', '4 6 7', '5 9 5']) assert count_parts(a, b, c, 12) == 84 def test3(): a, b, c = prepare_members(['2 3 1', '2 2 2', '2 1 3']) assert count_parts(a, b, c, 3) == 16 def test4(): a, b, c = prepare_members( [ '2 1 4', '2 3 1', ] ) assert count_parts(a, b, c, 3) == 12 def test5(): a, b, c = prepare_members( [ '2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1', ] ) assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2 def test6(): a, b, c = prepare_members( [ '2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1', ] ) assert count_parts(a, b, c, 5) == 16 + 16 + 3 def test_without_last_pizzas(): a, b, c = prepare_members( [ '3 3 1', '3 5 6' ] ) assert count_parts(a, b, c, 3) == 27 def test_with_one_last_pizza(): a, b, c = prepare_members( [ '2 3 1', '1 5 6' ] ) assert count_parts(a, b, c, 3) == 11 def test_with_two_last_pizzas(): a, b, c = prepare_members( [ '2 3 4', '2 3 1', '1 1 1' ] ) assert count_parts(a, b, c, 3) == 15 def test_without_different_happies(): a, b, c = prepare_members( [ '2 2 2', '4 1 1', '5 6 6' ] ) assert count_parts(a, b, c, 3) == 38 if __name__ == "__main__": main() ``` No
101,728
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? Input The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively. Output Print the maximum total happiness that can be achieved. Examples Input 3 12 3 5 7 4 6 7 5 9 5 Output 84 Input 6 10 7 4 7 5 8 8 12 5 8 6 11 6 3 3 7 5 9 6 Output 314 Note In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74. Submitted Solution: ``` from sys import stdin from collections import deque n,S = [int(x) for x in stdin.readline().split()] ppl = [] base = 0 tSlices = 0 for dude in range(n): s,a,b = [int(x) for x in stdin.readline().split()] base += s*a tSlices += s ppl.append([b-a,s]) #print(base) if tSlices % S != 0: ppl.append([0, S-(tSlices%S)]) ppl.sort(reverse=True) totalS = 0 totalH = 0 for h,s in ppl: if totalS + s < S: totalS += s totalH += h*s else: s -= S-totalS totalH += h*(S-totalS) if totalH > 0: base += totalH else: break totalS = 0 totalH = 0 if h > 0: base += h*(s//S) totalS = s%S totalH = h*(s%S) else: break print(base) ``` No
101,729
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) data = list(map(int, input().split())) sorted_data = sorted(data) ans = {} for i in range(0, n): ans[sorted_data[i]] = sorted_data[(i + 1) % n] for v in data: print(ans[v], end=' ') ```
101,730
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) a = list(map(int,input().split())) arr=sorted(a,reverse=True) ans=[None for x in range(n)] for i in range(n-1): pos=a.index(arr[i]) ans[pos]=arr[i+1] for i in range(n): if ans[i]==None: ans[i]=arr[0] print(*ans) ```
101,731
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Tags: constructive algorithms, greedy Correct Solution: ``` def solve(): n=int(input()) a=list(map(int,input().split())) b=sorted(a)+[min(a)] for i in range(n): a[i]=str(b[b.index(a[i])+1]) print(' '.join(a)) return solve() ```
101,732
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Tags: constructive algorithms, greedy Correct Solution: ``` n=int(input()) a=list(map(int,input().split())) b=a.copy() a.sort() c=[] for i in range(n): c.append(a[(a.index(b[i])+1)%n]) print(*c) ```
101,733
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Tags: constructive algorithms, greedy Correct Solution: ``` n=int(input()) a=list(map(int,input().split())) b = sorted(a) + [min(a)] for i in range(n):print(b[b.index(a[i])+1],end=' ') ```
101,734
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Tags: constructive algorithms, greedy Correct Solution: ``` import sys, math readline = sys.stdin.readline n = int(readline()) inf = pow(10,10) tmp = list(map(int,readline().split())) tmp2 = [inf] * n mai = 0 for i in range(n): for j in range(n): if tmp[i] < tmp[j]: tmp2[i] = min(tmp2[i],tmp[j]) for i in range(n): if tmp[i] == max(tmp): mai = i break tmp2[mai] = min(tmp) for x in tmp2: print(x,end=' ') ```
101,735
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) a = [int(i) for i in input().split()] b = sorted(a) s = {} for i in range(-1, n-1): s[b[i+1]] = b[i] print(' '.join([str(s[i]) for i in a])) ```
101,736
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) a = list(map(int , input().split())) ans = list() for i in range(n): ans.append(0) position = dict() for i in range(n): position[a[i]] = i; a = sorted(a) ans[position[a[n - 1]]] = a[0]; for i in range(n - 1): ans[position[a[i]]] = a[i + 1] for i in range(n): print(ans[i] , end = " ") ```
101,737
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Submitted Solution: ``` n = int(input()) A = list(map(int, input().split())) C = [] for i, a in enumerate(A): C.append((a, i)) C.sort() B = [-1]*n for i in range(n-1): B[C[i+1][1]] = C[i][0] B[C[0][1]] = C[-1][0] print(*B) ``` Yes
101,738
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Submitted Solution: ``` input() t, s = zip(*sorted((int(q), i) for i, q in enumerate(input().split()))) for i, q in sorted((i, q) for q, i in zip(t[1:] + t[:1], s)): print(q) ``` Yes
101,739
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Submitted Solution: ``` #!/usr/bin/env python3 n = int(input()) A = list(map(int,input().split())) S = sorted(A) #sorted((A[i],i) for i in range(n)) P = {S[i]:S[(i+1)%n] for i in range(n)} B = [P[a] for a in A] print(' '.join(map(str,B))) ``` Yes
101,740
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Submitted Solution: ``` # -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random import itertools import sys """ created by shhuan at 2017/11/17 22:54 """ N = int(input()) A = [int(x) for x in input().split()] wc = collections.Counter(A) if any(v > 1 for v in wc.values()): print(-1) exit(0) C = list(sorted(A)) NC = {C[i]: C[i+1] for i in range(N-1)} NC[C[-1]] = C[0] ans = [] for v in A: ans.append(NC[v]) print(" ".join(map(str, ans))) ``` Yes
101,741
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Submitted Solution: ``` def chec(): global m, a s = 0 for i in range(len(m)): m[i] = s + m[i] s += m[i] l = 0 r = len(m) - 1 while True: if abs(m[r] - m[l]) == abs(a[r] - a[l]): return False l += 1 if l == r: r -= 1 l = 0 if l == r: return True n = int(input()) m = list(map(int, input().split())) a = [0] * len(m) ans = [0] * len(m) s = 0 for i in range(n): a[i] = s + m[i] s += a[i] for i in range(n - 1): m[i], m[i + 1] = m[i + 1], m[i] for i in range(n): ans[i] = m[i] #if chec(): print(*ans) #else: # print(-1) ``` No
101,742
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Submitted Solution: ``` # http://codeforces.com/problemset/problem/892/D n = int(input()) a = input().split() if n == 1: print(-1) else: b = a[1:]+[a[0]] print(' '.join(b)) ``` No
101,743
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Submitted Solution: ``` n = int(input()) if n == 1: print(-1) exit() data = list(map(int, input().split())) sorted_data = sorted(data) ans = {} for i in range(0, n): ans[sorted_data[i]] = sorted_data[(i + 1) % n] for v in data: print(ans[v], end=' ') ``` No
101,744
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. <image> Input The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array. Output If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a. If there are multiple answers, print any of them. Examples Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 Note An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Submitted Solution: ``` n = int(input()) A = [int(a) for a in input().split(' ')] S = set(A) B = [] def diff(x, y): return abs(x-y) * abs(A.index(x)-A.index(y)) def check(): for i in range(n): for j in range(i, n): if not (i == 0 and j == n-1) and sum(A[i:j+1]) == sum(B[i:j+1]): return False return True for i in range(n): s = max(S, key=lambda s: diff(A[i],s)) B.append(s) S.remove(s) #if check(): print(' '.join([str(b) for b in B])) #else: # print(-1) ``` No
101,745
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Tags: bitmasks, dp, shortest paths Correct Solution: ``` table = "!x&x x&y&z !z&x&y x&y !y&x&z x&z !y&x&z|!z&x&y (y|z)&x !y&!z&x !y&!z&x|x&y&z !z&x !z&x|x&y !y&x !y&x|x&z !(y&z)&x x !x&y&z y&z !x&y&z|!z&x&y (x|z)&y !x&y&z|!y&x&z (x|y)&z !x&y&z|!y&x&z|!z&x&y (x|y)&z|x&y !x&y&z|!y&!z&x !y&!z&x|y&z !x&y&z|!z&x !z&x|y&z !x&y&z|!y&x !y&x|y&z !(y&z)&x|!x&y&z x|y&z !x&!z&y !x&!z&y|x&y&z !z&y !z&y|x&y !x&!z&y|!y&x&z !x&!z&y|x&z !y&x&z|!z&y !z&y|x&z !(!x&!y|x&y|z) !(!x&!y|x&y|z)|x&y&z !z&(x|y) !z&(x|y)|x&y !x&!z&y|!y&x !x&!z&y|!y&x|x&z !y&x|!z&y !z&y|x !x&y !x&y|y&z !(x&z)&y y !x&y|!y&x&z !x&y|x&z !(x&z)&y|!y&x&z x&z|y !x&y|!y&!z&x !x&y|!y&!z&x|y&z !x&y|!z&x !z&x|y !x&y|!y&x !x&y|!y&x|x&z !(x&z)&y|!y&x x|y !x&!y&z !x&!y&z|x&y&z !x&!y&z|!z&x&y !x&!y&z|x&y !y&z !y&z|x&z !y&z|!z&x&y !y&z|x&y !(!x&!z|x&z|y) !(!x&!z|x&z|y)|x&y&z !x&!y&z|!z&x !x&!y&z|!z&x|x&y !y&(x|z) !y&(x|z)|x&z !y&z|!z&x !y&z|x !x&z !x&z|y&z !x&z|!z&x&y !x&z|x&y !(x&y)&z z !(x&y)&z|!z&x&y x&y|z !x&z|!y&!z&x !x&z|!y&!z&x|y&z !x&z|!z&x !x&z|!z&x|x&y !x&z|!y&x !y&x|z !(x&y)&z|!z&x x|z !(!y&!z|x|y&z) !(!y&!z|x|y&z)|x&y&z !x&!y&z|!z&y !x&!y&z|!z&y|x&y !x&!z&y|!y&z !x&!z&y|!y&z|x&z !y&z|!z&y !y&z|!z&y|x&y !(!x&!y|x&y|z)|!x&!y&z !(!x&!y|x&y|z)|!x&!y&z|x&y&z !x&!y&z|!z&(x|y) !x&!y&z|!z&(x|y)|x&y !x&!z&y|!y&(x|z) !x&!z&y|!y&(x|z)|x&z !y&(x|z)|!z&y !y&z|!z&y|x !x&(y|z) !x&(y|z)|y&z !x&z|!z&y !x&z|y !x&y|!y&z !x&y|z !(x&y)&z|!z&y y|z !x&(y|z)|!y&!z&x !x&(y|z)|!y&!z&x|y&z !x&(y|z)|!z&x !x&z|!z&x|y !x&(y|z)|!y&x !x&y|!y&x|z !x&y|!y&z|!z&x x|y|z !(x|y|z) !(x|y|z)|x&y&z !(!x&y|!y&x|z) !(x|y|z)|x&y !(!x&z|!z&x|y) !(x|y|z)|x&z !(!x&y|!y&x|z)|!y&x&z !(x|y|z)|(y|z)&x !y&!z !y&!z|x&y&z !(!x&y|z) !y&!z|x&y !(!x&z|y) !y&!z|x&z !(!x&y|z)|!y&x !y&!z|x !(!y&z|!z&y|x) !(x|y|z)|y&z !(!x&y|!y&x|z)|!x&y&z !(x|y|z)|(x|z)&y !(!x&z|!z&x|y)|!x&y&z !(x|y|z)|(x|y)&z !(!x&y|!y&x|z)|!x&y&z|!y&x&z !(x|y|z)|(x|y)&z|x&y !x&y&z|!y&!z !y&!z|y&z !(!x&y|z)|!x&y&z !(!x&y|z)|y&z !(!x&z|y)|!x&y&z !(!x&z|y)|y&z !(!x&y|z)|!x&y&z|!y&x !y&!z|x|y&z !x&!z !x&!z|x&y&z !(!y&x|z) !x&!z|x&y !x&!z|!y&x&z !x&!z|x&z !(!y&x|z)|!y&x&z !(!y&x|z)|x&z !(x&y|z) !(x&y|z)|x&y&z !z !z|x&y !x&!z|!y&x !(x&y|z)|x&z !y&x|!z !z|x !(!y&z|x) !x&!z|y&z !(!y&x|z)|!x&y !x&!z|y !(!y&z|x)|!y&x&z !(!y&z|x)|x&z !(!y&x|z)|!x&y|!y&x&z !x&!z|x&z|y !x&y|!y&!z !(x&y|z)|y&z !x&y|!z !z|y !(!x&!y&z|x&y) !x&!z|!y&x|y&z !x&y|!y&x|!z !z|x|y !x&!y !x&!y|x&y&z !x&!y|!z&x&y !x&!y|x&y !(!z&x|y) !x&!y|x&z !(!z&x|y)|!z&x&y !(!z&x|y)|x&y !(x&z|y) !(x&z|y)|x&y&z !x&!y|!z&x !(x&z|y)|x&y !y !y|x&z !y|!z&x !y|x !(!z&y|x) !x&!y|y&z !(!z&y|x)|!z&x&y !(!z&y|x)|x&y !(!z&x|y)|!x&z !x&!y|z !(!z&x|y)|!x&z|!z&x&y !x&!y|x&y|z !x&z|!y&!z !(x&z|y)|y&z !(!x&!z&y|x&z) !x&!y|!z&x|y&z !x&z|!y !y|z !x&z|!y|!z&x !y|x|z !(x|y&z) !(x|y&z)|x&y&z !x&!y|!z&y !(x|y&z)|x&y !x&!z|!y&z !(x|y&z)|x&z !(!y&!z&x|y&z) !x&!y|!z&y|x&z !((x|y)&z|x&y) !((x|y)&z|x&y)|x&y&z !x&!y|!z !x&!y|!z|x&y !x&!z|!y !x&!z|!y|x&z !y|!z !y|!z|x !x !x|y&z !x|!z&y !x|y !x|!y&z !x|z !x|!y&z|!z&y !x|y|z !x|!y&!z !x|!y&!z|y&z !x|!z !x|!z|y !x|!y !x|!y|z !(x&y&z) !x|x".split() n = int(input()) for i in range(n): print(table[int(input(), 2)]) exit(0) E = set() T = set() F = set('xyz') prv = 0 x = int('00001111', 2) y = int('00110011', 2) z = int('01010101', 2) fam = 2 ** 8 tmpl = '#' * 99 ans = [tmpl] * fam def cmpr(E): global ans ans = [tmpl] * fam for e in E: res = eval(e.replace('!', '~')) & (fam - 1) if len(ans[res]) > len(e) or len(ans[res]) == len(e) and ans[res] > e: ans[res] = e return set(ans) - {tmpl} def cmpr3(E, T, F): return cmpr(E), cmpr(T), cmpr(F) while prv != (E, T, F): prv = E.copy(), T.copy(), F.copy() for f in prv[2]: F.add('!' + f) T.add(f) for t in prv[1]: T.add(t + '&' + f) for t in prv[1]: E.add(t) for e in prv[0]: if e not in F: F.add('(' + e + ')') for t in prv[1]: E.add(e + '|' + t) E, T, F = cmpr3(E, T, F) cmpr(E) for f in ans: print(f) print(ans.count(tmpl), fam - ans.count(tmpl)) ```
101,746
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Tags: bitmasks, dp, shortest paths Correct Solution: ``` answers = [ '!x&x', 'x&y&z', '!z&x&y', 'x&y', '!y&x&z', 'x&z', '!y&x&z|!z&x&y', '(y|z)&x', '!y&!z&x', '!y&!z&x|x&y&z', '!z&x', '!z&x|x&y', '!y&x', '!y&x|x&z', '!(y&z)&x', 'x', '!x&y&z', 'y&z', '!x&y&z|!z&x&y', '(x|z)&y', '!x&y&z|!y&x&z', '(x|y)&z', '!x&y&z|!y&x&z|!z&x&y', '(x|y)&z|x&y', '!x&y&z|!y&!z&x', '!y&!z&x|y&z', '!x&y&z|!z&x', '!z&x|y&z', '!x&y&z|!y&x', '!y&x|y&z', '!(y&z)&x|!x&y&z', 'x|y&z', '!x&!z&y', '!x&!z&y|x&y&z', '!z&y', '!z&y|x&y', '!x&!z&y|!y&x&z', '!x&!z&y|x&z', '!y&x&z|!z&y', '!z&y|x&z', '!(!x&!y|x&y|z)', '!(!x&!y|x&y|z)|x&y&z', '!z&(x|y)', '!z&(x|y)|x&y', '!x&!z&y|!y&x', '!x&!z&y|!y&x|x&z', '!y&x|!z&y', '!z&y|x', '!x&y', '!x&y|y&z', '!(x&z)&y', 'y', '!x&y|!y&x&z', '!x&y|x&z', '!(x&z)&y|!y&x&z', 'x&z|y', '!x&y|!y&!z&x', '!x&y|!y&!z&x|y&z', '!x&y|!z&x', '!z&x|y', '!x&y|!y&x', '!x&y|!y&x|x&z', '!(x&z)&y|!y&x', 'x|y', '!x&!y&z', '!x&!y&z|x&y&z', '!x&!y&z|!z&x&y', '!x&!y&z|x&y', '!y&z', '!y&z|x&z', '!y&z|!z&x&y', '!y&z|x&y', '!(!x&!z|x&z|y)', '!(!x&!z|x&z|y)|x&y&z', '!x&!y&z|!z&x', '!x&!y&z|!z&x|x&y', '!y&(x|z)', '!y&(x|z)|x&z', '!y&z|!z&x', '!y&z|x', '!x&z', '!x&z|y&z', '!x&z|!z&x&y', '!x&z|x&y', '!(x&y)&z', 'z', '!(x&y)&z|!z&x&y', 'x&y|z', '!x&z|!y&!z&x', '!x&z|!y&!z&x|y&z', '!x&z|!z&x', '!x&z|!z&x|x&y', '!x&z|!y&x', '!y&x|z', '!(x&y)&z|!z&x', 'x|z', '!(!y&!z|x|y&z)', '!(!y&!z|x|y&z)|x&y&z', '!x&!y&z|!z&y', '!x&!y&z|!z&y|x&y', '!x&!z&y|!y&z', '!x&!z&y|!y&z|x&z', '!y&z|!z&y', '!y&z|!z&y|x&y', '!(!x&!y|x&y|z)|!x&!y&z', '!(!x&!y|x&y|z)|!x&!y&z|x&y&z', '!x&!y&z|!z&(x|y)', '!x&!y&z|!z&(x|y)|x&y', '!x&!z&y|!y&(x|z)', '!x&!z&y|!y&(x|z)|x&z', '!y&(x|z)|!z&y', '!y&z|!z&y|x', '!x&(y|z)', '!x&(y|z)|y&z', '!x&z|!z&y', '!x&z|y', '!x&y|!y&z', '!x&y|z', '!(x&y)&z|!z&y', 'y|z', '!x&(y|z)|!y&!z&x', '!x&(y|z)|!y&!z&x|y&z', '!x&(y|z)|!z&x', '!x&z|!z&x|y', '!x&(y|z)|!y&x', '!x&y|!y&x|z', '!x&y|!y&z|!z&x', 'x|y|z', '!(x|y|z)', '!(x|y|z)|x&y&z', '!(!x&y|!y&x|z)', '!(x|y|z)|x&y', '!(!x&z|!z&x|y)', '!(x|y|z)|x&z', '!(!x&y|!y&x|z)|!y&x&z', '!(x|y|z)|(y|z)&x', '!y&!z', '!y&!z|x&y&z', '!(!x&y|z)', '!y&!z|x&y', '!(!x&z|y)', '!y&!z|x&z', '!(!x&y|z)|!y&x', '!y&!z|x', '!(!y&z|!z&y|x)', '!(x|y|z)|y&z', '!(!x&y|!y&x|z)|!x&y&z', '!(x|y|z)|(x|z)&y', '!(!x&z|!z&x|y)|!x&y&z', '!(x|y|z)|(x|y)&z', '!(!x&y|!y&x|z)|!x&y&z|!y&x&z', '!(x|y|z)|(x|y)&z|x&y', '!x&y&z|!y&!z', '!y&!z|y&z', '!(!x&y|z)|!x&y&z', '!(!x&y|z)|y&z', '!(!x&z|y)|!x&y&z', '!(!x&z|y)|y&z', '!(!x&y|z)|!x&y&z|!y&x', '!y&!z|x|y&z', '!x&!z', '!x&!z|x&y&z', '!(!y&x|z)', '!x&!z|x&y', '!x&!z|!y&x&z', '!x&!z|x&z', '!(!y&x|z)|!y&x&z', '!(!y&x|z)|x&z', '!(x&y|z)', '!(x&y|z)|x&y&z', '!z', '!z|x&y', '!x&!z|!y&x', '!(x&y|z)|x&z', '!y&x|!z', '!z|x', '!(!y&z|x)', '!x&!z|y&z', '!(!y&x|z)|!x&y', '!x&!z|y', '!(!y&z|x)|!y&x&z', '!(!y&z|x)|x&z', '!(!y&x|z)|!x&y|!y&x&z', '!x&!z|x&z|y', '!x&y|!y&!z', '!(x&y|z)|y&z', '!x&y|!z', '!z|y', '!(!x&!y&z|x&y)', '!x&!z|!y&x|y&z', '!x&y|!y&x|!z', '!z|x|y', '!x&!y', '!x&!y|x&y&z', '!x&!y|!z&x&y', '!x&!y|x&y', '!(!z&x|y)', '!x&!y|x&z', '!(!z&x|y)|!z&x&y', '!(!z&x|y)|x&y', '!(x&z|y)', '!(x&z|y)|x&y&z', '!x&!y|!z&x', '!(x&z|y)|x&y', '!y', '!y|x&z', '!y|!z&x', '!y|x', '!(!z&y|x)', '!x&!y|y&z', '!(!z&y|x)|!z&x&y', '!(!z&y|x)|x&y', '!(!z&x|y)|!x&z', '!x&!y|z', '!(!z&x|y)|!x&z|!z&x&y', '!x&!y|x&y|z', '!x&z|!y&!z', '!(x&z|y)|y&z', '!(!x&!z&y|x&z)', '!x&!y|!z&x|y&z', '!x&z|!y', '!y|z', '!x&z|!y|!z&x', '!y|x|z', '!(x|y&z)', '!(x|y&z)|x&y&z', '!x&!y|!z&y', '!(x|y&z)|x&y', '!x&!z|!y&z', '!(x|y&z)|x&z', '!(!y&!z&x|y&z)', '!x&!y|!z&y|x&z', '!((x|y)&z|x&y)', '!((x|y)&z|x&y)|x&y&z', '!x&!y|!z', '!x&!y|!z|x&y', '!x&!z|!y', '!x&!z|!y|x&z', '!y|!z', '!y|!z|x', '!x', '!x|y&z', '!x|!z&y', '!x|y', '!x|!y&z', '!x|z', '!x|!y&z|!z&y', '!x|y|z', '!x|!y&!z', '!x|!y&!z|y&z', '!x|!z', '!x|!z|y', '!x|!y', '!x|!y|z', '!(x&y&z)', '!x|x'] N = int(input()) for i in range(N): q = int(input(), 2) print(answers[q]) ```
101,747
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Tags: bitmasks, dp, shortest paths Correct Solution: ``` sol = {'01010101': 'z', '00110011': 'y', '00001111': 'x', '10101010': '!z', '11001100': '!y', '11110000': '!x', '01110111': 'y|z', '01011111': 'x|z', '00010001': 'y&z', '00000101': 'x&z', '00111111': 'x|y', '00000011': 'x&y', '11111111': '!x|x', '11011101': '!y|z', '11110101': '!x|z', '00000000': '!x&x', '01000100': '!y&z', '01010000': '!x&z', '10111011': '!z|y', '11110011': '!x|y', '00100010': '!z&y', '00110000': '!x&y', '10101111': '!z|x', '11001111': '!y|x', '00001010': '!z&x', '00001100': '!y&x', '01111111': 'x|y|z', '01010111': 'x&y|z', '00011111': 'x|y&z', '00000001': 'x&y&z', '00110111': 'x&z|y', '11110111': '!x|y|z', '01110101': '!x&y|z', '11011111': '!y|x|z', '01011101': '!y&x|z', '11110001': '!x|y&z', '00010000': '!x&y&z', '11001101': '!y|x&z', '00000100': '!y&x&z', '01110011': '!x&z|y', '10111111': '!z|x|y', '00111011': '!z&x|y', '10101011': '!z|x&y', '00000010': '!z&x&y', '01001111': '!y&z|x', '00101111': '!z&y|x', '10001000': '!y&!z', '10100000': '!x&!z', '11101110': '!y|!z', '11111010': '!x|!z', '11000000': '!x&!y', '11111100': '!x|!y', '00010101': '(x|y)&z', '00010011': '(x|z)&y', '00000111': '(y|z)&x', '11010101': '!x&!y|z', '11111101': '!x|!y|z', '01010001': '!x&z|y&z', '00110001': '!x&y|y&z', '00011011': '!z&x|y&z', '00011101': '!y&x|y&z', '01000101': '!y&z|x&z', '00100111': '!z&y|x&z', '00110101': '!x&y|x&z', '00001101': '!y&x|x&z', '01000000': '!x&!y&z', '01010100': '!(x&y)&z', '10110011': '!x&!z|y', '11111011': '!x|!z|y', '01000111': '!y&z|x&y', '01010011': '!x&z|x&y', '00100011': '!z&y|x&y', '00001011': '!z&x|x&y', '00100000': '!x&!z&y', '00110010': '!(x&z)&y', '10001111': '!y&!z|x', '11101111': '!y|!z|x', '00001000': '!y&!z&x', '00001110': '!(y&z)&x', '10000000': '!(x|y|z)', '01110000': '!x&(y|z)', '10101000': '!(x&y|z)', '01001100': '!y&(x|z)', '11100000': '!(x|y&z)', '11111110': '!(x&y&z)', '11001000': '!(x&z|y)', '00101010': '!z&(x|y)', '10100010': '!(!y&x|z)', '10111010': '!x&y|!z', '10001010': '!(!x&y|z)', '10101110': '!y&x|!z', '10110001': '!x&!z|y&z', '10001101': '!y&!z|x&z', '11101010': '!x&!y|!z', '00011001': '!y&!z&x|y&z', '00100101': '!x&!z&y|x&z', '11000100': '!(!z&x|y)', '11011100': '!x&z|!y', '10001100': '!(!x&z|y)', '11001110': '!y|!z&x', '11010001': '!x&!y|y&z', '10001011': '!y&!z|x&y', '11101100': '!x&!z|!y', '01000011': '!x&!y&z|x&y', '11010000': '!(!z&y|x)', '11110100': '!x|!y&z', '10110000': '!(!y&z|x)', '11110010': '!x|!z&y', '11000101': '!x&!y|x&z', '10100011': '!x&!z|x&y', '11111000': '!x|!y&!z', '00010111': '(x|y)&z|x&y', '01110001': '!x&(y|z)|y&z', '01100110': '!y&z|!z&y', '01110010': '!x&z|!z&y', '01110100': '!x&y|!y&z', '01101111': '!y&z|!z&y|x', '01100111': '!y&z|!z&y|x&y', '00000110': '!y&x&z|!z&x&y', '01100000': '!(!y&!z|x|y&z)', '01110110': '!(x&y)&z|!z&y', '01001101': '!y&(x|z)|x&z', '01001110': '!y&z|!z&x', '01011010': '!x&z|!z&x', '01011100': '!x&z|!y&x', '01111011': '!x&z|!z&x|y', '01011011': '!x&z|!z&x|x&y', '00010010': '!x&y&z|!z&x&y', '01011110': '!(x&y)&z|!z&x', '01001000': '!(!x&!z|x&z|y)', '10011001': '!y&!z|y&z', '10011111': '!y&!z|x|y&z', '10010001': '!(x|y|z)|y&z', '10111001': '!(x&y|z)|y&z', '11011001': '!(x&z|y)|y&z', '10100101': '!x&!z|x&z', '10110111': '!x&!z|x&z|y', '10000101': '!(x|y|z)|x&z', '10101101': '!(x&y|z)|x&z', '11100101': '!(x|y&z)|x&z', '00101011': '!z&(x|y)|x&y', '00101110': '!y&x|!z&y', '00111010': '!x&y|!z&x', '00111100': '!x&y|!y&x', '01111101': '!x&y|!y&x|z', '00111101': '!x&y|!y&x|x&z', '00010100': '!x&y&z|!y&x&z', '00101000': '!(!x&!y|x&y|z)', '00111110': '!(x&z)&y|!y&x', '11000011': '!x&!y|x&y', '11010111': '!x&!y|x&y|z', '10000011': '!(x|y|z)|x&y', '11100011': '!(x|y&z)|x&y', '11001011': '!(x&z|y)|x&y', '10011101': '!(!x&z|y)|y&z', '10001001': '!y&!z|x&y&z', '11011000': '!x&z|!y&!z', '00001001': '!y&!z&x|x&y&z', '10110101': '!(!y&z|x)|x&z', '10100001': '!x&!z|x&y&z', '11100100': '!x&!z|!y&z', '00100001': '!x&!z&y|x&y&z', '01000110': '!y&z|!z&x&y', '01100100': '!x&!z&y|!y&z', '01101110': '!y&(x|z)|!z&y', '01010010': '!x&z|!z&x&y', '01011000': '!x&z|!y&!z&x', '01111010': '!x&(y|z)|!z&x', '10011011': '!(!x&y|z)|y&z', '10111000': '!x&y|!y&!z', '11010011': '!(!z&y|x)|x&y', '11000001': '!x&!y|x&y&z', '11100010': '!x&!y|!z&y', '01000001': '!x&!y&z|x&y&z', '00100110': '!y&x&z|!z&y', '01100010': '!x&!y&z|!z&y', '00110100': '!x&y|!y&x&z', '00111000': '!x&y|!y&!z&x', '01111100': '!x&(y|z)|!y&x', '10100111': '!(!y&x|z)|x&z', '10101100': '!x&!z|!y&x', '11000111': '!(!z&x|y)|x&y', '11001010': '!x&!y|!z&x', '00011010': '!x&y&z|!z&x', '01001010': '!x&!y&z|!z&x', '00011100': '!x&y&z|!y&x', '00101100': '!x&!z&y|!y&x', '01111110': '!x&y|!y&z|!z&x', '01010110': '!(x&y)&z|!z&x&y', '00011110': '!(y&z)&x|!x&y&z', '10000001': '!(x|y|z)|x&y&z', '10101001': '!(x&y|z)|x&y&z', '11100001': '!(x|y&z)|x&y&z', '11001001': '!(x&z|y)|x&y&z', '00110110': '!(x&z)&y|!y&x&z', '11100110': '!(!y&!z&x|y&z)', '10000111': '!(x|y|z)|(y|z)&x', '11100111': '!x&!y|!z&y|x&z', '11110110': '!x|!y&z|!z&y', '01100101': '!x&!z&y|!y&z|x&z', '11011010': '!(!x&!z&y|x&z)', '10010011': '!(x|y|z)|(x|z)&y', '11011011': '!x&!y|!z&x|y&z', '11011110': '!x&z|!y|!z&x', '01011001': '!x&z|!y&!z&x|y&z', '11111001': '!x|!y&!z|y&z', '10011000': '!x&y&z|!y&!z', '00011000': '!x&y&z|!y&!z&x', '10010000': '!(!y&z|!z&y|x)', '11101101': '!x&!z|!y|x&z', '10100100': '!x&!z|!y&x&z', '00100100': '!x&!z&y|!y&x&z', '10000100': '!(!x&z|!z&x|y)', '01100011': '!x&!y&z|!z&y|x&y', '10111100': '!(!x&!y&z|x&y)', '10010101': '!(x|y|z)|(x|y)&z', '10111101': '!x&!z|!y&x|y&z', '10111110': '!x&y|!y&x|!z', '00111001': '!x&y|!y&!z&x|y&z', '11101011': '!x&!y|!z|x&y', '11000010': '!x&!y|!z&x&y', '01000010': '!x&!y&z|!z&x&y', '10000010': '!(!x&y|!y&x|z)', '01001011': '!x&!y&z|!z&x|x&y', '00101101': '!x&!z&y|!y&x|x&z', '10001110': '!(!x&y|z)|!y&x', '11101000': '!((x|y)&z|x&y)', '10110010': '!(!y&x|z)|!x&y', '11010100': '!(!z&x|y)|!x&z', '01101010': '!x&!y&z|!z&(x|y)', '01101100': '!x&!z&y|!y&(x|z)', '01111000': '!x&(y|z)|!y&!z&x', '00010110': '!x&y&z|!y&x&z|!z&x&y', '01100001': '!(!y&!z|x|y&z)|x&y&z', '01001001': '!(!x&!z|x&z|y)|x&y&z', '10010111': '!(x|y|z)|(x|y)&z|x&y', '01111001': '!x&(y|z)|!y&!z&x|y&z', '01101101': '!x&!z&y|!y&(x|z)|x&z', '00101001': '!(!x&!y|x&y|z)|x&y&z', '01101011': '!x&!y&z|!z&(x|y)|x&y', '10011100': '!(!x&z|y)|!x&y&z', '10110100': '!(!y&z|x)|!y&x&z', '11000110': '!(!z&x|y)|!z&x&y', '11010010': '!(!z&y|x)|!z&x&y', '10011010': '!(!x&y|z)|!x&y&z', '10100110': '!(!y&x|z)|!y&x&z', '01101000': '!(!x&!y|x&y|z)|!x&!y&z', '11101001': '!((x|y)&z|x&y)|x&y&z', '11010110': '!(!z&x|y)|!x&z|!z&x&y', '10110110': '!(!y&x|z)|!x&y|!y&x&z', '10000110': '!(!x&y|!y&x|z)|!y&x&z', '10011110': '!(!x&y|z)|!x&y&z|!y&x', '10010010': '!(!x&y|!y&x|z)|!x&y&z', '10010100': '!(!x&z|!z&x|y)|!x&y&z', '01101001': '!(!x&!y|x&y|z)|!x&!y&z|x&y&z', '10010110': '!(!x&y|!y&x|z)|!x&y&z|!y&x&z'} n = int(input()) for i in range(n): print(sol[input()]) ```
101,748
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Tags: bitmasks, dp, shortest paths Correct Solution: ``` import zlib, base64 exec(zlib.decompress(base64.b64decode(b'eJyFV8lu2zAQPTdfIenAUGhR9FygXxLk4MJu4SJwAscJSIEfX4nLzHtDpT0kGM6+j3w83IYfw8M0BhemL8M0+pBiWuYMBzdGtwjYgMUpWGRWtnFJq6Srkh7g4JqSjW9Jm3wKjdYohIzALkivfuX/m02nYBUJ2ZNVLjZPAM5hrFTR5BFGasLg/RbOvPniIsSU0AXAtMgMnanRShPVFx+QA+jRad5CyWhoMUbIqCBL0RII5jSZd+Fg+sLB7dpNWOItRcaFNKqVyFpKgdkR9ELB2PpzhIJGt1amli/aSDlOQ1W5ymHiJFsYYHCkD0VZsMSmDSMl1XpmYM2R9HtTwgOYgCe3KLwXmJUdMRaiID+w28WKfGVICbfyzMaHNKq36IWCC+Qp7gTLoVYRL+28GH6Pjb7JmDjJ1l6AsDu2CGFzJR5RM58wnDCZ/8it9nlXgzYrihNlNr2dFmUoamj1pv961Y93meJ9B62u0gF2rkXzB3qlJziEzfWuYFHWPJQLSrNZExXlgesBaI1S7dDm4v6AYYZkwNRD40AGaBck3vYLibQi4e7Mpzdhf7YtAgh+loaltc0HVw5zYkuEsS7ggJBtuAiJjOrDswaBanOqF9E6C7ebnO0wdKn5+BjM3k1HOl5245pj1yknlqH5iOnZ4TG5pSsPGSN7oesOHf3AbWGaglqiO/MpdM2Q3zUjZBNwYFBD7Q46XvMWlWxICAFca8Mq7x2nQwpdqS0Pa6nXHaxAQUZTtby1qnH+YLH6sFyySaV6qRYumsLpNS4dRyPdzjkSFitEDDDFtXB6irVwggtgVE55RYBFZW4rWm62iMd91wK4JjOL11vfO9LMUS85aODCdWuK7Mu3g7BkuNqOLKSfJwXMY8k/hxLiokkkR2bGIdiZtTWOCWVgH+1NYMPDXMl+q8siUffUp05hY4Q6alBt8DSSVi3jvlzTAppNKU8dpwppDSokDq2uhenx7tfzdTgP58twPVx+n/z5clv/Xt5ufp7n73efXq4b5ni4PZzeD09++vZzGj4P9/df/zyfL/7p/Hrz19P76fp6OqrcPD/Od38BvToehw=='))) ```
101,749
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Tags: bitmasks, dp, shortest paths Correct Solution: ``` val='''!x&x x&y&z !z&x&y x&y !y&x&z x&z !y&x&z|!z&x&y (y|z)&x !y&!z&x !y&!z&x|x&y&z !z&x !z&x|x&y !y&x !y&x|x&z !(y&z)&x x !x&y&z y&z !x&y&z|!z&x&y (x|z)&y !x&y&z|!y&x&z (x|y)&z !x&y&z|!y&x&z|!z&x&y (x|y)&z|x&y !x&y&z|!y&!z&x !y&!z&x|y&z !x&y&z|!z&x !z&x|y&z !x&y&z|!y&x !y&x|y&z !(y&z)&x|!x&y&z x|y&z !x&!z&y !x&!z&y|x&y&z !z&y !z&y|x&y !x&!z&y|!y&x&z !x&!z&y|x&z !y&x&z|!z&y !z&y|x&z !(!x&!y|x&y|z) !(!x&!y|x&y|z)|x&y&z !z&(x|y) !z&(x|y)|x&y !x&!z&y|!y&x !x&!z&y|!y&x|x&z !y&x|!z&y !z&y|x !x&y !x&y|y&z !(x&z)&y y !x&y|!y&x&z !x&y|x&z !(x&z)&y|!y&x&z x&z|y !x&y|!y&!z&x !x&y|!y&!z&x|y&z !x&y|!z&x !z&x|y !x&y|!y&x !x&y|!y&x|x&z !(x&z)&y|!y&x x|y !x&!y&z !x&!y&z|x&y&z !x&!y&z|!z&x&y !x&!y&z|x&y !y&z !y&z|x&z !y&z|!z&x&y !y&z|x&y !(!x&!z|x&z|y) !(!x&!z|x&z|y)|x&y&z !x&!y&z|!z&x !x&!y&z|!z&x|x&y !y&(x|z) !y&(x|z)|x&z !y&z|!z&x !y&z|x !x&z !x&z|y&z !x&z|!z&x&y !x&z|x&y !(x&y)&z z !(x&y)&z|!z&x&y x&y|z !x&z|!y&!z&x !x&z|!y&!z&x|y&z !x&z|!z&x !x&z|!z&x|x&y !x&z|!y&x !y&x|z !(x&y)&z|!z&x x|z !(!y&!z|x|y&z) !(!y&!z|x|y&z)|x&y&z !x&!y&z|!z&y !x&!y&z|!z&y|x&y !x&!z&y|!y&z !x&!z&y|!y&z|x&z !y&z|!z&y !y&z|!z&y|x&y !(!x&!y|x&y|z)|!x&!y&z !(!x&!y|x&y|z)|!x&!y&z|x&y&z !x&!y&z|!z&(x|y) !x&!y&z|!z&(x|y)|x&y !x&!z&y|!y&(x|z) !x&!z&y|!y&(x|z)|x&z !y&(x|z)|!z&y !y&z|!z&y|x !x&(y|z) !x&(y|z)|y&z !x&z|!z&y !x&z|y !x&y|!y&z !x&y|z !(x&y)&z|!z&y y|z !x&(y|z)|!y&!z&x !x&(y|z)|!y&!z&x|y&z !x&(y|z)|!z&x !x&z|!z&x|y !x&(y|z)|!y&x !x&y|!y&x|z !x&y|!y&z|!z&x x|y|z !(x|y|z) !(x|y|z)|x&y&z !(!x&y|!y&x|z) !(x|y|z)|x&y !(!x&z|!z&x|y) !(x|y|z)|x&z !(!x&y|!y&x|z)|!y&x&z !(x|y|z)|(y|z)&x !y&!z !y&!z|x&y&z !(!x&y|z) !y&!z|x&y !(!x&z|y) !y&!z|x&z !(!x&y|z)|!y&x !y&!z|x !(!y&z|!z&y|x) !(x|y|z)|y&z !(!x&y|!y&x|z)|!x&y&z !(x|y|z)|(x|z)&y !(!x&z|!z&x|y)|!x&y&z !(x|y|z)|(x|y)&z !(!x&y|!y&x|z)|!x&y&z|!y&x&z !(x|y|z)|(x|y)&z|x&y !x&y&z|!y&!z !y&!z|y&z !(!x&y|z)|!x&y&z !(!x&y|z)|y&z !(!x&z|y)|!x&y&z !(!x&z|y)|y&z !(!x&y|z)|!x&y&z|!y&x !y&!z|x|y&z !x&!z !x&!z|x&y&z !(!y&x|z) !x&!z|x&y !x&!z|!y&x&z !x&!z|x&z !(!y&x|z)|!y&x&z !(!y&x|z)|x&z !(x&y|z) !(x&y|z)|x&y&z !z !z|x&y !x&!z|!y&x !(x&y|z)|x&z !y&x|!z !z|x !(!y&z|x) !x&!z|y&z !(!y&x|z)|!x&y !x&!z|y !(!y&z|x)|!y&x&z !(!y&z|x)|x&z !(!y&x|z)|!x&y|!y&x&z !x&!z|x&z|y !x&y|!y&!z !(x&y|z)|y&z !x&y|!z !z|y !(!x&!y&z|x&y) !x&!z|!y&x|y&z !x&y|!y&x|!z !z|x|y !x&!y !x&!y|x&y&z !x&!y|!z&x&y !x&!y|x&y !(!z&x|y) !x&!y|x&z !(!z&x|y)|!z&x&y !(!z&x|y)|x&y !(x&z|y) !(x&z|y)|x&y&z !x&!y|!z&x !(x&z|y)|x&y !y !y|x&z !y|!z&x !y|x !(!z&y|x) !x&!y|y&z !(!z&y|x)|!z&x&y !(!z&y|x)|x&y !(!z&x|y)|!x&z !x&!y|z !(!z&x|y)|!x&z|!z&x&y !x&!y|x&y|z !x&z|!y&!z !(x&z|y)|y&z !(!x&!z&y|x&z) !x&!y|!z&x|y&z !x&z|!y !y|z !x&z|!y|!z&x !y|x|z !(x|y&z) !(x|y&z)|x&y&z !x&!y|!z&y !(x|y&z)|x&y !x&!z|!y&z !(x|y&z)|x&z !(!y&!z&x|y&z) !x&!y|!z&y|x&z !((x|y)&z|x&y) !((x|y)&z|x&y)|x&y&z !x&!y|!z !x&!y|!z|x&y !x&!z|!y !x&!z|!y|x&z !y|!z !y|!z|x !x !x|y&z !x|!z&y !x|y !x|!y&z !x|z !x|!y&z|!z&y !x|y|z !x|!y&!z !x|!y&!z|y&z !x|!z !x|!z|y !x|!y !x|!y|z !(x&y&z) !x|x'''.split() for _ in range(int(input())): n=0 for b in input(): n<<=1 if b=='1': n|=1 print(val[n]) ```
101,750
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Tags: bitmasks, dp, shortest paths Correct Solution: ``` f =['!x&x', '!(x|y|z)', '!x&!y&z', '!x&!y', '!x&!z&y', '!x&!z', '!(!y&!z|x|y&z)', '!(x|y&z)', '!x&y&z', '!(!y&z|!z&y|x)', '!x&z', '!(!z&y|x)', '!x&y', '!(!y&z|x)', '!x&(y|z)', '!x', '!y&!z&x', '!y&!z', '!(!x&!z|x&z|y)', '!(x&z|y)', '!(!x&!y|x&y|z)', '!(x&y|z)', '!(!x&!y|x&y|z)|!x&!y&z', '!((x|y)&z|x&y)', '!x&y&z|!y&!z&x', '!x&y&z|!y&!z', '!x&z|!y&!z&x', '!x&z|!y&!z', '!x&y|!y&!z&x', '!x&y|!y&!z', '!x&(y|z)|!y&!z&x', '!x|!y&!z', '!y&x&z', '!(!x&z|!z&x|y)', '!y&z', '!(!z&x|y)', '!x&!z&y|!y&x&z', '!x&!z|!y&x&z', '!x&!z&y|!y&z', '!x&!z|!y&z', '!x&y&z|!y&x&z', '!(!x&z|!z&x|y)|!x&y&z', '!(x&y)&z', '!(!z&x|y)|!x&z', '!x&y|!y&x&z', '!(!y&z|x)|!y&x&z', '!x&y|!y&z', '!x|!y&z', '!y&x', '!(!x&z|y)', '!y&(x|z)', '!y', '!x&!z&y|!y&x', '!x&!z|!y&x', '!x&!z&y|!y&(x|z)', '!x&!z|!y', '!x&y&z|!y&x', '!(!x&z|y)|!x&y&z', '!x&z|!y&x', '!x&z|!y', '!x&y|!y&x', '!(!x&!y&z|x&y)', '!x&(y|z)|!y&x', '!x|!y', '!z&x&y', '!(!x&y|!y&x|z)', '!x&!y&z|!z&x&y', '!x&!y|!z&x&y', '!z&y', '!(!y&x|z)', '!x&!y&z|!z&y', '!x&!y|!z&y', '!x&y&z|!z&x&y', '!(!x&y|!y&x|z)|!x&y&z', '!x&z|!z&x&y', '!(!z&y|x)|!z&x&y', '!(x&z)&y', '!(!y&x|z)|!x&y', '!x&z|!z&y', '!x|!z&y', '!z&x', '!(!x&y|z)', '!x&!y&z|!z&x', '!x&!y|!z&x', '!z&(x|y)', '!z', '!x&!y&z|!z&(x|y)', '!x&!y|!z', '!x&y&z|!z&x', '!(!x&y|z)|!x&y&z', '!x&z|!z&x', '!(!x&!z&y|x&z)', '!x&y|!z&x', '!x&y|!z', '!x&(y|z)|!z&x', '!x|!z', '!y&x&z|!z&x&y', '!(!x&y|!y&x|z)|!y&x&z', '!y&z|!z&x&y', '!(!z&x|y)|!z&x&y', '!y&x&z|!z&y', '!(!y&x|z)|!y&x&z', '!y&z|!z&y', '!(!y&!z&x|y&z)', '!x&y&z|!y&x&z|!z&x&y', '!(!x&y|!y&x|z)|!x&y&z|!y&x&z', '!(x&y)&z|!z&x&y', '!(!z&x|y)|!x&z|!z&x&y', '!(x&z)&y|!y&x&z', '!(!y&x|z)|!x&y|!y&x&z', '!(x&y)&z|!z&y', '!x|!y&z|!z&y', '!(y&z)&x', '!(!x&y|z)|!y&x', '!y&z|!z&x', '!y|!z&x', '!y&x|!z&y', '!y&x|!z', '!y&(x|z)|!z&y', '!y|!z', '!(y&z)&x|!x&y&z', '!(!x&y|z)|!x&y&z|!y&x', '!(x&y)&z|!z&x', '!x&z|!y|!z&x', '!(x&z)&y|!y&x', '!x&y|!y&x|!z', '!x&y|!y&z|!z&x', '!(x&y&z)', 'x&y&z', '!(x|y|z)|x&y&z', '!x&!y&z|x&y&z', '!x&!y|x&y&z', '!x&!z&y|x&y&z', '!x&!z|x&y&z', '!(!y&!z|x|y&z)|x&y&z', '!(x|y&z)|x&y&z', 'y&z', '!(x|y|z)|y&z', '!x&z|y&z', '!x&!y|y&z', '!x&y|y&z', '!x&!z|y&z', '!x&(y|z)|y&z', '!x|y&z', '!y&!z&x|x&y&z', '!y&!z|x&y&z', '!(!x&!z|x&z|y)|x&y&z', '!(x&z|y)|x&y&z', '!(!x&!y|x&y|z)|x&y&z', '!(x&y|z)|x&y&z', '!(!x&!y|x&y|z)|!x&!y&z|x&y&z', '!((x|y)&z|x&y)|x&y&z', '!y&!z&x|y&z', '!y&!z|y&z', '!x&z|!y&!z&x|y&z', '!(x&z|y)|y&z', '!x&y|!y&!z&x|y&z', '!(x&y|z)|y&z', '!x&(y|z)|!y&!z&x|y&z', '!x|!y&!z|y&z', 'x&z', '!(x|y|z)|x&z', '!y&z|x&z', '!x&!y|x&z', '!x&!z&y|x&z', '!x&!z|x&z', '!x&!z&y|!y&z|x&z', '!(x|y&z)|x&z', '(x|y)&z', '!(x|y|z)|(x|y)&z', 'z', '!x&!y|z', '!x&y|x&z', '!(!y&z|x)|x&z', '!x&y|z', '!x|z', '!y&x|x&z', '!y&!z|x&z', '!y&(x|z)|x&z', '!y|x&z', '!x&!z&y|!y&x|x&z', '!(x&y|z)|x&z', '!x&!z&y|!y&(x|z)|x&z', '!x&!z|!y|x&z', '!y&x|y&z', '!(!x&z|y)|y&z', '!y&x|z', '!y|z', '!x&y|!y&x|x&z', '!x&!z|!y&x|y&z', '!x&y|!y&x|z', '!x|!y|z', 'x&y', '!(x|y|z)|x&y', '!x&!y&z|x&y', '!x&!y|x&y', '!z&y|x&y', '!x&!z|x&y', '!x&!y&z|!z&y|x&y', '!(x|y&z)|x&y', '(x|z)&y', '!(x|y|z)|(x|z)&y', '!x&z|x&y', '!(!z&y|x)|x&y', 'y', '!x&!z|y', '!x&z|y', '!x|y', '!z&x|x&y', '!y&!z|x&y', '!x&!y&z|!z&x|x&y', '!(x&z|y)|x&y', '!z&(x|y)|x&y', '!z|x&y', '!x&!y&z|!z&(x|y)|x&y', '!x&!y|!z|x&y', '!z&x|y&z', '!(!x&y|z)|y&z', '!x&z|!z&x|x&y', '!x&!y|!z&x|y&z', '!z&x|y', '!z|y', '!x&z|!z&x|y', '!x|!z|y', '(y|z)&x', '!(x|y|z)|(y|z)&x', '!y&z|x&y', '!(!z&x|y)|x&y', '!z&y|x&z', '!(!y&x|z)|x&z', '!y&z|!z&y|x&y', '!x&!y|!z&y|x&z', '(x|y)&z|x&y', '!(x|y|z)|(x|y)&z|x&y', 'x&y|z', '!x&!y|x&y|z', 'x&z|y', '!x&!z|x&z|y', 'y|z', '!x|y|z', 'x', '!y&!z|x', '!y&z|x', '!y|x', '!z&y|x', '!z|x', '!y&z|!z&y|x', '!y|!z|x', 'x|y&z', '!y&!z|x|y&z', 'x|z', '!y|x|z', 'x|y', '!z|x|y', 'x|y|z', '!x|x'] n = int(input()) for i in range(n): s = input() a = 0 for j in range(8): a += int(s[j] == '1') << j print(f[a]) ```
101,751
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Tags: bitmasks, dp, shortest paths Correct Solution: ``` # -*- coding: utf-8 -*- dat = "硼磷碳磷溴硼氧磷氮硫氮氯氟溴硼磷碳硼硫碳氯溴硼磷碳硼硫溴硼磷碳硼氯碳硫溴硼磷碳硼氯溴硼氧硼硫碳硼氯氮磷氮硫碳氯氟溴硼氧磷氮硫碳氯氟溴硼磷碳硫碳氯溴硼氧硼硫碳氯氮硼氯碳硫氮磷氟溴硼磷碳氯溴硼氧硼氯碳硫氮磷氟溴硼磷碳硫溴硼氧硼硫碳氯氮磷氟溴硼磷碳氧硫氮氯氟溴硼磷溴硼硫碳硼氯碳磷溴硼硫碳硼氯溴硼氧硼磷碳硼氯氮磷碳氯氮硫氟溴硼氧磷碳氯氮硫氟溴硼氧硼磷碳硼硫氮磷碳硫氮氯氟溴硼氧磷碳硫氮氯氟溴硼氧硼磷碳硼硫氮磷碳硫氮氯氟氮硼磷碳硼硫碳氯溴硼氧氧磷氮硫氟碳氯氮磷碳硫氟溴硼磷碳硫碳氯氮硼硫碳硼氯碳磷溴硼磷碳硫碳氯氮硼硫碳硼氯溴硼磷碳氯氮硼硫碳硼氯碳磷溴硼磷碳氯氮硼硫碳硼氯溴硼磷碳硫氮硼硫碳硼氯碳磷溴硼磷碳硫氮硼硫碳硼氯溴硼磷碳氧硫氮氯氟氮硼硫碳硼氯碳磷溴硼磷氮硼硫碳硼氯溴硼硫碳磷碳氯溴硼氧硼磷碳氯氮硼氯碳磷氮硫氟溴硼硫碳氯溴硼氧硼氯碳磷氮硫氟溴硼磷碳硼氯碳硫氮硼硫碳磷碳氯溴硼磷碳硼氯氮硼硫碳磷碳氯溴硼磷碳硼氯碳硫氮硼硫碳氯溴硼磷碳硼氯氮硼硫碳氯溴硼磷碳硫碳氯氮硼硫碳磷碳氯溴硼氧硼磷碳氯氮硼氯碳磷氮硫氟氮硼磷碳硫碳氯溴硼氧磷碳硫氟碳氯溴硼氧硼氯碳磷氮硫氟氮硼磷碳氯溴硼磷碳硫氮硼硫碳磷碳氯溴硼氧硼硫碳氯氮磷氟氮硼硫碳磷碳氯溴硼磷碳硫氮硼硫碳氯溴硼磷氮硼硫碳氯溴硼硫碳磷溴硼氧硼磷碳氯氮硫氟溴硼硫碳氧磷氮氯氟溴硼硫溴硼磷碳硼氯碳硫氮硼硫碳磷溴硼磷碳硼氯氮硼硫碳磷溴硼磷碳硼氯碳硫氮硼硫碳氧磷氮氯氟溴硼磷碳硼氯氮硼硫溴硼磷碳硫碳氯氮硼硫碳磷溴硼氧硼磷碳氯氮硫氟氮硼磷碳硫碳氯溴硼磷碳氯氮硼硫碳磷溴硼磷碳氯氮硼硫溴硼磷碳硫氮硼硫碳磷溴硼氧硼磷碳硼硫碳氯氮磷碳硫氟溴硼磷碳氧硫氮氯氟氮硼硫碳磷溴硼磷氮硼硫溴硼氯碳磷碳硫溴硼氧硼磷碳硫氮硼硫碳磷氮氯氟溴硼磷碳硼硫碳氯氮硼氯碳磷碳硫溴硼磷碳硼硫氮硼氯碳磷碳硫溴硼氯碳硫溴硼氧硼硫碳磷氮氯氟溴硼磷碳硼硫碳氯氮硼氯碳硫溴硼磷碳硼硫氮硼氯碳硫溴硼磷碳硫碳氯氮硼氯碳磷碳硫溴硼氧硼磷碳硫氮硼硫碳磷氮氯氟氮硼磷碳硫碳氯溴硼磷碳氯氮硼氯碳磷碳硫溴硼氧硼氯碳硫氮磷氟氮硼氯碳磷碳硫溴硼氧磷碳氯氟碳硫溴硼氧硼硫碳磷氮氯氟氮硼磷碳硫溴硼磷碳氯氮硼氯碳硫溴硼磷氮硼氯碳硫溴硼氯碳磷溴硼氧硼磷碳硫氮氯氟溴硼磷碳硼硫碳氯氮硼氯碳磷溴硼磷碳硼硫氮硼氯碳磷溴硼氯碳氧磷氮硫氟溴硼氯溴硼磷碳硼硫碳氯氮硼氯碳氧磷氮硫氟溴硼磷碳硼硫氮硼氯溴硼磷碳硫碳氯氮硼氯碳磷溴硼氧硼磷碳硫氮氯氟氮硼磷碳硫碳氯溴硼磷碳氯氮硼氯碳磷溴硼氧硼磷碳硼氯碳硫氮磷碳氯氟溴硼磷碳硫氮硼氯碳磷溴硼磷碳硫氮硼氯溴硼磷碳氧硫氮氯氟氮硼氯碳磷溴硼磷氮硼氯溴硼硫碳磷碳氯氮硼氯碳磷碳硫溴硼氧硼磷碳硫氮硼硫碳磷氮氯氟氮硼硫碳磷碳氯溴硼硫碳氯氮硼氯碳磷碳硫溴硼氧硼氯碳磷氮硫氟氮硼氯碳磷碳硫溴硼硫碳磷碳氯氮硼氯碳硫溴硼氧硼硫碳磷氮氯氟氮硼硫碳磷碳氯溴硼硫碳氯氮硼氯碳硫溴硼氧硼硫碳硼氯碳磷氮硫碳氯氟溴硼磷碳硫碳氯氮硼硫碳磷碳氯氮硼氯碳磷碳硫溴硼氧硼磷碳硫氮硼硫碳磷氮氯氟氮硼磷碳硫碳氯氮硼硫碳磷碳氯溴硼氧磷碳硫氟碳氯氮硼氯碳磷碳硫溴硼氧硼氯碳磷氮硫氟氮硼磷碳氯氮硼氯碳磷碳硫溴硼氧磷碳氯氟碳硫氮硼硫碳磷碳氯溴硼氧硼硫碳磷氮氯氟氮硼磷碳硫氮硼硫碳磷碳氯溴硼氧磷碳硫氟碳氯氮硼氯碳硫溴硼磷氮硼硫碳氯氮硼氯碳硫溴硼氧硫碳氯氟碳磷溴硼氧硼磷碳硫氮氯氟氮硼硫碳磷溴硼硫碳氯氮硼氯碳磷溴硼硫氮硼氯碳磷溴硼硫碳磷氮硼氯碳硫溴硼硫碳磷氮硼氯溴硼硫碳氧磷氮氯氟氮硼氯碳硫溴硼硫氮硼氯溴硼氧硫碳氯氟碳磷氮硼磷碳硫碳氯溴硼氧硼磷碳硫氮氯氟氮硼磷碳硫碳氯氮硼硫碳磷溴硼氧磷碳硫氟碳氯氮硼氯碳磷溴硼磷碳氯氮硼硫氮硼氯碳磷溴硼氧磷碳氯氟碳硫氮硼硫碳磷溴硼磷碳硫氮硼硫碳磷氮硼氯溴硼磷碳硫氮硼硫碳氯氮硼氯碳磷溴硼氧磷碳硫碳氯氟溴磷碳硫碳氯溴硼氧磷氮硫氮氯氟氮磷碳硫碳氯溴硼磷碳硼硫碳氯氮磷碳硫碳氯溴硼磷碳硼硫氮磷碳硫碳氯溴硼磷碳硼氯碳硫氮磷碳硫碳氯溴硼磷碳硼氯氮磷碳硫碳氯溴硼氧硼硫碳硼氯氮磷氮硫碳氯氟氮磷碳硫碳氯溴硼氧磷氮硫碳氯氟氮磷碳硫碳氯溴硫碳氯溴硼氧磷氮硫氮氯氟氮硫碳氯溴硼磷碳氯氮硫碳氯溴硼磷碳硼硫氮硫碳氯溴硼磷碳硫氮硫碳氯溴硼磷碳硼氯氮硫碳氯溴硼磷碳氧硫氮氯氟氮硫碳氯溴硼磷氮硫碳氯溴硼硫碳硼氯碳磷氮磷碳硫碳氯溴硼硫碳硼氯氮磷碳硫碳氯溴硼氧硼磷碳硼氯氮磷碳氯氮硫氟氮磷碳硫碳氯溴硼氧磷碳氯氮硫氟氮磷碳硫碳氯溴硼氧硼磷碳硼硫氮磷碳硫氮氯氟氮磷碳硫碳氯溴硼氧磷碳硫氮氯氟氮磷碳硫碳氯溴硼氧硼磷碳硼硫氮磷碳硫氮氯氟氮硼磷碳硼硫碳氯氮磷碳硫碳氯溴硼氧氧磷氮硫氟碳氯氮磷碳硫氟氮磷碳硫碳氯溴硼硫碳硼氯碳磷氮硫碳氯溴硼硫碳硼氯氮硫碳氯溴硼磷碳氯氮硼硫碳硼氯碳磷氮硫碳氯溴硼氧磷碳氯氮硫氟氮硫碳氯溴硼磷碳硫氮硼硫碳硼氯碳磷氮硫碳氯溴硼氧磷碳硫氮氯氟氮硫碳氯溴硼磷碳氧硫氮氯氟氮硼硫碳硼氯碳磷氮硫碳氯溴硼磷氮硼硫碳硼氯氮硫碳氯溴磷碳氯溴硼氧磷氮硫氮氯氟氮磷碳氯溴硼硫碳氯氮磷碳氯溴硼磷碳硼硫氮磷碳氯溴硼磷碳硼氯碳硫氮磷碳氯溴硼磷碳硼氯氮磷碳氯溴硼磷碳硼氯碳硫氮硼硫碳氯氮磷碳氯溴硼氧磷氮硫碳氯氟氮磷碳氯溴氧磷氮硫氟碳氯溴硼氧磷氮硫氮氯氟氮氧磷氮硫氟碳氯溴氯溴硼磷碳硼硫氮氯溴硼磷碳硫氮磷碳氯溴硼氧硼硫碳氯氮磷氟氮磷碳氯溴硼磷碳硫氮氯溴硼磷氮氯溴硼硫碳磷氮磷碳氯溴硼硫碳硼氯氮磷碳氯溴硼硫碳氧磷氮氯氟氮磷碳氯溴硼硫氮磷碳氯溴硼磷碳硼氯碳硫氮硼硫碳磷氮磷碳氯溴硼氧磷碳硫氮氯氟氮磷碳氯溴硼磷碳硼氯碳硫氮硼硫碳氧磷氮氯氟氮磷碳氯溴硼磷碳硼氯氮硼硫氮磷碳氯溴硼硫碳磷氮硫碳氯溴硼氧硼磷碳氯氮硫氟氮硫碳氯溴硼硫碳磷氮氯溴硼硫氮氯溴硼磷碳硫氮硼硫碳磷氮磷碳氯溴硼磷碳硼氯氮硼硫碳磷氮硫碳氯溴硼磷碳硫氮硼硫碳磷氮氯溴硼磷氮硼硫氮氯溴磷碳硫溴硼氧磷氮硫氮氯氟氮磷碳硫溴硼磷碳硼硫碳氯氮磷碳硫溴硼磷碳硼硫氮磷碳硫溴硼氯碳硫氮磷碳硫溴硼磷碳硼氯氮磷碳硫溴硼磷碳硼硫碳氯氮硼氯碳硫氮磷碳硫溴硼氧磷氮硫碳氯氟氮磷碳硫溴氧磷氮氯氟碳硫溴硼氧磷氮硫氮氯氟氮氧磷氮氯氟碳硫溴硼磷碳氯氮磷碳硫溴硼氧硼氯碳硫氮磷氟氮磷碳硫溴硫溴硼磷碳硼氯氮硫溴硼磷碳氯氮硫溴硼磷氮硫溴硼氯碳磷氮磷碳硫溴硼硫碳硼氯氮磷碳硫溴硼磷碳硼硫碳氯氮硼氯碳磷氮磷碳硫溴硼氧磷碳氯氮硫氟氮磷碳硫溴硼氯碳氧磷氮硫氟氮磷碳硫溴硼氯氮磷碳硫溴硼磷碳硼硫碳氯氮硼氯碳氧磷氮硫氟氮磷碳硫溴硼磷碳硼硫氮硼氯氮磷碳硫溴硼氯碳磷氮硫碳氯溴硼氧硼磷碳硫氮氯氟氮硫碳氯溴硼磷碳氯氮硼氯碳磷氮磷碳硫溴硼磷碳硼硫氮硼氯碳磷氮硫碳氯溴硼氯碳磷氮硫溴硼氯氮硫溴硼磷碳氯氮硼氯碳磷氮硫溴硼磷氮硼氯氮硫溴氧硫氮氯氟碳磷溴硼氧磷氮硫氮氯氟氮氧硫氮氯氟碳磷溴硼硫碳氯氮磷碳硫溴硼氧硼氯碳磷氮硫氟氮磷碳硫溴硼氯碳硫氮磷碳氯溴硼氧硼硫碳磷氮氯氟氮磷碳氯溴硼硫碳氯氮硼氯碳硫氮磷碳硫溴硼磷碳硼硫氮硼氯碳硫氮磷碳氯溴氧磷氮硫氟碳氯氮磷碳硫溴硼氧磷氮硫氮氯氟氮氧磷氮硫氟碳氯氮磷碳硫溴磷碳硫氮氯溴硼磷碳硼硫氮磷碳硫氮氯溴磷碳氯氮硫溴硼磷碳硼氯氮磷碳氯氮硫溴硫氮氯溴硼磷氮硫氮氯溴磷溴硼硫碳硼氯氮磷溴硼硫碳氯氮磷溴硼硫氮磷溴硼氯碳硫氮磷溴硼氯氮磷溴硼硫碳氯氮硼氯碳硫氮磷溴硼硫氮硼氯氮磷溴磷氮硫碳氯溴硼硫碳硼氯氮磷氮硫碳氯溴磷氮氯溴硼硫氮磷氮氯溴磷氮硫溴硼氯氮磷氮硫溴磷氮硫氮氯溴硼磷氮磷".split('溴') d1, d2 = "硼碳氮氧氟磷硫氯", "!&|()xyz" for i in range(int(input())): s = dat[eval("0b" + ''.join(list(reversed(input()))))] for i in range(8): s = s.replace(d1[i], d2[i]) print(s) ```
101,752
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Submitted Solution: ``` ans = {'01100000': '!x&!y&z&(y|z)', '01110101': '!x&y|z', '11111011': '!x&z|y', '00010101': '(x|y)&z', '10111000': '!x&y&!z&!y', '01111011': '!x&z|!z&x|y', '01100001': '!x&!y&z&(y|z)|x&y&z', '10001001': '!y&!z|x&y&z', '10101001': '!x&y&!z|x&y&z', '10111011': '!z|y', '10111111': '!z|x|y', '11110000': '!x', '01101010': '!(x|y)&z&(x|y|z)', '00000101': 'x&z', '01010001': '!x&!y&z', '11011000': '!x&z&!y&!z', '11100111': '!x&!y&!y&z|x&z', '11101010': '!(x|y)&z', '11101111': '!y&z|x', '01000000': '!x&!y&z', '00100011': '!z&!x&y', '11001000': '!x&z&!y', '00100111': '!z&y|x&z', '01010011': '!x&z|x&y', '01110100': '!x&y|!y&z', '00100100': '!x&!z&y|!y&x&z', '10111010': '!x&y|!z', '10110001': '!x&!z|y&z', '10100000': '!x&!z', '00010001': 'y&z', '11010000': '!x&!y&!z', '11010010': '!x&!y&!z|!z&x&y', '01001100': '!y&(x|z)', '01100101': '!x&!z&y|!y&!x&z', '00110101': '!x&y|x&z', '10001000': '!y&!z', '10001010': '!y&!x&!z', '11000110': '!x&!z&!y|!z&x&y', '01101110': '!y&z&(x|y|z)', '00111100': '!x&y|!y&x', '01010101': 'z', '10100100': '!x&!z|!y&x&z', '01110011': '!x&z|y', '00011110': '!x&y&z|!y&z&x', '11101101': '!(x|z)&y|x&z', '00101000': '!x&y&!z&(x|y)', '11011010': '!x&!y&!z|!z&x', '00011101': '!y&x|y&z', '11101110': '!y&z', '11000001': '!x&!y|x&y&z', '10011001': '!y&!z|y&z', '01001110': '!y&z|!z&x', '10000001': '!(x|y|z)|x&y&z', '10110011': '!x&!z|y', '10101111': '!z|x', '00111110': '!x&y|!y&z&x', '01000001': '!x&!y&!y&!x&z', '11110011': '!x|y', '00110000': '!x&y', '10010100': '!(!x&z|!z&x|y)|!x&y&z', '00110110': '!x&z&y|!y&x&z', '01011111': 'x|z', '00011010': '!x&y&z|!z&x', '10010000': '!(!y&z|!z&y|x)', '01001111': '!y&z|x', '01100100': '!x&!z&y|!y&z', '00000001': 'x&y&z', '10100110': '!x&!y&!z|!y&x&z', '00000111': '(y|z)&x', '10011100': '!x&y&z|!y&!z&!x', '10000101': '!(x|y|z)|x&z', '11111010': '!x&z', '10010001': '!(x|y|z)|y&z', '10001011': '!y&!z|x&y', '00100101': '!x&!z&y|x&z', '11100100': '!x&!z&!y&z', '11000010': '!x&!y|!z&x&y', '11010001': '!x&!y|y&z', '01000110': '!y&z|!z&x&y', '11001111': '!y|x', '11100010': '!x&!y&!y&z', '10010010': '!(!x&y|!y&x|z)|!x&y&z', '11011011': '!x&!y|!z&x|y&z', '01011010': '!x&z|!z&x', '11000111': '!x&!z&!y|x&y', '10110100': '!x&!z&!y|!y&x&z', '00110010': '!x&z&y', '00011111': 'x|y&z', '01001101': '!y&!x&z|!y&x', '11111110': '!x&y&z', '10100010': '!x&!y&!z', '10011111': '!y&!z|x|y&z', '00100010': '!z&y', '00111010': '!x&y|!z&x', '00110011': 'y', '11100011': '!x&!y&z|x&y', '01001000': '!x&z&!y&(x|z)', '01011001': '!x&!y&z|!y&!z&x', '11110110': '!x|!y&z|!z&y', '01110001': '!x&!y&z|!x&y', '11010100': '!x&!y|!x&y&z', '00111001': '!x&!z&y|!y&!z&x', '10100001': '!x&!z|x&y&z', '10101101': '!x&y&!z|x&z', '00000100': '!y&x&z', '10110111': '!x&!z|x&z|y', '01100010': '!x&!y&z|!z&y', '00101010': '!z&(x|y)', '11110100': '!x|!y&z', '11111101': '!x&y|z', '01011011': '!x&!y&z|!z&x', '01011110': '!x&y&z|!z&x', '10001110': '!y&!z|!y&z&x', '01100011': '!x&!y&z|!z&!x&y', '11111111': '!x|x', '00010000': '!x&y&z', '11000100': '!x&!z&!y', '01001010': '!x&!y&z|!z&x', '11111001': '!(y|z)&x|y&z', '11101100': '!(x|z)&y', '01000011': '!x&!y&z|x&y', '00010111': '(x|y)&z|x&y', '00001000': '!y&!z&x', '10110101': '!x&!z&!y|x&z', '01001011': '!x&!y&z|!z&!y&x', '10110110': '!x&!z|!x&z&y|!y&x&z', '11001011': '!x&z&!y|x&y', '01111100': '!x&y&(x|y|z)', '00101111': '!z&y|x', '10111001': '!x&y&!z|y&z', '11001100': '!y', '10111100': '!x&!z&!y|!y&x', '10000110': '!(!x&y|!y&x|z)|!y&x&z', '10101000': '!x&y&!z', '11001010': '!x&!y|!z&x', '11011111': '!y|x|z', '00000110': '!y&z&(y|z)&x', '00111101': '!x&!z&y|!y&x', '01011101': '!y&x|z', '11010011': '!x&!y&!z|x&y', '01101100': '!(x|z)&y&(x|y|z)', '00001011': '!z&!y&x', '01101101': '!(x|z)&y&(x|y|z)|x&z', '11100000': '!x&!y&z', '01010010': '!x&z|!z&x&y', '10000100': '!(!x&z|!z&x|y)', '11010101': '!x&!y|z', '00000011': 'x&y', '10000011': '!(x|y|z)|x&y', '01110000': '!x&(y|z)', '00000010': '!z&x&y', '00110111': 'x&z|y', '00101011': '!z&!x&y|!z&x', '11110001': '!x|y&z', '01001001': '!x&z&!y&(x|z)|x&y&z', '11111100': '!x&y', '00111000': '!x&y|!y&!z&x', '11011100': '!x&z|!y', '10010111': '!(x|y|z)|(x|y)&z|x&y', '00001111': 'x', '11010111': '!x&!y|x&y|z', '11011101': '!y|z', '00010010': '!x&z&(x|z)&y', '01101000': '!(x|y)&z&!x&y&(x|y|z)', '11101000': '!(x|y)&z&!x&y', '10000000': '!(x|y|z)', '01110110': '!x&y&z|!z&y', '00010011': '(x|z)&y', '00101001': '!x&y&!z&(x|y)|x&y&z', '01000111': '!y&z|x&y', '01000100': '!y&z', '01111110': '!x&y&z&(x|y|z)', '11011110': '!x&z|!y|!z&x', '01100110': '!y&z|!z&y', '00010110': '!x&y&(x|y)&z|!z&x&y', '10100111': '!x&!y&!z|x&z', '10101011': '!z|x&y', '00101110': '!y&x|!z&y', '10101100': '!x&!z|!y&x', '01010000': '!x&z', '00001100': '!y&x', '00001101': '!y&!z&x', '00001001': '!y&!z&!z&!y&x', '11001001': '!x&z&!y|x&y&z', '10100101': '!x&!z|x&z', '10110000': '!x&!z&!y', '00001110': '!y&z&x', '00011000': '!x&y&z|!y&!z&x', '10010011': '!(x|y|z)|(x|z)&y', '10001101': '!y&!z|x&z', '01111000': '!(y|z)&x&(x|y|z)', '01010111': 'x&y|z', '10101010': '!z', '00111011': '!z&x|y', '11000011': '!x&!y|x&y', '10011110': '!x&y&z|!y&!z|!y&z&x', '11001101': '!y|x&z', '00111111': 'x|y', '01100111': '!y&!x&z|!z&y', '00110001': '!x&!z&y', '00100001': '!x&!z&!z&!x&y', '10001111': '!y&!z|x', '00101101': '!x&!z&y|!y&!z&x', '10011011': '!y&!x&!z|y&z', '00100000': '!x&!z&y', '10000111': '!(x|y|z)|(y|z)&x', '01011100': '!x&z|!y&x', '10011010': '!x&y&z|!y&!x&!z', '01110010': '!x&z|!z&y', '10010110': '!(!x&y|!y&x|z)|!x&y&(x|y)&z', '01111111': 'x|y|z', '11011001': '!x&z&!y|y&z', '11110111': '!x|y|z', '00100110': '!y&x&z|!z&y', '00011001': '!y&!z&x|y&z', '10010101': '!(x|y|z)|(x|y)&z', '01000101': '!y&!x&z', '10001100': '!y&!z&!x', '01101011': '!(x|y)&z&(x|y|z)|x&y', '01101001': '!(x|y)&!x&y&z&(!x&y|!y&x|z)', '10011000': '!x&y&z|!y&!z', '11100001': '!x&!y&z|x&y&z', '10101110': '!y&x|!z', '00110100': '!x&y|!y&x&z', '10000010': '!(!x&y|!y&x|z)', '10111110': '!x&y|!y&x|!z', '11111000': '!(y|z)&x', '01000010': '!x&!y&z|!z&x&y', '01111001': '!(y|z)&x&(x|y|z)|y&z', '10111101': '!x&!z|!y&x|y&z', '11010110': '!x&!y|!x&y&z|!z&x&y', '01111010': '!x&z&(x|y|z)', '11000000': '!x&!y', '00000000': '!x&x', '00101100': '!x&!z&y|!y&x', '11101001': '!(x|y)&z&!x&y|x&y&z', '11000101': '!x&!y|x&z', '11110101': '!x|z', '01010100': '!x&y&z', '10110010': '!x&!z|!x&z&y', '11001110': '!y|!z&x', '00011100': '!x&y&z|!y&x', '11101011': '!(x|y)&z|x&y', '10100011': '!x&!z|x&y', '01101111': '!y&z|!z&y|x', '00011011': '!z&x|y&z', '01111101': '!x&y|!y&x|z', '00001010': '!z&x', '11100110': '!x&!y&!z&!y&z', '10011101': '!y&!z&!x|y&z', '11110010': '!x|!z&y', '01010110': '!x&y&z|!z&x&y', '01011000': '!x&z|!y&!z&x', '11100101': '!x&!y&z|x&z', '00010100': '!x&y&(x|y)&z', '01110111': 'y|z'} n=int(input()) for i in range(n): print(ans[input()]) ``` No
101,753
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Submitted Solution: ``` s = '''00000000 !x&x 00000001 x&y&z 00000010 !x&y&z 00000011 y&z 00000100 !y&x&z 00000101 x&z 00000110 !x&y|!y&x&z 00000111 (x|y)&z 00001000 !x&!y&z 00001001 !x&!y|x&y&z 00001010 !x&z 00001011 !x&z|y&z 00001100 !y&z 00001101 !y&z|x&z 00001110 !(!z|x&y) 00001111 z 00010000 !z&x&y 00010001 x&y 00010010 !x&z|!z&x&y 00010011 (x|z)&y 00010100 !y&z|!z&y&x 00010101 (y|z)&x 00010110 !x&y&z|!y&z|!z&y&x 00010111 (x|y)&x&y|z 00011000 !x&!y&z|!z&x&y 00011001 !x&!y&z|x&y 00011010 !x&z|!z&x&y 00011011 !x&z|x&y 00011100 !y&z|!z&x&y 00011101 !y&z|x&y 00011110 !(x&y&z)&x&y|z 00011111 x&y|z 00100000 !x&!z&y 00100001 !x&!z|x&z&y 00100010 !x&y 00100011 !x&y|y&z 00100100 !x&!z&y|!y&x&z 00100101 !x&!z&y|x&z 00100110 !x&y|!y&x&z 00100111 !x&y|x&z 00101000 !x&!y&z|!z&y 00101001 !x&!y&z|!z&y|x&y&z 00101010 !x&(y|z) 00101011 !x&(y|z)|y&z 00101100 !x&!z&y|!y&z 00101101 !x&!y&z|!z&y|x&z 00101110 !x&y|!y&z 00101111 !x&y|z 00110000 !z&y 00110001 !z&y|x&y 00110010 !(!y|x&z) 00110011 y 00110100 !y&x&z|!z&y 00110101 !z&y|x&z 00110110 !(x&y&z)&x&z|y 00110111 x&z|y 00111000 !x&!y&z|!z&y 00111001 !x&!y&z|!z&y|x&y 00111010 !x&z|!z&y 00111011 !x&z|y 00111100 !y&z|!z&y 00111101 !y&z|!z&y|x&y 00111110 !(!y&!z|x&y&z) 00111111 y|z 01000000 !y&!z&x 01000001 !y&!z|y&z&x 01000010 !x&y&z|!y&!z&x 01000011 !y&!z&x|y&z 01000100 !y&x 01000101 !y&x|x&z 01000110 !x&y&z|!y&x 01000111 !y&x|y&z 01001000 !x&z|!z&x&!y 01001001 !x&z|!z&x&!y|x&y&z 01001010 !x&z|!y&!z&x 01001011 !x&z|!y&!z&x|y&z 01001100 !y&(x|z) 01001101 !y&(x|z)|x&z 01001110 !x&z|!y&x 01001111 !y&x|z 01010000 !z&x 01010001 !z&x|x&y 01010010 !x&y&z|!z&x 01010011 !z&x|y&z 01010100 !(!x|y&z) 01010101 x 01010110 x|y&z&!(x&y&z) 01010111 x|y&z 01011000 !x&!y&z|!z&x 01011001 !x&!y&z|!z&x|x&y 01011010 !x&z|!z&x 01011011 !x&z|!z&x|x&y 01011100 !y&z|!z&x 01011101 !y&z|x 01011110 !(!x&!z|x&y&z) 01011111 x|z 01100000 !x&y|!y&x&!z 01100001 !x&y|!y&x&!z|x&y&z 01100010 !x&y|!y&!z&x 01100011 !x&y|!y&!z&x|y&z 01100100 !x&!z&y|!y&x 01100101 !x&!z&y|!y&x|x&z 01100110 !x&y|!y&x 01100111 !x&y|!y&x|x&z 01101000 !x&!y&z|!x&y|!y&x&!z 01101001 !x&!y&z|!z&y|!y&!z|y&z&x 01101010 !x&(y|z)|!y&!z&x 01101011 !x&(y|z)|!y&!z&x|y&z 01101100 !x&!z&y|!y&(x|z) 01101101 !x&!z&y|!y&(x|z)|x&z 01101110 !x&(y|z)|!y&x 01101111 !x&y|!y&x|z 01110000 !z&(x|y) 01110001 !z&(x|y)|x&y 01110010 !x&y|!z&x 01110011 !z&x|y 01110100 !y&x|!z&y 01110101 !z&y|x 01110110 !(!x&!y|x&y&z) 01110111 x|y 01111000 !x&!y&z|!z&(x|y) 01111001 !x&!y&z|!z&(x|y)|x&y 01111010 !x&(y|z)|!z&x 01111011 !x&z|!z&x|y 01111100 !y&(x|z)|!z&y 01111101 !y&z|!z&y|x 01111110 !x&y|!y&z|!z&x 01111111 x|y|z 10000000 !(x|y|z) 10000001 !(x|y|z)|x&y&z 10000010 !x&!y&!z|y&z 10000011 !(x|y|z)|y&z 10000100 !x&!z|x&z&!y 10000101 !(x|y|z)|x&z 10000110 !x&!y&!z|y&z|!y&x&z 10000111 !(x|y|z)|(x|y)&z 10001000 !x&!y 10001001 !x&!y|x&y&z 10001010 !(!z&y|x) 10001011 !x&!y|y&z 10001100 !(!z&x|y) 10001101 !x&!y|x&z 10001110 !(!z&x|y)|!x&z 10001111 !x&!y|z 10010000 !x&!y|x&y&!z 10010001 !(x|y|z)|x&y 10010010 !x&!y&!z|y&z|!z&x&y 10010011 !(x|y|z)|(x|z)&y 10010100 !x&!y|x&y&!z|!y&x&z 10010101 !(x|y|z)|(y|z)&x 10010110 !x&!y&!z|y&z|!y&z|!z&y&x 10010111 !(x|y|z)|(x|y)&x&y|z 10011000 !x&!y|!z&x&y 10011001 !x&!y|x&y 10011010 !(!z&y|x)|!z&x&y 10011011 !(!z&y|x)|x&y 10011100 !(!z&x|y)|!z&x&y 10011101 !(!z&x|y)|x&y 10011110 !(x&y&z)&!x&!y|x&y|z 10011111 !x&!y|x&y|z 10100000 !x&!z 10100001 !x&!z|x&y&z 10100010 !(!y&z|x) 10100011 !x&!z|y&z 10100100 !x&!z|!y&x&z 10100101 !x&!z|x&z 10100110 !(!y&z|x)|!y&x&z 10100111 !(!y&z|x)|x&z 10101000 !(x|y&z) 10101001 !(x|y&z)|x&y&z 10101010 !x 10101011 !x|y&z 10101100 !x&!z|!y&z 10101101 !(x|y&z)|x&z 10101110 !x|!y&z 10101111 !x|z 10110000 !(!y&x|z) 10110001 !x&!z|x&y 10110010 !(!y&x|z)|!x&y 10110011 !x&!z|y 10110100 !(!y&x|z)|!y&x&z 10110101 !(!y&x|z)|x&z 10110110 !(x&y&z)&!x&!z|x&z|y 10110111 !x&!z|x&z|y 10111000 !x&!y|!z&y 10111001 !(x|y&z)|x&y 10111010 !x|!z&y 10111011 !x|y 10111100 !(!y&!z&x|y&z) 10111101 !x&!y|!z&y|x&z 10111110 !x|!y&z|!z&y 10111111 !x|y|z 11000000 !y&!z 11000001 !y&!z|x&y&z 11000010 !x&y&z|!y&!z 11000011 !y&!z|y&z 11000100 !(!x&z|y) 11000101 !y&!z|x&z 11000110 !(!x&z|y)|!x&y&z 11000111 !(!x&z|y)|y&z 11001000 !(x&z|y) 11001001 !(x&z|y)|x&y&z 11001010 !x&z|!y&!z 11001011 !(x&z|y)|y&z 11001100 !y 11001101 !y|x&z 11001110 !x&z|!y 11001111 !y|z 11010000 !(!x&y|z) 11010001 !y&!z|x&y 11010010 !(!x&y|z)|!x&y&z 11010011 !(!x&y|z)|y&z 11010100 !(!x&y|z)|!y&x 11010101 !y&!z|x 11010110 !(x&y&z)&!y&!z|x|y&z 11010111 !y&!z|x|y&z 11011000 !x&!y|!z&x 11011001 !(x&z|y)|x&y 11011010 !(!x&!z&y|x&z) 11011011 !x&!y|!z&x|y&z 11011100 !y|!z&x 11011101 !y|x 11011110 !x&z|!y|!z&x 11011111 !y|x|z 11100000 !(x&y|z) 11100001 !(x&y|z)|x&y&z 11100010 !x&y|!y&!z 11100011 !(x&y|z)|y&z 11100100 !x&!z|!y&x 11100101 !(x&y|z)|x&z 11100110 !(!x&!y&z|x&y) 11100111 !x&!z|!y&x|y&z 11101000 !((x|y)&x&y|z) 11101001 !((x|y)&x&y|z)|x&y&z 11101010 !x|!y&!z 11101011 !x|!y&!z|y&z 11101100 !x&!z|!y 11101101 !x&!z|!y|x&z 11101110 !x|!y 11101111 !x|!y|z 11110000 !z 11110001 !z|x&y 11110010 !x&y|!z 11110011 !z|y 11110100 !y&x|!z 11110101 !z|x 11110110 !x&y|!y&x|!z 11110111 !z|x|y 11111000 !x&!y|!z 11111001 !x&!y|!z|x&y 11111010 !x|!z 11111011 !x|!z|y 11111100 !y|!z 11111101 !y|!z|x 11111110 !(x&y&z) 11111111 !x|x''' def vim(s): rez = '' for c in s: if c == 'x': rez += 'z' elif c == 'z': rez += 'x' else: rez += c return rez l = s.split('\n') _d = dict() for p in l: _d[p.split()[0]] = p.split()[1] n = int(input()) for i in range(n): s = input().strip() print(vim(_d[s])) ``` No
101,754
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Submitted Solution: ``` base = [ "x", "(not x)", "y", "(not y)", "z", "(not z)", ] expr = ["x", "(not x)", "y", "(not y)", "z", "(not z)"] for x in base: for y in base: if x == y: continue for z in base: if y == z: continue expr.append(x + "|" + y) expr.append(x + "&" + y) expr.append(x + "|" + y + "|" + z) expr.append(x + "|" + "(" + y + "|" + z + ")") expr.append(x + "&" + y + "|" + z) expr.append(x + "&" + "(" + y + "|" + z + ")") expr.append(x + "|" + y + "&" + z) expr.append("(" + x + "|" + y + ")" + "&" + z) expr.append(x + "&" + y + "&" + z) expr.append(x + "&" + "(" + y + "&" + z + ")") n = int(input()) for i in range(n): s = input() resp = "zzzzzzzzzzzzzzzzzz" for exp in expr: x = 0; y = 0; z = 0 if int(s[0]) != eval(exp): continue x = 0; y = 0; z = 1 if int(s[1]) != eval(exp): continue x = 0; y = 1; z = 0 if int(s[2]) != eval(exp): continue x = 0; y = 1; z = 1 if int(s[3]) != eval(exp): continue x = 1; y = 0; z = 0 if int(s[4]) != eval(exp): continue x = 1; y = 0; z = 1 if int(s[5]) != eval(exp): continue x = 1; y = 1; z = 0 if int(s[6]) != eval(exp): continue x = 1; y = 1; z = 1 if int(s[7]) != eval(exp): continue if (len(exp) < len(resp)): resp = exp elif (len(exp) < len(resp) and exp < resp): resp = exp i = resp.find("(not ") while i != -1: resp = resp[0:i] + "!" + resp[i+5] + resp[i+7:] i = resp.find("(not ") print(resp) ``` No
101,755
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: * Operation AND ('&', ASCII code 38) * Operation OR ('|', ASCII code 124) * Operation NOT ('!', ASCII code 33) * Variables x, y and z (ASCII codes 120-122) * Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' Input The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>. Output You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. Example Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&amp;x !x x|y&amp;z Note The truth table for the second function: <image> Submitted Solution: ``` f = ['!x&x', '!(x|y|z)', '!x&!y&z', '!x&!y', '!x&!z&y', '!x&!z', '!(!y&!z|x|y&z)', '!(x|y&z)', '!x&y&z', '!(!y&z|!z&y|x)', '!x&z', '!(!z&y|x)', '!x&y', '!(!y&z|x)', '!x&(y|z)', '!x', '!y&!z&x', '!y&!z', '!(!x&!z|x&z|y)', '!(x&z|y)', '!(!x&!y|x&y|z)', '!(x&y|z)', '!(!x&!y|x&y|z)|!x&!y&z', '!((x|y)&z|x&y)', '!x&y&z|!y&!z&x', '!x&y&z|!y&!z', '!x&z|!y&!z&x', '!x&z|!y&!z', '!x&y|!y&!z&x', '!x&y|!y&!z', '!x&(y|z)|!y&!z&x', '!x|!y&!z', '!y&x&z', '!(!x&z|!z&x|y)', '!y&z', '!(!z&x|y)', '!x&!z&y|!y&x&z', '!x&!z|!y&x&z', '!x&!z&y|!y&z', '!x&!z|!y&z', '!x&y&z|!y&x&z', '!(!x&z|!z&x|y)|!x&y&z', '!(!z|x&y)', '!(!z&x|y)|!x&z', '!x&y|!y&x&z', '!(!y&z|x)|!y&x&z', '!x&y|!y&z', '!x|!y&z', '!y&x', '!(!x&z|y)', '!y&(x|z)', '!y', '!x&!z&y|!y&x', '!x&!z|!y&x', '!x&!z&y|!y&(x|z)', '!x&!z|!y', '!x&y&z|!y&x', '!(!x&z|y)|!x&y&z', '!x&z|!y&x', '!x&z|!y', '!x&y|!y&x', '!(!x&!y&z|x&y)', '!x&(y|z)|!y&x', '!x|!y', '!z&x&y', '!(!x&y|!y&x|z)', '!x&!y&z|!z&x&y', '!x&!y|!z&x&y', '!z&y', '!(!y&x|z)', '!x&!y&z|!z&y', '!x&!y|!z&y', '!x&y&z|!z&x&y', '!(!x&y|!y&x|z)|!x&y&z', '!x&z|!z&x&y', '!(!z&y|x)|!z&x&y', '!(!y|x&z)', '!(!y&x|z)|!x&y', '!x&z|!z&y', '!x|!z&y', '!z&x', '!(!x&y|z)', '!x&!y&z|!z&x', '!x&!y|!z&x', '!z&(x|y)', '!z', '!x&!y&z|!z&(x|y)', '!x&!y|!z', '!x&y&z|!z&x', '!(!x&y|z)|!x&y&z', '!x&z|!z&x', '!(!x&!z&y|x&z)', '!x&y|!z&x', '!x&y|!z', '!x&(y|z)|!z&x', '!x|!z', '!y&x&z|!z&x&y', '!(!x&y|!y&x|z)|!y&x&z', '!y&z|!z&x&y', '!(!z&x|y)|!z&x&y', '!y&x&z|!z&y', '!(!y&x|z)|!y&x&z', '!y&z|!z&y', '!(!y&!z&x|y&z)', '!x&y&z|!y&x&z|!z&x&y', '!(!x&y|!y&x|z)|!x&y&z|!y&x&z', '!(!z|x&y)|!z&x&y', '!(!z&x|y)|!x&z|!z&x&y', '!(!y|x&z)|!y&x&z', '!(!y&x|z)|!x&y|!y&x&z', '!(!y&!z|x&y&z)', '!x|!y&z|!z&y', '!(!x|y&z)', '!(!x&y|z)|!y&x', '!y&z|!z&x', '!y|!z&x', '!y&x|!z&y', '!y&x|!z', '!y&(x|z)|!z&y', '!y|!z', '!(!x|y&z)|!x&y&z', '!(!x&y|z)|!x&y&z|!y&x', '!(!x&!z|x&y&z)', '!x&z|!y|!z&x', '!(!x&!y|x&y&z)', '!x&y|!y&x|!z', '!x&y|!y&z|!z&x', '!(x&y&z)', 'x&y&z', '!(x|y|z)|x&y&z', '!x&!y&z|x&y&z', '!x&!y|x&y&z', '!x&!z&y|x&y&z', '!x&!z|x&y&z', '!(!y&!z|x|y&z)|x&y&z', '!(x|y&z)|x&y&z', 'y&z', '!(x|y|z)|y&z', '!x&z|y&z', '!x&!y|y&z', '!x&y|y&z', '!x&!z|y&z', '!x&(y|z)|y&z', '!x|y&z', '!y&!z&x|x&y&z', '!y&!z|x&y&z', '!(!x&!z|x&z|y)|x&y&z', '!(x&z|y)|x&y&z', '!(!x&!y|x&y|z)|x&y&z', '!(x&y|z)|x&y&z', '!(!x&!y|x&y|z)|!x&!y&z|x&y&z', '!((x|y)&z|x&y)|x&y&z', '!y&!z&x|y&z', '!y&!z|y&z', '!x&z|!y&!z&x|y&z', '!(x&z|y)|y&z', '!x&y|!y&!z&x|y&z', '!(x&y|z)|y&z', '!x&(y|z)|!y&!z&x|y&z', '!x|!y&!z|y&z', 'x&z', '!(x|y|z)|x&z', '!y&z|x&z', '!x&!y|x&z', '!x&!z&y|x&z', '!x&!z|x&z', '!x&!z&y|!y&z|x&z', '!(x|y&z)|x&z', '(x|y)&z', '!(x|y|z)|(x|y)&z', 'z', '!x&!y|z', '!x&y|x&z', '!(!y&z|x)|x&z', '!x&y|z', '!x|z', '!y&x|x&z', '!y&!z|x&z', '!y&(x|z)|x&z', '!y|x&z', '!x&!z&y|!y&x|x&z', '!(x&y|z)|x&z', '!x&!z&y|!y&(x|z)|x&z', '!x&!z|!y|x&z', '!y&x|y&z', '!(!x&z|y)|y&z', '!y&x|z', '!y|z', '!x&y|!y&x|x&z', '!x&!z|!y&x|y&z', '!x&y|!y&x|z', '!x|!y|z', 'x&y', '!(x|y|z)|x&y', '!x&!y&z|x&y', '!x&!y|x&y', '!z&y|x&y', '!x&!z|x&y', '!x&!y&z|!z&y|x&y', '!(x|y&z)|x&y', '(x|z)&y', '!(x|y|z)|(x|z)&y', '!x&z|x&y', '!(!z&y|x)|x&y', 'y', '!x&!z|y', '!x&z|y', '!x|y', '!z&x|x&y', '!y&!z|x&y', '!x&!y&z|!z&x|x&y', '!(x&z|y)|x&y', '!z&(x|y)|x&y', '!z|x&y', '!x&!y&z|!z&(x|y)|x&y', '!x&!y|!z|x&y', '!z&x|y&z', '!(!x&y|z)|y&z', '!x&z|!z&x|x&y', '!x&!y|!z&x|y&z', '!z&x|y', '!z|y', '!x&z|!z&x|y', '!x|!z|y', '(y|z)&x', '!(x|y|z)|(y|z)&x', '!y&z|x&y', '!(!z&x|y)|x&y', '!z&y|x&z', '!(!y&x|z)|x&z', '!y&z|!z&y|x&y', '!x&!y|!z&y|x&z', '(x|y)&z|x&y', '!(x|y|z)|(x|y)&z|x&y', 'x&y|z', '!x&!y|x&y|z', 'x&z|y', '!x&!z|x&z|y', 'y|z', '!x|y|z', 'x', '!y&!z|x', '!y&z|x', '!y|x', '!z&y|x', '!z|x', '!y&z|!z&y|x', '!y|!z|x', 'x|y&z', '!y&!z|x|y&z', 'x|z', '!y|x|z', 'x|y', '!z|x|y', 'x|y|z', '!x|x'] n = int(input()) for i in range(n): s = input() a = 0 for j in range(8): a += int(s[j] == '1') << j print(f[a]) ``` No
101,756
Provide tags and a correct Python 3 solution for this coding contest problem. Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression. An Ahmes arithmetic expression can be defined as: * "d" is an Ahmes arithmetic expression, where d is a one-digit positive integer; * "(E1 op E2)" is an Ahmes arithmetic expression, where E1 and E2 are valid Ahmes arithmetic expressions (without spaces) and op is either plus ( + ) or minus ( - ). For example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions. On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task: Given the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators. Input The first line contains a string E (1 ≤ |E| ≤ 104) — a valid Ahmes arithmetic expression. All operators are erased and replaced with '?'. The second line contains two space-separated integers P and M (0 ≤ min(P, M) ≤ 100) — the number of plus and minus operators, respectively. It is guaranteed that P + M = the number of erased operators. Output Print one line containing the answer to the problem. Examples Input (1?1) 1 0 Output 2 Input (2?(1?2)) 1 1 Output 1 Input ((1?(5?7))?((6?2)?7)) 3 2 Output 18 Input ((1?(5?7))?((6?2)?7)) 2 3 Output 16 Note * The first sample will be (1 + 1) = 2. * The second sample will be (2 + (1 - 2)) = 1. * The third sample will be ((1 - (5 - 7)) + ((6 + 2) + 7)) = 18. * The fourth sample will be ((1 + (5 + 7)) - ((6 - 2) - 7)) = 16. Tags: dfs and similar, dp, trees Correct Solution: ``` from math import inf class Node: def __init__(self, parent = None, leftExp = None, rightExp = None, signQ = 0): self.parent, self.leftExp, self.rightExp, self.signQ = parent, leftExp, rightExp, signQ def __str__(self): return "Node" memo = {} def Memoize(node, p, maxValue, minValue): if not node in memo: memo.update({node : {p : [maxValue, minValue]} }) else: memo[node].update({p : [maxValue, minValue]}) def ExpMaxValue(root: Node, p): m = root.signQ - p """if root.signQ == 1: if p == 1: return [root.leftExp.value + root.rightExp.value, root.leftExp.value + root.rightExp.value] else: return [root.leftExp.value - root.rightExp.value, root.leftExp.value - root.rightExp.value]""" if root.signQ == 0: return [root.value, root.value] if root in memo: if p in memo[root]: return memo[root][p] if m == 0: value = ExpMaxValue(root.leftExp, root.leftExp.signQ)[0] + ExpMaxValue(root.rightExp, root.rightExp.signQ)[0] Memoize(root, p, value, value) return [value, value] if p == 0: value = ExpMaxValue(root.leftExp, 0)[0] - ExpMaxValue(root.rightExp, 0)[0] Memoize(root, p, value, value) return [value, value] maxValue = -inf minValue = inf if m >= p: for pQMid in range(2): pQLeftMin = min(p - pQMid, root.leftExp.signQ) for pQLeft in range(pQLeftMin + 1): if root.leftExp.signQ - pQLeft + (1 - pQMid) > m: continue resLeft = ExpMaxValue(root.leftExp, pQLeft) resRight = ExpMaxValue(root.rightExp, p - pQMid - pQLeft) if pQMid == 1: maxValue = max(resLeft[0] + resRight[0], maxValue) minValue = min(resLeft[1] + resRight[1], minValue) else: maxValue = max(resLeft[0] - resRight[1], maxValue) minValue = min(resLeft[1] - resRight[0], minValue) else: for mQMid in range(2): mQLeftMin = min(m - mQMid, root.leftExp.signQ) for mQLeft in range(mQLeftMin + 1): pQLeft = root.leftExp.signQ - mQLeft if pQLeft + (1 - mQMid) > p: continue resLeft = ExpMaxValue(root.leftExp, pQLeft) resRight = ExpMaxValue(root.rightExp, p - (1 - mQMid) - pQLeft) if mQMid == 0: maxValue = max(resLeft[0] + resRight[0], maxValue) minValue = min(resLeft[1] + resRight[1], minValue) else: maxValue = max(resLeft[0] - resRight[1], maxValue) minValue = min(resLeft[1] - resRight[0], minValue) Memoize(root, p, int(maxValue), int(minValue)) return [int(maxValue), int(minValue)] def PrintNodes(root: Node): if root.signQ != 0: leftExp = root.leftExp if root.leftExp.signQ != 0 else root.leftExp.value rightExp = root.rightExp if root.rightExp.signQ != 0 else root.rightExp.value check = root.signQ == root.leftExp.signQ + root.rightExp.signQ + 1 print(root.signQ, root.parent, leftExp, rightExp, check) PrintNodes(root.leftExp) PrintNodes(root.rightExp) def main(): exp = str(input()) if len(exp) == 1: print(exp) return #root = Node(None, None, None) #root.parent = root cNode = Node() isRight = False for i in range(1, len(exp) - 1): if exp[i] == '(': if not isRight: cNode.leftExp = Node(cNode) cNode = cNode.leftExp else: cNode.rightExp = Node(cNode) cNode = cNode.rightExp isRight = False elif exp[i] == '?': isRight = True cNode.signQ += 1 elif exp[i] == ')': if cNode.parent != None: cNode.parent.signQ += cNode.signQ cNode = cNode.parent isRight = False else: if not isRight: cNode.leftExp = Node(cNode) cNode.leftExp.value = int(exp[i]) else: cNode.rightExp = Node(cNode) cNode.rightExp.value = int(exp[i]) #PrintNodes(cNode) ss = str(input()).split() p, m = int(ss[0]), int(ss[1]) print(ExpMaxValue(cNode, p)[0]) main() ```
101,757
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression. An Ahmes arithmetic expression can be defined as: * "d" is an Ahmes arithmetic expression, where d is a one-digit positive integer; * "(E1 op E2)" is an Ahmes arithmetic expression, where E1 and E2 are valid Ahmes arithmetic expressions (without spaces) and op is either plus ( + ) or minus ( - ). For example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions. On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task: Given the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators. Input The first line contains a string E (1 ≤ |E| ≤ 104) — a valid Ahmes arithmetic expression. All operators are erased and replaced with '?'. The second line contains two space-separated integers P and M (0 ≤ min(P, M) ≤ 100) — the number of plus and minus operators, respectively. It is guaranteed that P + M = the number of erased operators. Output Print one line containing the answer to the problem. Examples Input (1?1) 1 0 Output 2 Input (2?(1?2)) 1 1 Output 1 Input ((1?(5?7))?((6?2)?7)) 3 2 Output 18 Input ((1?(5?7))?((6?2)?7)) 2 3 Output 16 Note * The first sample will be (1 + 1) = 2. * The second sample will be (2 + (1 - 2)) = 1. * The third sample will be ((1 - (5 - 7)) + ((6 + 2) + 7)) = 18. * The fourth sample will be ((1 + (5 + 7)) - ((6 - 2) - 7)) = 16. Submitted Solution: ``` from math import inf class Node: def __init__(self, parent = None, leftExp = None, rightExp = None, signQ = 0): self.parent, self.leftExp, self.rightExp, self.signQ = parent, leftExp, rightExp, signQ def __str__(self): return "Node" memo = {} def Memoize(node, p, maxValue, minValue): if not node in memo: memo.update({node : {p : [maxValue, minValue]} }) else: memo[node].update({p : [maxValue, minValue]}) def ExpMaxValue(root: Node, p, m): """if root.signQ == 1: if p == 1: return [root.leftExp.value + root.rightExp.value, root.leftExp.value + root.rightExp.value] else: return [root.leftExp.value - root.rightExp.value, root.leftExp.value - root.rightExp.value]""" if root in memo: if p in memo[root]: return memo[root][p] if root.signQ == 0: return [root.value, root.value] if m == 0: value = ExpMaxValue(root.leftExp, root.leftExp.signQ, 0)[0] + ExpMaxValue(root.rightExp, root.rightExp.signQ, 0)[0] Memoize(root, p, value, value) return [value, value] if p == 0: value = ExpMaxValue(root.leftExp, 0, root.leftExp.signQ)[0] - ExpMaxValue(root.rightExp, 0, root.rightExp.signQ)[0] Memoize(root, p, value, value) return [value, value] maxValue = -inf minValue = inf if m >= p: for pQMid in range(2): pQLeftMin = min(p - pQMid, root.leftExp.signQ) for pQLeft in range(pQLeftMin + 1): mQLeft = root.leftExp.signQ - pQLeft resLeft = ExpMaxValue(root.leftExp, pQLeft, mQLeft) resRight = ExpMaxValue(root.rightExp, p - pQMid - pQLeft, m - (1 - pQMid) - mQLeft) if pQMid == 1: maxValue = max(resLeft[0] + resRight[0], maxValue) minValue = min(resLeft[1] + resRight[1], minValue) else: maxValue = max(resLeft[0] - resRight[1], maxValue) minValue = min(resLeft[1] - resRight[0], minValue) else: for mQMid in range(2): mQLeftMin = min(m - mQMid, root.leftExp.signQ) for mQLeft in range(mQLeftMin + 1): pQLeft = root.leftExp.signQ - mQLeft resLeft = ExpMaxValue(root.leftExp, pQLeft, mQLeft) resRight = ExpMaxValue(root.rightExp, p - (1 - mQMid) - pQLeft, m - mQMid - mQLeft) if mQMid == 0: maxValue = max(resLeft[0] + resRight[0], maxValue) minValue = min(resLeft[1] + resRight[1], minValue) else: maxValue = max(resLeft[0] - resRight[1], maxValue) minValue = min(resLeft[1] - resRight[0], minValue) Memoize(root, p, maxValue, minValue) return [maxValue, minValue] def PrintNodes(root: Node): if root.signQ != 0: print(root.signQ, root.parent, root.leftExp if root.leftExp.signQ != 0 else root.leftExp.value, root.rightExp if root.rightExp.signQ != 0 else root.rightExp.value) PrintNodes(root.leftExp) PrintNodes(root.rightExp) def main(): exp = str(input()) if len(exp) == 1: print(exp) return #root = Node(None, None, None) #root.parent = root cNode = Node() isRight = False for i in range(1, len(exp) - 1): if exp[i] == '(': if not isRight: cNode.leftExp = Node(cNode) cNode = cNode.leftExp else: cNode.rightExp = Node(cNode) cNode = cNode.rightExp isRight = False elif exp[i] == '?': isRight = True cNode.signQ += 1 elif exp[i] == ')': if cNode.parent != None: cNode.parent.signQ += cNode.signQ cNode = cNode.parent isRight = False else: if not isRight: cNode.leftExp = Node(cNode) cNode.leftExp.value = int(exp[i]) else: cNode.rightExp = Node(cNode) cNode.rightExp.value = int(exp[i]) #PrintNodes(cNode) ss = str(input()).split() p, m = int(ss[0]), int(ss[1]) print(ExpMaxValue(cNode, p, m)[0]) main() ``` No
101,758
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression. An Ahmes arithmetic expression can be defined as: * "d" is an Ahmes arithmetic expression, where d is a one-digit positive integer; * "(E1 op E2)" is an Ahmes arithmetic expression, where E1 and E2 are valid Ahmes arithmetic expressions (without spaces) and op is either plus ( + ) or minus ( - ). For example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions. On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task: Given the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators. Input The first line contains a string E (1 ≤ |E| ≤ 104) — a valid Ahmes arithmetic expression. All operators are erased and replaced with '?'. The second line contains two space-separated integers P and M (0 ≤ min(P, M) ≤ 100) — the number of plus and minus operators, respectively. It is guaranteed that P + M = the number of erased operators. Output Print one line containing the answer to the problem. Examples Input (1?1) 1 0 Output 2 Input (2?(1?2)) 1 1 Output 1 Input ((1?(5?7))?((6?2)?7)) 3 2 Output 18 Input ((1?(5?7))?((6?2)?7)) 2 3 Output 16 Note * The first sample will be (1 + 1) = 2. * The second sample will be (2 + (1 - 2)) = 1. * The third sample will be ((1 - (5 - 7)) + ((6 + 2) + 7)) = 18. * The fourth sample will be ((1 + (5 + 7)) - ((6 - 2) - 7)) = 16. Submitted Solution: ``` from math import inf class Node: def __init__(self, parent = None, leftExp = None, rightExp = None, signQ = 0): self.parent, self.leftExp, self.rightExp, self.signQ = parent, leftExp, rightExp, signQ def __str__(self): return "Node" memo = {} def Memoize(node, p, maxValue, minValue): if not node in memo: memo.update({node : {p : [maxValue, minValue]} }) else: memo[node].update({p : [maxValue, minValue]}) def ExpMaxValue(root: Node, p, m): """if root.signQ == 1: if p == 1: return [root.leftExp.value + root.rightExp.value, root.leftExp.value + root.rightExp.value] else: return [root.leftExp.value - root.rightExp.value, root.leftExp.value - root.rightExp.value]""" if root in memo: if p in memo[root]: return memo[root][p] if root.signQ == 0: return [root.value, root.value] if m == 0: value = ExpMaxValue(root.leftExp, root.leftExp.signQ, 0)[0] + ExpMaxValue(root.rightExp, root.rightExp.signQ, 0)[0] Memoize(root, p, value, value) return [value, value] if p == 0: value = ExpMaxValue(root.leftExp, 0, root.leftExp.signQ)[0] - ExpMaxValue(root.rightExp, 0, root.rightExp.signQ)[0] Memoize(root, p, value, value) return [value, value] maxValue = -inf minValue = inf if m >= p: for pQMid in range(2): pQLeftMin = min(p - pQMid, root.leftExp.signQ) for pQLeft in range(pQLeftMin + 1): mQLeft = root.leftExp.signQ - pQLeft resLeft = ExpMaxValue(root.leftExp, pQLeft, mQLeft) resRight = ExpMaxValue(root.rightExp, p - pQMid - pQLeft, m - (1 - pQMid) - mQLeft) if pQMid == 1: maxValue = max(resLeft[0] + resRight[0], maxValue) minValue = min(resLeft[1] + resRight[1], minValue) else: maxValue = max(resLeft[0] - resRight[1], maxValue) minValue = min(resLeft[1] - resRight[0], minValue) else: for mQMid in range(2): mQLeftMin = min(m - mQMid, root.leftExp.signQ) for mQLeft in range(mQLeftMin + 1): pQLeft = root.leftExp.signQ - mQLeft resLeft = ExpMaxValue(root.leftExp, pQLeft, mQLeft) resRight = ExpMaxValue(root.rightExp, p - (1 - mQMid) - pQLeft, m - mQMid - mQLeft) if mQMid == 0: maxValue = max(resLeft[0] + resRight[0], maxValue) minValue = min(resLeft[1] + resRight[1], minValue) else: maxValue = max(resLeft[0] - resRight[1], maxValue) minValue = min(resLeft[1] - resRight[0], minValue) Memoize(root, p, maxValue, minValue) return [maxValue, minValue] def PrintNodes(root: Node): if root.signQ != 0: print(root.signQ, root.parent, root.leftExp if root.leftExp.signQ != 0 else root.leftExp.value, root.rightExp if root.rightExp.signQ != 0 else root.rightExp.value) PrintNodes(root.leftExp) PrintNodes(root.rightExp) def main(): exp = str(input()) if len(exp) == 1: print(exp) return #root = Node(None, None, None) #root.parent = root cNode = Node() isRight = False for i in range(1, len(exp) - 1): if exp[i] == '(': if not isRight: cNode.leftExp = Node(cNode) cNode = cNode.leftExp else: cNode.rightExp = Node(cNode) cNode = cNode.rightExp isRight = False elif exp[i] == '?': isRight = True cNode.signQ += 1 elif exp[i] == ')': if cNode.parent != None: cNode.parent.signQ += cNode.signQ cNode = cNode.parent isRight = False else: if not isRight: cNode.leftExp = Node(cNode) cNode.leftExp.value = int(exp[i]) else: cNode.rightExp = Node(cNode) cNode.rightExp.value = int(exp[i]) PrintNodes(cNode) ss = str(input()).split() p, m = int(ss[0]), int(ss[1]) print(ExpMaxValue(cNode, p, m)[0]) main() ``` No
101,759
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Tags: geometry Correct Solution: ``` from collections import namedtuple from itertools import combinations Point = namedtuple('Point', ['x', 'y']) def read(): x, y = input().split() return Point(int(x), int(y)) def doubled_oriented_area(p1, p2, p3): return (p3.y - p1.y) * (p2.x - p1.x) - (p3.x - p1.x) * (p2.y - p1.y) def filter_points(p1, p2, points): res = [] for p in points: if doubled_oriented_area(p1, p2, p) != 0: res.append(p) return res def on_the_same_line(points): if len(points) < 3: return True return not filter_points(points[0], points[1], points[2:]) def main(): n = int(input()) if n <= 4: print('YES') return points = [] for i in range(n): points.append(read()) for p in combinations(range(3), 2): filtered = filter_points(points[p[0]], points[p[1]], points) if on_the_same_line(filtered): print('YES') return print('NO') if __name__ == '__main__': main() ```
101,760
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Tags: geometry Correct Solution: ``` import math import sys from collections import defaultdict def solve(io): N = io.readInt() P = [None] * N for i in range(0, N): X = io.readInt() Y = io.readInt() P[i] = (X, Y) if N <= 4: io.println("YES") return for i in range(0, 3): P[0], P[i] = P[i], P[0] if can(P): io.println("YES") return io.println("NO") def can(P): slopes = makeSlopeDict(P) if len(slopes) <= 2: return True matches = 0 others = [] for _, v in slopes.items(): if len(v) > 1: matches += 1 else: others += v if matches > 1: return False line = makeSlopeDict(others) return len(line) <= 1 def makeSlopeDict(pts): slopes = defaultdict(set) for i in range(1, len(pts)): dx = pts[i][0] - pts[0][0] dy = pts[i][1] - pts[0][1] if dy < 0: dx *= -1 dy *= -1 if dx != 0 and dy != 0: g = math.gcd(dx, dy) v = (dx / g, dy / g) elif dx == 0 and dy != 0: v = (0, 1) elif dx != 0 and dy == 0: v = (1, 0) else: v = (0, 0) slopes[v].add(pts[i]) return slopes # +---------------------+ # | TEMPLATE CODE BELOW | # | DO NOT MODIFY | # +---------------------+ # TODO: maybe reading byte-by-byte is faster than reading and parsing tokens. class IO: input = None output = None raw = "" buf = [] pos = 0 def __init__(self, inputStream, outputStream): self.input = inputStream self.output = outputStream def readToBuffer(self): self.raw = self.input.readline().rstrip('\n') self.buf = self.raw.split() self.pos = 0 def readString(self): while self.pos == len(self.buf): self.readToBuffer() ans = self.buf[self.pos] self.pos += 1 return ans def readInt(self): return int(self.readString()) def readFloat(self): return float(self.readString()) def readStringArray(self, N, offset = 0): arr = [ None ] * offset for _ in range(0, N): arr.append(self.readString()) return arr def readIntArray(self, N, offset = 0): arr = [ None ] * offset for _ in range(0, N): arr.append(self.readInt()) return arr def readFloatArray(self, N, offset = 0): arr = [ None ] * offset for _ in range(0, N): arr.append(self.readFloat()) return arr def readLine(self): while self.pos == len(self.buf): self.readToBuffer() if self.pos > 0: raise ValueError("Cannot call readline in the middle of a line.") return self.raw def print(self, s): self.output.write(str(s)) def println(self, s): self.print(s) self.print('\n') def flushOutput(self): self.output.flush() pythonIO = IO(sys.stdin, sys.stdout) solve(pythonIO) pythonIO.flushOutput() ```
101,761
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Tags: geometry Correct Solution: ``` ## necessary imports import sys input = sys.stdin.readline #from math import ceil, floor, factorial; # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp ## gcd function def gcd(a,b): if b == 0: return a return gcd(b, a % b); ## nCr function efficient using Binomial Cofficient def nCr(n, k): if(k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## upper bound function code -- such that e in a[:i] e < x; def upper_bound(a, x, lo=0): hi = len(a) while lo < hi: mid = (lo+hi)//2 if a[mid] < x: lo = mid+1 else: hi = mid return lo ## prime factorization def primefs(n): ## if n == 1 ## calculating primes primes = {} while(n%2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n//2 for i in range(3, int(n**0.5)+2, 2): while(n%i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n//i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## DISJOINT SET UNINON FUNCTIONS def swap(a,b): temp = a a = b b = temp return a,b # find function with path compression included (recursive) # def find(x, link): # if link[x] == x: # return x # link[x] = find(link[x], link); # return link[x]; # find function with path compression (ITERATIVE) def find(x, link): p = x; while( p != link[p]): p = link[p]; while( x != p): nex = link[x]; link[x] = p; x = nex; return p; # the union function which makes union(x,y) # of two nodes x and y def union(x, y, link, size): x = find(x, link) y = find(y, link) if size[x] < size[y]: x,y = swap(x,y) if x != y: size[x] += size[y] link[y] = x ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e6 + 5) def spf_sieve(): spf[1] = 1; for i in range(2, MAXN): spf[i] = i; for i in range(4, MAXN, 2): spf[i] = 2; for i in range(3, ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i*i, MAXN, i): if spf[j] == j: spf[j] = i; ## function for storing smallest prime factors (spf) in the array ################## un-comment below 2 lines when using factorization ################# # spf = [0 for i in range(MAXN)] # spf_sieve() def factoriazation(x): ret = {}; while x != 1: ret[spf[x]] = ret.get(spf[x], 0) + 1; x = x//spf[x] return ret ## this function is useful for multiple queries only, o/w use ## primefs function above. complexity O(log n) ## taking integer array input def int_array(): return list(map(int, input().strip().split())) ## taking string array input def str_array(): return input().strip().split(); #defining a couple constants MOD = int(1e9)+7; CMOD = 998244353; INF = float('inf'); NINF = -float('inf'); ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### def fxn(p, q): x = []; for r in a: ## simple slope check (y3 - y1 )/(x3 - x1) = (y2 - y1)/(x2 - x1); if (r[1] - p[1]) * (q[0] - p[0]) != (q[1] - p[1]) * (r[0] - p[0]): x.append(r); if len(x) <= 2: return True; rh, cp = x[0], x[1]; for c in x: if (c[1] - rh[1]) * (cp[0] - rh[0]) != (cp[1] - rh[1]) * (c[0] - rh[0]): return False; return True; n = int(input()); a = []; for _ in range(n): x, y = int_array(); a.append((x, y)); if n < 5: print('YES'); else: if fxn(a[0], a[1]) or fxn(a[0], a[2]) or fxn(a[1], a[2]): print('YES'); else: print('NO'); ```
101,762
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Tags: geometry Correct Solution: ``` import sys input = sys.stdin.readline n = int(input()) if n <= 4: print("YES") exit() A = [None]*n for i in range(n): A[i] = list(map(int,input().split())) def is_colinear(a1,a2,a3): if a1 == a2 or a2 == a3 or a1 == a3: return True x1,y1 = a1 x2,y2 = a2 x3,y3 = a3 if x1 == x2 or x1 == x3 or x2 == x3: return x1 == x2 == x3 if y1 == y2 or y1 == y3 or y2 == y3: return y1 == y2 == y3 return (y2 - y1) * (x3 - x1) == (y3 - y1) * (x2 - x1) X,Y,Z = A[0],A[1],A[2] def good(X,Y): # are X,Y on the same line? bad = [] for i in range(n): if not is_colinear(X,Y,A[i]): bad.append(A[i]) if len(bad) <= 2: return True U,V = bad[0],bad[1] for i in range(len(bad)): if not is_colinear(U,V,bad[i]): return False return True if good(X,Y) or good(Y,Z) or good(X,Z): print("YES") exit() print("NO") exit() ```
101,763
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Tags: geometry Correct Solution: ``` from decimal import Decimal class Point: def __init__(self,x,y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return self.x.__hash__()^self.y.__hash__() class Line: def __init__(self,p1,p2): self.A = p1.y - p2.y self.B = p2.x - p1.x self.C = p1.x*p2.y - p2.x*p1.y def isPointOnLine(self,p): if (self.A*p.x + self.B*p.y + self.C) == 0: return True else: return False def __eq__(self, line): if ((self.A==0) != (line.A == 0)) or ((self.B==0) != (line.B == 0)) or ((self.C==0) != (line.C == 0)): return False t = 0 if self.A != 0: t = Decimal(self.A)/Decimal(line.A) if self.B != 0: if t == 0: t = Decimal(self.B)/Decimal(line.B) else: if t != Decimal(self.B)/Decimal(line.B): return False if self.C != 0: if t == 0: t = Decimal(self.C)/Decimal(line.C) else: if t != Decimal(self.C)/Decimal(line.C): return False return True #in n = int(input()) points = [] for i in range(0,n): a = list(map(int,input().split())) points.append(Point(a[0],a[1])) #calc ans = "" if n < 5: ans = "Yes" else: lines = [] linePoints = [] lines.append(Line(points[0], points[1])) linePoints.append([points[0], points[1]]) for i in range(1, 5): for j in range(0, i): if i != j: line = Line(points[i], points[j]) exist = False for k in range(0, len(lines)): if lines[k] == line: exist = True existP = False for p in range(0, len(linePoints[k])): if linePoints[k][p] == points[i]: existP = True break if not existP: linePoints[k].append(points[i]) if not exist: lines.append(Line(points[i],points[j])) linePoints.append([points[i],points[j]]) firstLine = 0 secondLine = 0 i_point = 0 if len(lines) == 9: ans == "No" else: if len(lines) == 8 or len(lines) == 6: for i in range(0, len(linePoints)): if len(linePoints[i]) == 3: firstLine = i for i in range(0, len(linePoints)): if len(set(linePoints[i])-set(linePoints[firstLine])) == 2: secondLine = i lines = [lines[firstLine], lines[secondLine]] linePoints = [linePoints[firstLine], linePoints[secondLine]] elif len(lines) == 5: for i in range(0, len(linePoints)): if len(linePoints[i]) == 4: firstLine = i fifth_point = list(set(points[:5])-set(linePoints[firstLine]))[0] if len(points) > 5: for i in range(5, len(points)): exist = False if not lines[firstLine].isPointOnLine(points[i]): six_point = points[i] lines = [lines[firstLine], Line(fifth_point, six_point)] i_point = i + 1 exist = True break if not exist: ans = "Yes" else: ans = "Yes" elif len(lines) == 1: if len(points) > 5: for i in range(5, len(points)): exist = False if not lines[0].isPointOnLine(points[i]): first_point = points[i] i_point = i + 1 exist = True break if exist: if len(points) > i_point: for i in range(i_point, len(points)): exist = False if not lines[0].isPointOnLine(points[i]): second_point = points[i] i_point = i + 1 exist = True lines = [lines[0], Line(first_point, second_point)] break if not exist: ans = "Yes" else: ans = "Yes" else: ans = "Yes" else: ans = "Yes" if ans == "" and len(points) > i_point: exist = False for i in range(i_point, len(points)): if not (lines[0].isPointOnLine(points[i]) or lines[1].isPointOnLine(points[i])): exist = True ans = "No" break if not exist: ans = "Yes" else: ans = "Yes" #out print(ans) ```
101,764
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Tags: geometry Correct Solution: ``` def collinear(a, b, c): return a[0]*(b[1] - c[1]) + b[0]*(c[1] - a[1]) + c[0]*(a[1] - b[1]) def check(a, pt1, pt2): tmp = [] for x in a: if collinear(a[pt1], x, a[pt2]) != 0: tmp.append(x) if len(tmp) < 3: return True x = tmp[0] y = tmp[1] for z in tmp: if collinear(x, z, y) != 0: return False return True; n = int(input()) ok = False a = [] for i in range(n): a.append(list(map(int, input().split()))) if (n < 5) or (check(a, 0, 1)) or (check(a, 0, 2)) or (check(a, 1, 2)): ok = True if ok == True: print('YES') else: print('NO') ```
101,765
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Tags: geometry Correct Solution: ``` n = int(input()) lst = [] for x in range(n): (a, b) = map(int, input().split()) lst.append((a, b)) def scal(x1, y1, x2, y2, x3, y3): if (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) == 0: return True return False def check(): for x in range(n - 2): if len(s2) >= 3: if not scal(lst[s2[-3]][0], lst[s2[-3]][1], lst[s2[-2]][0], lst[s2[-2]][1], lst[s2[-1]][0], lst[s2[-1]][1]): return False if scal(lst[0][0], lst[0][1], lst[1][0], lst[1][1], lst[x + 2][0], lst[x + 2][1]): s1.append(x + 2) else: s2.append(x + 2) if len(s2) >= 3: if not scal(lst[s2[-3]][0], lst[s2[-3]][1], lst[s2[-2]][0], lst[s2[-2]][1], lst[s2[-1]][0], lst[s2[-1]][1]): return False return True flag = True if n >= 5: s1 = [] s2 = [] if not check(): lst[1], lst[s2[0]] = lst[s2[0]], lst[1] x = s2[0] s1 = [] s2 = [] if not check(): lst[0], lst[s2[0]] = lst[s2[0]], lst[0] s1 = [] s2 = [] if not check(): flag = False if flag: print("YES") else: print("NO") ```
101,766
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Tags: geometry Correct Solution: ``` # https://codeforces.com/problemset/problem/961/D def is_linear(A, B, C): return (B[0] - A[0]) * (C[1] - A[1]) == (C[0] - A[0]) * (B[1] - A[1]) def is_line(pos): if len(pos) <= 2: return True A, B = P[pos[0]], P[pos[1]] for p in pos[2:]: if is_linear(A, B, P[p]) == False: return False return True def check(A, B, used): for i, p in enumerate(P): if is_linear(A, B, p) == True: used[i] = 1 def refresh(): for i in range(n): used[i] = 0 n = int(input()) P = [list(map(int, input().split())) for _ in range(n)] if n <= 3: print("YES") else: used = [0] * n flg = "NO" for i in range(3): A, B = P[i], P[(i+1)%3] check(A, B, used) pos = [i for i, x in enumerate(used) if x==0] if is_line(pos) == True: flg = "YES" #print(A, B) refresh() print(flg) ```
101,767
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Submitted Solution: ``` from itertools import combinations ps = [tuple(map(int, input().split())) for ln in range(int(input()))] def outside(pt, v1, v2): return ((pt[0]-v2[0])*(v1[1] - v2[1]) - (pt[1]-v2[1])*(v1[0] - v2[0])) def oneline(ps): return len(ps) <= 2 or not [p for p in ps if outside(p, ps[0], ps[1])] if len(ps) <= 4: print("YES") else: vs = (ps[:2] + [p for p in ps if outside(p, *ps[:2])] + [ps[0]])[:3] print ("YES" if any(oneline([p for p in ps if outside(p, v1, v2)]) for v1, v2 in combinations(vs,2)) else "NO") ``` Yes
101,768
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Submitted Solution: ``` import math import sys from collections import defaultdict def solve(io): N = io.readInt() P = [None] * N for i in range(0, N): X = io.readInt() Y = io.readInt() P[i] = (X, Y) if N <= 4: io.println("YES") return if can(P): io.println("YES") return P[0], P[1] = P[1], P[0] if can(P): io.println("YES") return P[0], P[2] = P[2], P[0] if can(P): io.println("YES") return io.println("NO") def can(P): slopes = makeSlopeDict(P) if len(slopes) <= 2: return True matches = 0 others = [] for _, v in slopes.items(): if len(v) > 1: matches += 1 else: others += v if matches > 1: return False line = makeSlopeDict(others) return len(line) <= 1 def makeSlopeDict(pts): slopes = defaultdict(set) for i in range(1, len(pts)): dx = pts[i][0] - pts[0][0] dy = pts[i][1] - pts[0][1] if dy < 0: dx *= -1 dy *= -1 if dx != 0 and dy != 0: g = math.gcd(dx, dy) v = (dx / g, dy / g) elif dx == 0 and dy != 0: v = (0, 1) elif dx != 0 and dy == 0: v = (1, 0) else: v = (0, 0) slopes[v].add(pts[i]) return slopes # +---------------------+ # | TEMPLATE CODE BELOW | # | DO NOT MODIFY | # +---------------------+ # TODO: maybe reading byte-by-byte is faster than reading and parsing tokens. class IO: input = None output = None raw = "" buf = [] pos = 0 def __init__(self, inputStream, outputStream): self.input = inputStream self.output = outputStream def readToBuffer(self): self.raw = self.input.readline().rstrip('\n') self.buf = self.raw.split() self.pos = 0 def readString(self): while self.pos == len(self.buf): self.readToBuffer() ans = self.buf[self.pos] self.pos += 1 return ans def readInt(self): return int(self.readString()) def readFloat(self): return float(self.readString()) def readStringArray(self, N, offset = 0): arr = [ None ] * offset for _ in range(0, N): arr.append(self.readString()) return arr def readIntArray(self, N, offset = 0): arr = [ None ] * offset for _ in range(0, N): arr.append(self.readInt()) return arr def readFloatArray(self, N, offset = 0): arr = [ None ] * offset for _ in range(0, N): arr.append(self.readFloat()) return arr def readLine(self): while self.pos == len(self.buf): self.readToBuffer() if self.pos > 0: raise ValueError("Cannot call readline in the middle of a line.") return self.raw def print(self, s): self.output.write(str(s)) def println(self, s): self.print(s) self.print('\n') def flushOutput(self): self.output.flush() pythonIO = IO(sys.stdin, sys.stdout) solve(pythonIO) pythonIO.flushOutput() ``` Yes
101,769
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Submitted Solution: ``` from itertools import combinations import sys d = [int(x) for x in sys.stdin.read().split()][1:] ps = list(zip(d[::2], d[1::2])) def outside(pt, v1, v2): return ((pt[0]-v2[0])*(v1[1] - v2[1]) - (pt[1]-v2[1])*(v1[0] - v2[0])) def oneline(ps): return len(ps) <= 2 or not [p for p in ps if outside(p, ps[0], ps[1])] if len(ps) <= 4: print("YES") else: vs = (ps[:2] + [p for p in ps if outside(p, *ps[:2])] + [ps[0]])[:3] print ("YES" if any(oneline([p for p in ps if outside(p, v1, v2)]) for v1, v2 in combinations(vs,2)) else "NO") ``` Yes
101,770
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Submitted Solution: ``` import math def get_line(x1, y1, x2, y2): a = x2 - x1 b = y1 - y2 c = x1 * (y2 - y1) - y1 * (x2 - x1) g = math.gcd(math.gcd(a, b), c) a //= g b //= g c //= g return a, b, c n = int(input()) xy = [] for i in range(n): x, y = [int(x) for x in input().split()] xy.append((x, y)) if n <= 3: print("YES") exit() def check(x1, y1, x2, y2, xy): a1, b1, c1 = get_line(x1, y1, x2, y2) other_point = None cnt_other = 0 a2, b2, c2 = 0, 0, 0 for i in range(len(xy)): x, y = xy[i] if a1 * y + b1 * x + c1 != 0: if other_point is None: other_point = x, y cnt_other = 1 elif cnt_other == 1: cnt_other = 2 a2, b2, c2 = get_line(*other_point, x, y) else: if a2 * y + b2 * x + c2 != 0: return False return True if check(*xy[0], *xy[1], xy[2:]): print("YES") elif check(*xy[1], *xy[2], [xy[0]] + xy[3:]): print("YES") elif check(*xy[0], *xy[2], [xy[1]] + xy[3:]): print("YES") else: print("NO") ``` Yes
101,771
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Submitted Solution: ``` n = int(input()) L = [(0, 0)] * n for i in range(n): t = input().split(' ') a = int(t[0]) b = int(t[1]) L[i] = (a, b) if n <= 4: print("YES") else: b0 = True b1 = True b2 = True L0 = [L[0]] L1 = [L[1]] L2 = [L[2]] for j in range(3, n): if (L[0][0]-L[1][0])*(L[0][1]-L[j][1])!=(L[0][1]-L[1][1])*(L[0][0]-L[j][0]): L2.append(L[j]) if (L[2][0]-L[0][0])*(L[2][1]-L[j][1])!=(L[2][1]-L[0][1])*(L[2][0]-L[j][0]): L1.append(L[j]) if (L[2][0]-L[1][0])*(L[2][1]-L[j][1])!=(L[2][1]-L[1][1])*(L[2][0]-L[j][0]): L0.append(L[j]) if len(L0) >= 3: for j in range(2, len(L0)): if (L0[0][0]-L0[1][0])*(L0[0][1]-L0[j][1])!=(L0[0][1]-L0[1][1])*(L0[0][0]-L0[j][0]): b0 = False if len(L1) >= 3: for j in range(2, len(L1)): if (L1[0][0]-L1[1][0])*(L1[0][1]-L1[j][1])!=(L1[0][1]-L1[1][1])*(L1[0][0]-L1[j][0]): b1 = False if len(L2) >= 3: for j in range(2, len(L2)): if (L2[0][0]-L2[1][0])*(L2[0][1]-L2[j][1])!=(L2[0][1]-L2[1][1])*(L2[0][0]-L2[j][0]): b2 = False if b0 or b1 or b2: print("YES") else: print("NO") ``` No
101,772
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Submitted Solution: ``` class Point: def __init__(self,x,y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return self.x.__hash__()^self.y.__hash__() class Line: def __init__(self,p1,p2): self.A = p1.y - p2.y self.B = p2.x - p1.x self.C = p1.x*p2.y - p2.x*p1.y def isPointOnLine(self,p): if (self.A*p.x + self.B*p.y + self.C) == 0: return True else: return False def __eq__(self, line): if ((self.A==0) != (line.A == 0)) or ((self.B==0) != (line.B == 0)) or ((self.C==0) != (line.C == 0)): return False t = 0 if self.A != 0: t = self.A/line.A if self.B != 0: if t == 0: t = self.B/line.B else: if t != self.B/line.B: return False if self.C != 0: if t == 0: t = self.C/line.C else: if t != self.C/line.C: return False return True #in n = int(input()) points = [] for i in range(0,n): a = list(map(int,input().split())) points.append(Point(a[0],a[1])) #calc ans = "" if n < 5: ans = "Yes" else: lines = [] linePoints = [] lines.append(Line(points[0], points[1])) linePoints.append([points[0], points[1]]) for i in range(1, 5): for j in range(0, i): if i != j: line = Line(points[i], points[j]) exist = False for k in range(0, len(lines)): if lines[k] == line: exist = True existP = False for p in range(0, len(linePoints[k])): if linePoints[k][p] == points[i]: existP = True break if not existP: linePoints[k].append(points[i]) if not exist: lines.append(Line(points[i],points[j])) linePoints.append([points[i],points[j]]) firstLine = 0 secondLine = 0 i_point = 0 if len(lines) == 10: ans == "No" else: if len(lines) == 8: for i in range(0, len(linePoints)): if len(linePoints[i]) == 3: firstLine = i for i in range(0, len(linePoints)): if len(set(linePoints[i]) & set(linePoints[firstLine])) == 0: secondLine = i lines = [lines[firstLine], lines[secondLine]] linePoints = [linePoints[firstLine], linePoints[secondLine]] elif len(lines) == 5: for i in range(0, len(linePoints)): if len(linePoints[i]) == 4: firstLine = i fifth_point = list(set(points[:5])-set(linePoints[firstLine]))[0] if len(points) > 5: for i in range(5, len(points)): exist = False if not lines[firstLine].isPointOnLine(points[i]): six_point = points[i] lines = [lines[firstLine], Line(fifth_point, six_point)] i_point = i + 1 exist = True break if not exist: ans = "Yes" else: ans = "Yes" elif len(lines) == 1: if len(points) > 5: for i in range(5, len(points)): exist = False if not lines[0].isPointOnLine(points[i]): first_point = points[i] i_point = i + 1 exist = True break if exist: if len(points) > i_point: for i in range(i_point, len(points)): exist = False if not lines[0].isPointOnLine(points[i]): second_point = points[i] i_point = i + 1 exist = True lines = [lines[0], Line(first_point, second_point)] break if not exist: ans = "Yes" else: ans = "Yes" else: ans = "Yes" else: ans = "Yes" if ans == "" and len(points) > i_point: exist = False for i in range(i_point, len(points)): if not (lines[0].isPointOnLine(points[i]) or lines[1].isPointOnLine(points[i])): exist = True ans = "No" break if not exist: ans = "Yes" else: ans = "Yes" #out print(ans) ``` No
101,773
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Submitted Solution: ``` def gcd(a, b): if a > b: a, b = b, a if b % a==0: return a return gcd(b % a, a) def line(a, b): x0, y0 = a x1, y1 = b if x0==x1: return [True, x1, None] else: slope = (y1-y0)/(x1-x0) inter = y0-slope*x0 return [False, slope, inter] def online(line, a): x0, y0 = a if line[0]: return x0==line[1] else: C, slope, inter = line return slope*x0+inter==y0 def process(A): n = len(A) if n <= 3: return 'YES' l1 = line(A[0], A[1]) l2 = line(A[1], A[2]) l3 = line(A[0], A[2]) for Line1 in [l1, l2, l3]: other = [] for x in A: if not online(Line1, x): other.append(x) if len(other) <= 2: return 'YES' a1 = other[0] a2 = other[1] Line2 = line(a1, a2) works = True for x in other: if not online(Line2, x): works = False break if works: return 'YES' return 'NO' n = int(input()) A = [] for i in range(n): x, y = [int(x) for x in input().split()] A.append([x, y]) print(process(A)) ``` No
101,774
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines? Input The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct. Output If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO. Examples Input 5 0 0 0 1 1 1 1 -1 2 2 Output YES Input 5 0 0 1 0 2 1 1 1 2 3 Output NO Note In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. <image> Submitted Solution: ``` import sys input = sys.stdin.readline from math import gcd def linear(a, b, c): if len(set([a, b, c])) < 3: return True q1, p1 = a[1] - b[1], a[0] - b[0] g1 = gcd(q1, p1) q1 //= g1 p1 //= g1 if p1 * q1 < 0: p1 = -abs(p1) q1 = abs(q1) q2, p2 = b[1] - c[1], b[0] - c[0] g2 = gcd(q2, p2) q2 //= g2 p2 //= g2 if p2 * q2 < 0: p2 = -abs(p2) q2 = abs(q2) if p1 == 0 and p2 == 0 or q1 == 0 and q2 == 0: return True return p1 == p2 and q1 == q2 n = int(input()) a = [] for i in range(n): x, y = map(int, input().split()) a.append((x, y)) if n <= 4: print('YES') exit() b = [a[0], a[1]] d = dict() d[(a[0], a[1])] = 2 for i in range(2, n): lin = False for j in range(len(b) - 1): for k in range(j+1, len(b)): p1, p2 = b[j], b[k] if linear(p1, p2, a[i]): lin = True d[(p1, p2)] += 1 if not lin: b.append(a[i]) for p in b: d[(p, a[i])] = 2 if len(b) == 4: break if len(b) == 2: print('YES') exit() if len(b) == 3: if min(d.values()) > 2: print('NO') else: print('YES') exit() for i in range(len(b)): for j in range(i+1, len(b)): p1, p2 = b[i], b[j] p3, p4 = set(b) - set([p1, p2]) poss = True for p in a: if linear(p1, p2, p) or linear(p3, p4, p): pass else: poss = False break if poss: print('YES') exit() print('NO') ``` No
101,775
Provide tags and a correct Python 3 solution for this coding contest problem. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Tags: constructive algorithms, graphs Correct Solution: ``` a = list(map(int, input().split())) ab = [['A']*25+['B']*25 for i in range(25)] cd = [['C']*25+['D']*25 for i in range(25)] print (50, 50) for i in range(4): a[i] -= 1 si, sj = 26, 26 while a[0] > 0: cd[si-25][sj] = 'A' a[0] -= 1 sj += 2 if sj == 50: sj = 26 si += 2 si, sj = 26, 0 while a[1] > 0: cd[si-25][sj] = 'B' a[1] -= 1 sj += 2 if sj == 26: sj = 0 si += 2 si, sj = 0,0 while a[2] > 0: ab[si][sj] = 'C' a[2] -= 1 sj += 2 if sj == 24: sj = 0 si += 2 si, sj = 0, 26 while a[3] > 0: ab[si][sj] = 'D' a[3] -= 1 sj += 2 if sj == 50: sj = 26 si += 2 for i in ab: print (''.join(i)) for i in cd: print (''.join(i)) ```
101,776
Provide tags and a correct Python 3 solution for this coding contest problem. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Tags: constructive algorithms, graphs Correct Solution: ``` a = [int(x) - 1 for x in input().split()] n = m = 48 colors = "ABCD" side = n // 2 ans = [[0] * n for _ in range(n)] for i, color in enumerate(colors): for dx in range(side): for dy in range(side): x, y = dx + side * (i & 1), dy + side * (i // 2) ans[x][y] = color new_i = (i + 1) % 4 if 0 < min(dx, dy) and max(dx, dy) < side - 1 and a[new_i] and dx & 1 and dy & 1: ans[x][y] = colors[new_i] a[new_i] -= 1 print(n, m) print(*(''.join(row) for row in ans), sep='\n') ```
101,777
Provide tags and a correct Python 3 solution for this coding contest problem. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Tags: constructive algorithms, graphs Correct Solution: ``` import sys A,B,C,D = map(int,input().split()) board = [['A']*50 for i in range(33)] for i in range(24,33): for j in range(50): board[i][j] ='B' A -= 1 for i in range(1,24,2): for j in range(1,50,2): # B는 1개 남겨두기 if B > 1: board[i][j] = 'B' B -= 1 elif C > 0: board[i][j] = 'C' C -= 1 elif D > 0: board[i][j] = 'D' D -= 1 board[23][49] = 'B' for i in range(25,33,2): for j in range(1,50,2): if A > 0: board[i][j] = 'A' A -= 1 sys.stdout.write("33 50\n") for i in range(33): sys.stdout.write(''.join(board[i])) if i != 32: sys.stdout.write('\n') ```
101,778
Provide tags and a correct Python 3 solution for this coding contest problem. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Tags: constructive algorithms, graphs Correct Solution: ``` a, b, c, d = map(int, input().split()) res = [['A'] * 50 for i in range(25)] + \ [['B'] * 50 for i in range(25)] a, b = a - 1, b - 1 for i in range(0, 24, 2): for j in range(0, 50, 2): if b > 0: b -= 1 res[i][j] = 'B' elif c > 0: c -= 1 res[i][j] = 'C' elif d > 0: d -= 1 res[i][j] = 'D' if a > 0: a -= 1 res[i + 26][j] = 'A' print(50, 50) for i in res: print(''.join(i)) ```
101,779
Provide tags and a correct Python 3 solution for this coding contest problem. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Tags: constructive algorithms, graphs Correct Solution: ``` a,b,c,d = map(int,input().split()) if a + b + c + d == 4: print(1,4) print("ABCD") else: print(50,50) ans = [[""]*50 for i in range(50)] if a == 1: for i in range(50): for j in range(50): ans[i][j] = "A" for i in range(0,50,2): for j in range(0,50,2): b -= 1 ans[i][j] = "B" if b == 0: break if b == 0: break for i in range(15,50,2): for j in range(0,50,2): c -= 1 ans[i][j] = "C" if c == 0: break if c == 0: break for i in range(30,50,2): for j in range(0,50,2): d -= 1 ans[i][j] = "D" if d == 0: break if d == 0: break elif b == 1: for i in range(50): for j in range(50): ans[i][j] = "B" for i in range(0,50,2): for j in range(0,50,2): a -= 1 ans[i][j] = "a" if a == 0: break if a == 0: break for i in range(15,50,2): for j in range(0,50,2): c -= 1 ans[i][j] = "C" if c == 0: break if c == 0: break for i in range(30,50,2): for j in range(0,50,2): d -= 1 ans[i][j] = "D" if d == 0: break if d == 0: break else: b -= 1 a -= 1 for i in range(50): for j in range(50): ans[i][j] = "A" for i in range(0,50,2): for j in range(0,50,2): b -= 1 ans[i][j] = "B" if b == 0: break if b == 0: break for i in range(12,50,2): for j in range(0,50,2): c -= 1 ans[i][j] = "C" if c == 0: break if c == 0: break for i in range(24,50,2): for j in range(0,50,2): d -= 1 ans[i][j] = "D" if d == 0: break if d == 0: break for i in range(35,50): for j in range(50): ans[i][j] = "B" for i in range(37,50,2): for j in range(0,50,2): a -= 1 ans[i][j] = "A" if a == 0: break if a == 0: break for i in range(50): for j in range(50): print(ans[i][j],end="") print() ```
101,780
Provide tags and a correct Python 3 solution for this coding contest problem. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Tags: constructive algorithms, graphs Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): a,b,c,d = LI() r = [['']*50 for _ in range(50)] for i in range(50): for j in range(50): if i < 25: if j < 25: r[i][j] = 'A' else: r[i][j] = 'B' else: if j < 25: r[i][j] = 'C' else: r[i][j] = 'D' for i in range(a-1): j = (i // 12) * 2 k = (i % 12) * 2 r[j][k+26] = 'A' for i in range(b-1): j = (i // 12) * 2 k = (i % 12) * 2 r[j][k] = 'B' for i in range(c-1): j = (i // 12) * 2 k = (i % 12) * 2 r[j+26][k+26] = 'C' for i in range(d-1): j = (i // 12) * 2 k = (i % 12) * 2 r[j+26][k] = 'D' return '50 50\n' + '\n'.join(map(lambda x: ''.join(x), r)) print(main()) ```
101,781
Provide tags and a correct Python 3 solution for this coding contest problem. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Tags: constructive algorithms, graphs Correct Solution: ``` FIFTY = 50 TWENTY_FIVE = 25 TWELVE = 12 grid = [['X' for _ in range(FIFTY)] for _ in range(FIFTY)] def construct(n, mark, bg, base_i, base_j): for i in range(TWENTY_FIVE): for j in range(TWENTY_FIVE): grid[base_i + i][base_j + j] = bg for i in range(n): grid[base_i + 2 * (i // TWELVE) + 1][base_j + 2 * (i % TWELVE) + 1] = mark def main(): a, b, c, d = map(int, input().split()) construct(a - 1, 'A', 'B', 0, 0) construct(b - 1, 'B', 'C', TWENTY_FIVE, 0) construct(c - 1, 'C', 'D', 0, TWENTY_FIVE) construct(d - 1, 'D', 'A', TWENTY_FIVE, TWENTY_FIVE) print(FIFTY, FIFTY) for row in grid: print(''.join(row)) if __name__ == '__main__': main() ```
101,782
Provide tags and a correct Python 3 solution for this coding contest problem. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Tags: constructive algorithms, graphs Correct Solution: ``` a, b, c, d = map(int, input().strip().split()) def fill(s, st, ch, cnt): ri, ci = st, 0 while cnt > 0: s[ri][ci] = ch cnt -= 1 ci += 2 if ci >= 50: ri += 3 ci = 0 dat = dict() dat.update({'A': a, 'B': b, 'C': c, 'D': d}) dat = sorted(dat.items(), key=lambda kv : kv[1]) mf = dat[3] lf = dat[0] res = list() for i in range(30): res.append(list(lf[0] * 50)) for i in range(20): res.append(list(mf[0] * 50)) fill(res, 0, dat[3][0], dat[3][1] - 1) fill(res, 1, dat[2][0], dat[2][1]) fill(res, 2, dat[1][0], dat[1][1]) fill(res, 31, dat[0][0], dat[0][1] - 1) print(50, 50) for e_ in res: print(''.join(map(str, e_))) ```
101,783
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Submitted Solution: ``` data = input() def main(): counters = [int(x) for x in data.split(' ')] codes = { 0: 'A', 1: 'B', 2: 'C', 3: 'D', } counters[0] -= 1 counters[3] -= 1 completed = [] row = [] for flower in range(1, 4): rows, row = fill_grid(row, 'A', codes[flower], counters[flower]) completed += rows if row: completed.append(''.join(row) + 'A' * (50 - len(row))) completed.append('A' * 50) completed.append('D' * 50) row = [] rows, row = fill_grid(row, 'D', 'A', counters[0]) completed += rows if row: completed.append(''.join(row) + 'D' * (50 - len(row))) completed.append('D' * 50) print('{} 50'.format(len(completed))) for row in completed: print(row) def fill_grid(row, grid, flower, counter): completed = [] while counter > 0: counter -= 1 row.append(flower) row.append(grid) if len(row) == 50: completed.append(''.join(row)) completed.append(''.join([grid] * 50)) row = [] return completed, row if __name__ == '__main__': main() ``` Yes
101,784
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Submitted Solution: ``` a,b,c,d=map(int,input().split()) m=[] for i in range(50): m.append([0]*50) for i in range(0,25,2): for j in range(0,25,2): if a==1: break a-=1 m[i][j]='A' if a==1: break for i in range(25): for j in range(25): if m[i][j]==0: m[i][j]='B' for i in range(0,25,2): for j in range(26,50,2): if b==1: break b-=1 m[i][j]='B' if b==1: break for i in range(25): for j in range(25,50): if m[i][j]==0: m[i][j]='C' for i in range(26,50,2): for j in range(25,50,2): if c==1: break c-=1 m[i][j]='C' if c==1: break for i in range(25,50): for j in range(25,50): if m[i][j]==0: m[i][j]='D' for i in range(25,50,2): for j in range(0,24,2): if d==1: break d-=1 m[i][j]='D' if d==1: break for i in range(25,50): for j in range(0,25): if m[i][j]==0: m[i][j]='A' print(50,50) for i in range(50): for j in range(50): print(m[i][j],end="") print() ``` Yes
101,785
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Submitted Solution: ``` a,b,c,d=map(int,input().split()) r=[['A' for i in range(50)] for j in range(50)] flag=0 print(50,50) for i in range(0,8,2): for j in range(0,50,2): r[i][j]='D' d-=1 if(d==0): flag=1 break if(flag==1): break flag=0 for i in range(8,16,2): for j in range(0,50,2): r[i][j]='C' c-=1 if(c==0): flag=1 break if(flag==1): break for i in range(49,32,-1): for j in range(50): r[i][j]='B' a-=1 b-=1 flag=0 if(a!=0): for i in range(34,50,2): for j in range(0,50,2): r[i][j]='A' a-=1 if(a==0): flag=1 break if(flag==1): break flag=0 if(b!=0): for i in range(16,50,2): for j in range(0,50,2): r[i][j]='B' b-=1 if(b==0): flag=1 break if(flag==1): break for i in r: for j in i: print(j,end="") print() ``` Yes
101,786
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Submitted Solution: ``` a,b,c,d = list(map(int ,input().split())) pole = [] for row in range (40): pole.append(['A']*50) for row in range (10): pole.append(['D']*50) for i in range(b): pole[(i // 25) *2 ][(i %25) *2] = 'B' for i in range(c): pole[ 7 + (i // 25) *2 ][(i %25) *2] = 'C' for i in range(d-1): pole[ 14 + (i // 25) *2 ][(i %25) *2] = 'D' for i in range(a-1): pole[41 + (i // 25) *2 ][(i %25) *2] = 'A' print('50 50') for row in range(50): print(''.join(pole[row])) ``` Yes
101,787
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Submitted Solution: ``` # https://codeforces.com/problemset/problem/989/C def create(bk, fr, num): a = [[bk for _ in range(50)] for _ in range(12)] flg = True for i in range(0, 12, 2): for j in range(0, 50, 2): if num == 0: flg = False break a[i][j] = fr num -= 1 if flg == False: break return a a, b, c, d = list(map(int, input().split())) a -= 1 b -= 1 c -= 1 d -= 1 ans = [] ans.extend(create('A', 'B', b)) ans.extend(create('B', 'C', c)) ans.extend(create('C', 'D', d)) ans.extend(create('D', 'A', a)) for x in ans: for y in x: print(y, end='') print() ``` No
101,788
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Submitted Solution: ``` line = input() flowers = line.split('\n')[0] flowers = flowers.split(' ') a = int(flowers[3]) ind = 3 for i in range(3): if int(flowers[i]) < a: a = int(flowers[i]) ind = i b = int(flowers[3]) index = (ind+2)%4 field = [[0 for x in range(50)] for y in range(50)] def makerect(field,n,index): for i in range(50): for j in range(50): if field[i][j] == 0: field[i][j] = chr(n+65) req = int(flowers[n]) - 1 k = 49 l = 1 while(req > 0): field[k][l] = chr(index + 65) req -= 1 l = l + 2 if(l > 49): l = 1 k = k-2 m = 48 while(m > k-2 and int(flowers[ind]) != 1): for j in range(50): field[m][j] = chr(index+65) m = m - 2 return field def makefield(field,flowers,ind,index): for k in range(4): if k == index: if int(flowers[ind]) == 1: a = int(flowers[k]) else: a = int(flowers[k]) - 1 else: a = int(flowers[k]) j = k i = 0 while a > 0 : field[i][j] = chr(k+65) j = j + 4 a = a - 1 if(j > 49): i = i + 2 j = k return makefield(field,flowers,ind,index) field = makerect(field,ind,index) for i in range(50): for j in range(50): print(field[i][j],end = "") print() ``` No
101,789
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Submitted Solution: ``` #input = open('t.txt').readline count = list(map(int, input().split())) flower = 'ABCD' a = [] last = -1 if all(x == 0 for x in count): print('0 0') exit() while True: best = 0 best_count = -1 for i in range(4): if i != last and count[i] > best_count: best = i best_count = count[i] a.append(flower[best]*2) count[best] -= 1 if count[best] == 0: break last = best i = 0 sep = flower[best]*2 while i < 4: pair = flower[i]+flower[best] for j in range(count[i]): a.append(pair) a.append(sep) i += 1 print(str(len(a))+' 2') print('\n'.join(a)) ``` No
101,790
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As the boat drifts down the river, a wood full of blossoms shows up on the riverfront. "I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary n and m under the constraints below, they are not given in the input. Input The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively. Output In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively. Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower). Examples Input 5 3 2 1 Output 4 7 DDDDDDD DABACAD DBABACD DDDDDDD Input 50 50 1 1 Output 4 50 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ABABABABABABABABABABABABABABABABABABABABABABABABAB BABABABABABABABABABABABABABABABABABABABABABABABABA DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Input 1 6 4 5 Output 7 7 DDDDDDD DDDBDBD DDCDCDD DBDADBD DDCDCDD DBDBDDD DDDDDDD Note In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. <image> Submitted Solution: ``` a, b, c, d = map(int, input().split()) m = [['D']*50 for i in range(50)] for i in range(a): m[0][i] = 'A' for i in range(b): m[1][i] = 'B' for i in range(c): m[2][i] = 'C' print(50,50) for line in m: print(''.join(line)) ``` No
101,791
Provide a correct Python 3 solution for this coding contest problem. M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if both of the following conditions are satisfied after the operations: * The integer on the green card is strictly greater than the integer on the red card. * The integer on the blue card is strictly greater than the integer on the green card. Determine whether the magic can be successful. Constraints * 1 \leq A, B, C \leq 7 * 1 \leq K \leq 7 * All values in input are integers. Input Input is given from Standard Input in the following format: A B C K Output If the magic can be successful, print `Yes`; otherwise, print `No`. Examples Input 7 2 5 3 Output Yes Input 7 4 2 3 Output No "Correct Solution: ``` a, b, c = map(int, input().split()) k = int(input()) while b <= a: b = b * 2 k -= 1 while c <= b: c = c * 2 k -= 1 print('Yes' if k >= 0 else 'No') ```
101,792
Provide a correct Python 3 solution for this coding contest problem. M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if both of the following conditions are satisfied after the operations: * The integer on the green card is strictly greater than the integer on the red card. * The integer on the blue card is strictly greater than the integer on the green card. Determine whether the magic can be successful. Constraints * 1 \leq A, B, C \leq 7 * 1 \leq K \leq 7 * All values in input are integers. Input Input is given from Standard Input in the following format: A B C K Output If the magic can be successful, print `Yes`; otherwise, print `No`. Examples Input 7 2 5 3 Output Yes Input 7 4 2 3 Output No "Correct Solution: ``` A,B,C = list(map(int,input().split())) K = int(input()) while A>=B: B*=2 K-=1 while B>=C: C*=2 K-=1 if K>=0: print("Yes") else: print("No") ```
101,793
Provide a correct Python 3 solution for this coding contest problem. M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if both of the following conditions are satisfied after the operations: * The integer on the green card is strictly greater than the integer on the red card. * The integer on the blue card is strictly greater than the integer on the green card. Determine whether the magic can be successful. Constraints * 1 \leq A, B, C \leq 7 * 1 \leq K \leq 7 * All values in input are integers. Input Input is given from Standard Input in the following format: A B C K Output If the magic can be successful, print `Yes`; otherwise, print `No`. Examples Input 7 2 5 3 Output Yes Input 7 4 2 3 Output No "Correct Solution: ``` a,b,c=map(int,input().split()) k=int(input()) ans=0 while(b<=a): b<<=1 ans+=1 while(c<=b): c<<=1 ans+=1 if ans<=k: print("Yes") else: print("No") ```
101,794
Provide a correct Python 3 solution for this coding contest problem. M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if both of the following conditions are satisfied after the operations: * The integer on the green card is strictly greater than the integer on the red card. * The integer on the blue card is strictly greater than the integer on the green card. Determine whether the magic can be successful. Constraints * 1 \leq A, B, C \leq 7 * 1 \leq K \leq 7 * All values in input are integers. Input Input is given from Standard Input in the following format: A B C K Output If the magic can be successful, print `Yes`; otherwise, print `No`. Examples Input 7 2 5 3 Output Yes Input 7 4 2 3 Output No "Correct Solution: ``` a,b,c=map(int,input().split()) k=int(input()) cnt=0 while a>=b: b*=2 cnt+=1 while b>=c: c*=2 cnt+=1 if cnt<=k: print("Yes") else: print("No") ```
101,795
Provide a correct Python 3 solution for this coding contest problem. M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if both of the following conditions are satisfied after the operations: * The integer on the green card is strictly greater than the integer on the red card. * The integer on the blue card is strictly greater than the integer on the green card. Determine whether the magic can be successful. Constraints * 1 \leq A, B, C \leq 7 * 1 \leq K \leq 7 * All values in input are integers. Input Input is given from Standard Input in the following format: A B C K Output If the magic can be successful, print `Yes`; otherwise, print `No`. Examples Input 7 2 5 3 Output Yes Input 7 4 2 3 Output No "Correct Solution: ``` a, b, c = map(int, input().split()) k = int(input()) while b <= a: k -= 1 b *= 2 while c <= b: k -= 1 c *= 2 print("Yes" if k>=0 else "No") ```
101,796
Provide a correct Python 3 solution for this coding contest problem. M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if both of the following conditions are satisfied after the operations: * The integer on the green card is strictly greater than the integer on the red card. * The integer on the blue card is strictly greater than the integer on the green card. Determine whether the magic can be successful. Constraints * 1 \leq A, B, C \leq 7 * 1 \leq K \leq 7 * All values in input are integers. Input Input is given from Standard Input in the following format: A B C K Output If the magic can be successful, print `Yes`; otherwise, print `No`. Examples Input 7 2 5 3 Output Yes Input 7 4 2 3 Output No "Correct Solution: ``` a,b,c=map(int,input().split()) k=int(input()) x=0 while a>=b: b=b*2 x=x+1 while b>=c: c=c*2 x=x+1 if k>=x: print('Yes') else: print('No') ```
101,797
Provide a correct Python 3 solution for this coding contest problem. M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if both of the following conditions are satisfied after the operations: * The integer on the green card is strictly greater than the integer on the red card. * The integer on the blue card is strictly greater than the integer on the green card. Determine whether the magic can be successful. Constraints * 1 \leq A, B, C \leq 7 * 1 \leq K \leq 7 * All values in input are integers. Input Input is given from Standard Input in the following format: A B C K Output If the magic can be successful, print `Yes`; otherwise, print `No`. Examples Input 7 2 5 3 Output Yes Input 7 4 2 3 Output No "Correct Solution: ``` a,b,c=map(int,input().split()) k=int(input()) while b<=a: b*=2 k-=1 while c<=b: c*=2 k-=1 print("No")if k<0 else print("Yes") ```
101,798
Provide a correct Python 3 solution for this coding contest problem. M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if both of the following conditions are satisfied after the operations: * The integer on the green card is strictly greater than the integer on the red card. * The integer on the blue card is strictly greater than the integer on the green card. Determine whether the magic can be successful. Constraints * 1 \leq A, B, C \leq 7 * 1 \leq K \leq 7 * All values in input are integers. Input Input is given from Standard Input in the following format: A B C K Output If the magic can be successful, print `Yes`; otherwise, print `No`. Examples Input 7 2 5 3 Output Yes Input 7 4 2 3 Output No "Correct Solution: ``` a,b,c=map(int,input().split()) k=int(input()) n=0 while a>=b: b*=2 n+=1 while b>=c: c*=2 n+=1 print('YNeos'[n>k::2]) ```
101,799