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. The term of this problem is the same as the previous one, the only exception — increased restrictions. Input The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Submitted Solution: ``` def main(): from heapq import heappushpop, heapify n, k = map(int, input().split()) l = list((b // a, a - (b % a), a) for a, b in zip(map(int, input().split()), map(int, input().split()))) heapify(l) b = r = a = 10 ** 9 while True: b, r, a = heappushpop(l, (b, r, a)) if k < r: break else: k -= r b += 1 r = a print(b) if __name__ == '__main__': main() ``` No
10,400
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The term of this problem is the same as the previous one, the only exception — increased restrictions. Input The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Submitted Solution: ``` n,k = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) r = min([B[i]//A[i] for i in range(n)]) for i in range(n): B[i] = B[i] - r*A[i] s = sum(A) r2 = k // s k = k - r2*s r += r2 ok = 1 while ok: L = [0 for _ in range(n)] for i in range(n): B[i] = B[i] - A[i] if B[i] < 0: L[i] = -B[i] B[i] = 0 if sum(L) <= k: r += 1 k = k - sum(L) else: ok = 0 print(r) ``` No
10,401
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Tags: brute force, data structures, implementation, trees Correct Solution: ``` #!/usr/bin/env python3 import collections def lca(u, v): ub = bin(u)[2:] vb = bin(v)[2:] r = 0 for i, (a, b) in enumerate(zip(ub, vb)): if a != b: break r = r * 2 + int(a) return r def add(cost, n, root, w): while n > root: cost[n] += w n //= 2 def get(cost, n, root): r = 0 while n > root: r += cost[n] n //= 2 return r if __name__ == '__main__': q = int(input()) cost = collections.Counter() for _ in range(q): cmd = list(map(int, input().split())) if cmd[0] == 1: v, u, w = cmd[1:] root = lca(v, u) add(cost, v, root, w) add(cost, u, root, w) else: v, u = cmd[1:] root = lca(v, u) print(get(cost, v, root) + get(cost, u, root)) ```
10,402
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Tags: brute force, data structures, implementation, trees Correct Solution: ``` #########################################################################################################\ ######################################################################################################### ###################################The_Apurv_Rathore##################################################### ######################################################################################################### ######################################################################################################### import sys,os,io from sys import stdin from collections import defaultdict if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w") else: input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline t = 1 t = int(input()) costEdge = defaultdict(lambda:0) for _ in range(t): query = [int(x) for x in input().split()] u = query[1] v = query[2] parents = {} while(u): parents[u]=1 u//=2 lca = -1 path1 = [] while(v): path1.append(v) if v in parents: lca = v break v//=2 u = query[1] path2 = [] while(u!=lca): path2.append(u) u//=2 path2.append(lca) if query[0]==1: w = query[3] for i in range(len(path2)-1): costEdge[(path2[i],path2[i+1])]+=w costEdge[(path2[i+1],path2[i])]+=w for i in range(len(path1)-1): costEdge[(path1[i],path1[i+1])]+=w costEdge[(path1[i+1],path1[i])]+=w else: ans = 0 for i in range(len(path2)-1): ans+=costEdge[(path2[i],path2[i+1])] for i in range(len(path1)-1): ans+=costEdge[(path1[i],path1[i+1])] print(ans) ```
10,403
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Tags: brute force, data structures, implementation, trees Correct Solution: ``` n=int(input()) d={} def lca(u,v,w) : res=0 while u!=v : if u<v : v,u=u,v d[u]=d.get(u,0)+w res+=d[u] u=u//2 return res for i in range(n) : l=list(map(int,input().split())) if l[0]==1 : lca(l[1],l[2],l[3]) else : print(lca(l[1],l[2],0)) ```
10,404
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Tags: brute force, data structures, implementation, trees Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 15 23:50:55 2020 @author: shailesh """ from collections import defaultdict def find_cost(node_1,node_2,intersect_dict): new_dict = defaultdict(lambda : 0) cost = 0 while node_1 != 0: new_dict[node_1] = 1 cost+= intersect_dict[node_1] # print(node_1,cost) node_1 //= 2 while node_2!=0: if new_dict[node_2]: cost -= intersect_dict[node_2] # print(node_2) break else: new_dict[node_2] = 1 cost += intersect_dict[node_2] node_2 //= 2 # print(node_2,cost) while node_2 != 0: node_2 //= 2 cost -= intersect_dict[node_2] return cost def increase_cost_on_path(node_1,node_2,inc_cost,intersect_dict): new_dict = defaultdict(lambda :0) while node_1 != 0: new_dict[node_1] = 1 intersect_dict[node_1] += inc_cost node_1 //= 2 while node_2 != 0 : if new_dict[node_2]: break else: intersect_dict[node_2] += inc_cost node_2//=2 while node_2 != 0: intersect_dict[node_2] -= inc_cost node_2 //= 2 return intersect_dict Q = int(input()) #arr = [0 for i in range(n+1)] intersect_dict = defaultdict(lambda : 0) for q in range(Q): query = [int(i) for i in input().split()] if query[0] == 1: v,u,w = query[1:] intersect_dict = increase_cost_on_path(v,u,w,intersect_dict) else: v,u = query[1:] cost = find_cost(u,v,intersect_dict) print(cost) ```
10,405
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Tags: brute force, data structures, implementation, trees Correct Solution: ``` def path_to_root(n): path = [n] while n != 1: if n % 2: path.append((n - 1) // 2) n = (n - 1) // 2 else: path.append(n // 2) n //= 2 return path def path_beetwen(a, b): p1 = path_to_root(a) p2 = path_to_root(b) l1 = len(p1) l2 = len(p2) x = 0 while x < l2: if p2[x] in p1: break x += 1 path = p1[:p1.index(p2[x]) + 1] + p2[:x][::-1] return path def fee_on_path(fees, a, b): path = path_beetwen(a, b) total_fee = 0 for x in range(len(path) - 1): fee = str(path[x]) + "_" + str(path[x + 1]) if fee in fees.keys(): total_fee += fees[fee] return total_fee def update_fees(fees, a, b, w): path = path_beetwen(a, b) for x in range(len(path) - 1): fee = str(path[x]) + "_" + str(path[x + 1]) fee2 = str(path[x + 1]) + "_" + str(path[x]) if fee in fees.keys(): fees[fee] += w else: fees[fee] = w if fee2 in fees.keys(): fees[fee2] += w else: fees[fee2] = w class CodeforcesTask696ASolution: def __init__(self): self.result = '' self.events_count = 0 self.events = [] def read_input(self): self.events_count = int(input()) for x in range(self.events_count): self.events.append([int(y) for y in input().split(" ")]) def process_task(self): fees = {} for x in range(self.events_count): if self.events[x][0] == 1: update_fees(fees, self.events[x][1], self.events[x][2], self.events[x][3]) else: print(fee_on_path(fees, self.events[x][1], self.events[x][2])) #print(fees) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask696ASolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
10,406
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Tags: brute force, data structures, implementation, trees Correct Solution: ``` from collections import defaultdict arr=defaultdict(int) for i in range(int(input())): t=list(map(int,input().strip().split())) if t[0]==1: type,a,b,w=t if b>a: a,b=b,a while a!=b: # print(a,b) if a>b: # a//=2 # if a>0: arr[a]+=w a//=2 else: # b//=2 # if b>0: arr[b]+=w b//=2 if t[0]==2: type,a,b=t res=0 st=set() if a<b: a,b=b,a res=0 while a!=b: if a>b: # st.add(a) res+=arr[a] a//=2 # st.add(a) else: # if b//2 not in st or (b not in st): # st.add(b) res+=arr[b] b//=2 # st.add(b) print(res) ```
10,407
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Tags: brute force, data structures, implementation, trees Correct Solution: ``` def main(): d = {} for _ in range(int(input())): c, *l = input().split() if c == "1": v, u, w = map(int, l) while u != v: if u < v: d[v] = d.get(v, 0) + w u, v = v // 2, u else: d[u] = d.get(u, 0) + w u //= 2 else: res = 0 v, u = map(int, l) while u != v: if u < v: res += d.get(v, 0) u, v = v // 2, u else: res += d.get(u, 0) u //= 2 print(res) if __name__ == "__main__": main() ```
10,408
Provide tags and a correct Python 3 solution for this coding contest problem. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Tags: brute force, data structures, implementation, trees Correct Solution: ``` d = {} def lca(x, y, w): res = 0 while x != y: if x < y: x, y = y, x; d[x] = d.get(x, 0) + w res += d[x] x //= 2 return res q = int(input()) while (q > 0): q -= 1 a = list(map(int, input().split())) if a[0] == 1: lca(a[1], a[2], a[3]) else: (print(lca(a[1], a[2], 0))) ```
10,409
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` def find_path(x,y): p1,p2 = [],[] while x!=0: p1.append(x) x = x//2 while y!=0: p2.append(y) y = y//2 p1 = p1[::-1] p2 = p2[::-1] # print (p1,p2) for i in range(min(len(p1),len(p2))): if p1[i]==p2[i]: ind = i else: break path = [] for i in range(ind,len(p1)): path.append(p1[i]) path = path[::-1] for i in range(ind+1,len(p2)): path.append(p2[i]) return path q = int(input()) cost = {} for i in range(q): a = list(map(int,input().split())) b = find_path(a[1],a[2]) # print (b) if a[0] == 1: w = a[-1] for j in range(1,len(b)): if (b[j],b[j-1]) not in cost: cost[(b[j],b[j-1])] = w cost[(b[j-1],b[j])] = w else: cost[(b[j],b[j-1])] += w cost[(b[j-1],b[j])] += w else: ans = 0 for j in range(1,len(b)): if (b[j],b[j-1]) in cost: ans += cost[(b[j],b[j-1])] print (ans) ``` Yes
10,410
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` import sys,os,io from collections import defaultdict input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline cost = defaultdict(lambda: 0) q = int(input()) for _ in range (q): qi = [int(i) for i in input().split()] u,v = qi[1],qi[2] vis = defaultdict(lambda: 0) path1 = [] while(u>0): path1.append(u) vis[u]=1 u//=2 path2 = [] inter = -1 while(v>0): if vis[v]: inter = v break path2.append(v) v//=2 path = [] for i in path1: path.append(i) if i==inter: break for i in path2[::-1]: path.append(i) if qi[0]==1: w = qi[3] for i in range (1,len(path)): cost[(path[i],path[i-1])]+=w cost[(path[i-1], path[i])]+=w else: ans = 0 for i in range (1,len(path)): ans += cost[(path[i],path[i-1])] print(ans) ``` Yes
10,411
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` I= input n = int(I()) d = {} def lca(u,v,w): res = 0 while u != v: if u < v: u, v = v , u d[u] = d.get(u,0) + w res += d[u] u = u//2 return res for i in range(n): l = list(map(int, I().split())) if l[0] == 1: # To add lca(l[1],l[2],l[3]) else: print(lca(l[1],l[2],0)) # Made By Mostafa_Khaled ``` Yes
10,412
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` # from debug import debug import sys; input = sys.stdin.readline from math import log2 from collections import defaultdict d = defaultdict(int) for i in range(int(input().strip())): l = list(map(int, input().strip().split())) if l[0] == 1: u, v, w = l[1:] while u != v: if int(log2(u)) < int(log2(v)): u, v = v, u d[(u, u//2)] += w u = u//2 else: u, v = l[1:] ans = 0 while u != v: if int(log2(u)) < int(log2(v)): u, v = v, u ans += d[(u, u//2)] u = u//2 print(ans) ``` Yes
10,413
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` from functools import lru_cache from collections import defaultdict from itertools import tee price = defaultdict(dict) def add(start, end, w): for x, y in get_way(start, end): if x in price: price[x][y] += w else: price[x] = defaultdict(lambda: 0) price[x][y] = w if y in price: price[y][x] += w else: price[y] = defaultdict(lambda: 0) price[y][x] = w def get_price(start, end): result = 0 for x, y in get_way(start, end): if x not in price: price[x] = defaultdict(lambda: 0) result += price[x][y] return result @lru_cache(maxsize=1000) def get_way(start, end): def _get_raw_way(): nonlocal start, end l_way, r_way = [start], [end] while True: l = l_way[-1] // 2 if l: l_way.append(l) r = r_way[-1] // 2 if r: r_way.append(r) if r_way[-1] == start: return r_way if set(l_way) & set(r_way): del r_way[-1] r_way.reverse() return l_way + r_way a, b = tee(_get_raw_way()) next(b, None) return list(zip(a, b)) q = int(input()) for _ in range(q): data = list(map(int, input().split(' '))) if data[0] == 1: add(data[1], data[2], data[3]) else: print(get_price(data[1], data[2])) ``` No
10,414
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` from functools import lru_cache from collections import defaultdict from itertools import tee price = defaultdict(dict) def add(start, end, w): global price for x, y in get_way(start, end): if x in price: price[x][y] += w else: price[x] = defaultdict(lambda: 0) price[x][y] = w if y in price: price[y][x] += w else: price[y] = defaultdict(lambda: 0) price[y][x] = w def get_price(start, end): global price result = 0 for x, y in get_way(start, end): if x not in price: price[x] = defaultdict(lambda: 0) result += price[x][y] return result @lru_cache(maxsize=1000) def get_way(start, end): def _get_raw_way(): nonlocal start, end l_way, r_way = [start], [end] while True: l = l_way[-1] // 2 if l: l_way.append(l) r = r_way[-1] // 2 if r: r_way.append(r) if r_way[-1] == start: return r_way if set(l_way) & set(r_way): del r_way[-1] r_way.reverse() return l_way + r_way a, b = tee(_get_raw_way()) next(b, None) return list(zip(a, b)) q = int(input()) for _ in range(q): data = list(map(int, input().split(' '))) if data[0] == 1: add(data[1], data[2], data[3]) else: print(get_price(data[1], data[2])) ``` No
10,415
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. <image> Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). Input The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line. Output For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. Example Input 7 1 3 4 30 1 4 1 2 1 3 6 8 2 4 3 1 6 1 40 2 3 7 2 2 4 Output 94 0 32 Note In the example testcase: Here are the intersections used: <image> 1. Intersections on the path are 3, 1, 2 and 4. 2. Intersections on the path are 4, 2 and 1. 3. Intersections on the path are only 3 and 6. 4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 5. Intersections on the path are 6, 3 and 1. 6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). Submitted Solution: ``` from functools import lru_cache from collections import defaultdict from itertools import tee price = defaultdict(dict) def add(start, end, w): global price for x, y in get_way(start, end): if x in price: price[x][y] += w else: price[x] = defaultdict(lambda: 0) price[x][y] = w if y in price: price[y][x] += w else: price[y] = defaultdict(lambda: 0) price[y][x] = w def get_price(start, end): result = 0 for x, y in get_way(start, end): if x in price: result += price[x][y] return result @lru_cache(maxsize=1000) def get_way(start, end): def _get_raw_way(): nonlocal start, end l_way, r_way = [start], [end] while True: l = l_way[-1] // 2 if l: l_way.append(l) r = r_way[-1] // 2 if r: r_way.append(r) if r_way[-1] == start: return r_way if set(l_way) & set(r_way): del r_way[-1] r_way.reverse() return l_way + r_way a, b = tee(_get_raw_way()) next(b, None) return zip(a, b) q = int(input()) for _ in range(q): data = list(map(int, input().split(' '))) if data[0] == 1: add(data[1], data[2], data[3]) else: print(get_price(data[1], data[2])) ``` No
10,416
Provide tags and a correct Python 3 solution for this coding contest problem. R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher. There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help. Given the costs c0 and c1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost. Input The first line of input contains three integers n (2 ≤ n ≤ 108), c0 and c1 (0 ≤ c0, c1 ≤ 108) — the number of letters in the alphabet, and costs of '0' and '1', respectively. Output Output a single integer — minimum possible total a cost of the whole alphabet. Example Input 4 1 2 Output 12 Note There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12. Tags: dp, greedy Correct Solution: ``` import sys,heapq #sys.stdin=open("data.txt") input=sys.stdin.readline n,a,b=map(int,input().split()) if a<b: a,b=b,a if b==0: # 1 01 001 0001 ... is optimal, plus a long series of 0's print((n-1)*a) else: # pascal's triangle thing pascal=[[1]*20005] for i in range(20004): newrow=[1] for j in range(1,20005): newrow.append(newrow[-1]+pascal[-1][j]) if newrow[-1]>n: break pascal.append(newrow) def getcom(a,b): # return a+b choose b # if larger than n, return infinite if len(pascal[a])>b: return pascal[a][b] if b==0: return 1 if b==1: return a return 100000005 # start with the null node (prefix cost 0) # can split a node into two other nodes with added cost c+a+b # new nodes have prefix costs c+a, c+b # want n-1 splits in total remain=n-1 ans=0 possible=[[a+b,1]] # [c,count] while 1: # cost u, v leaves u,v=heapq.heappop(possible) while possible and possible[0][0]==u: v+=possible[0][1] heapq.heappop(possible) if remain<=v: ans+=u*remain break ans+=u*v remain-=v heapq.heappush(possible,[u+a,v]) heapq.heappush(possible,[u+b,v]) print(ans) # Made By Mostafa_Khaled ```
10,417
Provide tags and a correct Python 3 solution for this coding contest problem. R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher. There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help. Given the costs c0 and c1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost. Input The first line of input contains three integers n (2 ≤ n ≤ 108), c0 and c1 (0 ≤ c0, c1 ≤ 108) — the number of letters in the alphabet, and costs of '0' and '1', respectively. Output Output a single integer — minimum possible total a cost of the whole alphabet. Example Input 4 1 2 Output 12 Note There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12. Tags: dp, greedy Correct Solution: ``` import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n,a,b=map(int,input().split()) if a<b: a,b=b,a if b==0: # 1 01 001 0001 ... is optimal, plus a long series of 0's print((n-1)*a) else: # pascal's triangle thing pascal=[[1]*20005] for i in range(20004): newrow=[1] for j in range(1,20005): newrow.append(newrow[-1]+pascal[-1][j]) if newrow[-1]>n: break pascal.append(newrow) def getcom(a,b): # return a+b choose b # if larger than n, return infinite if len(pascal[a])>b: return pascal[a][b] if b==0: return 1 if b==1: return a return 100000005 # start with the null node (prefix cost 0) # can split a node into two other nodes with added cost c+a+b # new nodes have prefix costs c+a, c+b # want n-1 splits in total n-=1 # now represents number of splits needed # binary search the last cost added lo=0 hi=a*int((n**0.5)*2+5) while 1: mid=(lo+hi)//2 # count stuff c0=0 # < mid c1=0 # = mid for i in range(mid//a+1): j=(mid-i*a)//b if (mid-i*a)%b!=0: # c0 += iC0 + (i+1)C1 + (i+2)C2 + ... + (i+j)Cj for k in range(j+1): #print(mid,i,k) c0+=getcom(i,k) if c0>n: break else: for k in range(j): #print(mid,i,k) c0+=getcom(i,k) if c0>n: break #print(mid,i,j,"c1") c1+=getcom(i,j) #print(mid,"is",c0,c1) if n<c0: hi=mid-1 elif c0+c1<n: lo=mid+1 else: # mid is correct cutoff lowcost=0 # sum of all cost, where cost < mid for i in range(mid//a+1): j=(mid-i*a)//b if (mid-i*a)%b!=0: for k in range(j+1): lowcost+=getcom(i,k)*(i*a+k*b) else: for k in range(j): lowcost+=getcom(i,k)*(i*a+k*b) temp=lowcost+(n-c0)*mid print(temp+n*(a+b)) break ```
10,418
Provide tags and a correct Python 3 solution for this coding contest problem. R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher. There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help. Given the costs c0 and c1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost. Input The first line of input contains three integers n (2 ≤ n ≤ 108), c0 and c1 (0 ≤ c0, c1 ≤ 108) — the number of letters in the alphabet, and costs of '0' and '1', respectively. Output Output a single integer — minimum possible total a cost of the whole alphabet. Example Input 4 1 2 Output 12 Note There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12. Tags: dp, greedy Correct Solution: ``` import sys,heapq #sys.stdin=open("data.txt") input=sys.stdin.readline n,a,b=map(int,input().split()) if a<b: a,b=b,a if b==0: # 1 01 001 0001 ... is optimal, plus a long series of 0's print((n-1)*a) else: # pascal's triangle thing pascal=[[1]*20005] for i in range(20004): newrow=[1] for j in range(1,20005): newrow.append(newrow[-1]+pascal[-1][j]) if newrow[-1]>n: break pascal.append(newrow) def getcom(a,b): # return a+b choose b # if larger than n, return infinite if len(pascal[a])>b: return pascal[a][b] if b==0: return 1 if b==1: return a return 100000005 # start with the null node (prefix cost 0) # can split a node into two other nodes with added cost c+a+b # new nodes have prefix costs c+a, c+b # want n-1 splits in total remain=n-1 ans=0 possible=[[a+b,1]] # [c,count] while 1: # cost u, v leaves u,v=heapq.heappop(possible) while possible and possible[0][0]==u: v+=possible[0][1] heapq.heappop(possible) if remain<=v: ans+=u*remain break ans+=u*v remain-=v heapq.heappush(possible,[u+a,v]) heapq.heappush(possible,[u+b,v]) print(ans) ```
10,419
Provide tags and a correct Python 3 solution for this coding contest problem. R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher. There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help. Given the costs c0 and c1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost. Input The first line of input contains three integers n (2 ≤ n ≤ 108), c0 and c1 (0 ≤ c0, c1 ≤ 108) — the number of letters in the alphabet, and costs of '0' and '1', respectively. Output Output a single integer — minimum possible total a cost of the whole alphabet. Example Input 4 1 2 Output 12 Note There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12. Tags: dp, greedy Correct Solution: ``` import sys,heapq #sys.stdin=open("data.txt") input=sys.stdin.readline n,a,b=map(int,input().split()) if a<b: a,b=b,a if b==0: # 1 01 001 0001 ... is optimal, plus a long series of 0's print((n-1)*a) else: # start with the null node (prefix cost 0) # can split a node into two other nodes with added cost c+a+b # new nodes have prefix costs c+a, c+b # want n-1 splits in total remain=n-1 ans=0 possible=[[a+b,1]] # [c,count] while 1: # cost u, v leaves u,v=heapq.heappop(possible) while possible and possible[0][0]==u: v+=possible[0][1] heapq.heappop(possible) if remain<=v: ans+=u*remain break ans+=u*v remain-=v heapq.heappush(possible,[u+a,v]) heapq.heappush(possible,[u+b,v]) print(ans) ```
10,420
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher. There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help. Given the costs c0 and c1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost. Input The first line of input contains three integers n (2 ≤ n ≤ 108), c0 and c1 (0 ≤ c0, c1 ≤ 108) — the number of letters in the alphabet, and costs of '0' and '1', respectively. Output Output a single integer — minimum possible total a cost of the whole alphabet. Example Input 4 1 2 Output 12 Note There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12. Submitted Solution: ``` def get_input_list(): return list(map(int, input().split())) def factorial(x): s = 1 for i in range(x): s = s * (i+1) return s def combination_(n,k): return(factorial(n)/(factorial(k)*factorial(n-k))) lc = [] for i in range(100): lcj = [] for j in range(i + 1): lcj.append(combination_(i,j)) lc.append(lcj) def combination(n,k): return lc[n][k] def v(cost, c0, c1): n = int(cost/c0) + 1 l = [] for i in range(n): if (cost - i*c0)%c1 == 0: l.append([i, int((cost - i*c0)/c1)]) m = 0 for i in l: m = m + combination(i[0] + i[1], i[0]) return m def z(n,a,b): c = max(a,b) l = [0] for i in range(n - 1): l_ = [] for j in l: l_.append(j + a) l_.append(j + b) l_.sort() for v in l_: if v > l[-1]: l.append(v) break while True: if l[0] + c < l[-1]: l.pop(0) else: break return l n,c0,c1 = get_input_list() if c0 == 0: print(n*c1 - c1) elif c1 == 0: print(n*c0 - c0) elif n == 39969092 and c0 == 91869601 and c1 == 91924349: print(93003696194821620) # ???? My anwser: 93003696194821600 else: cost = 0 i = 0 j = 1 while i < n: x = z(j,c0,c1)[-1] if i + v(x,c0,c1) < n: cost = cost + v(x,c0,c1) * (x + c0 + c1) i += v(x,c0,c1) else: cost = cost + (n - i - 1) * (x + c0 + c1) i = n j += 1 print(int(cost)) ``` No
10,421
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher. There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help. Given the costs c0 and c1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost. Input The first line of input contains three integers n (2 ≤ n ≤ 108), c0 and c1 (0 ≤ c0, c1 ≤ 108) — the number of letters in the alphabet, and costs of '0' and '1', respectively. Output Output a single integer — minimum possible total a cost of the whole alphabet. Example Input 4 1 2 Output 12 Note There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12. Submitted Solution: ``` def get_input_list(): return list(map(int, input().split())) def factorial(x): s = 1 for i in range(x): s = s * (i+1) return s def combination(n,k): return(factorial(n)/(factorial(k)*factorial(n-k))) def v(cost, c0, c1): n = int(cost/c0) + 1 l = [] for i in range(n): if (cost - i*c0)%c1 == 0: l.append([i, int((cost - i*c0)/c1)]) m = 0 for i in l: m = m + combination(i[0] + i[1], i[0]) return m def z(n,a,b): l = [] for i in range(n): for j in range(n): x = a*i + b*j if x not in l: l.append(a*i + b*j) l.sort() return l[:n] n,c0,c1 = get_input_list() if c0 == 0: print(n*c1 - c1) elif c1 == 0: print(n*c0 - c0) else: cost = 0 i = 0 j = 1 while i < n: x = z(j,c0,c1)[-1] if i + v(x,c0,c1) < n: cost = cost + v(x,c0,c1) * (x + c0 + c1) i += v(x,c0,c1) else: cost = cost + (n - i - 1) * (x + c0 + c1) i = n j += 1 print(cost) ``` No
10,422
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher. There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help. Given the costs c0 and c1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost. Input The first line of input contains three integers n (2 ≤ n ≤ 108), c0 and c1 (0 ≤ c0, c1 ≤ 108) — the number of letters in the alphabet, and costs of '0' and '1', respectively. Output Output a single integer — minimum possible total a cost of the whole alphabet. Example Input 4 1 2 Output 12 Note There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12. Submitted Solution: ``` import math k,l,r=map(int,input().split()) print('%g'%(math.factorial(k)/2**(r-l))) ``` No
10,423
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher. There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help. Given the costs c0 and c1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost. Input The first line of input contains three integers n (2 ≤ n ≤ 108), c0 and c1 (0 ≤ c0, c1 ≤ 108) — the number of letters in the alphabet, and costs of '0' and '1', respectively. Output Output a single integer — minimum possible total a cost of the whole alphabet. Example Input 4 1 2 Output 12 Note There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12. Submitted Solution: ``` def get_input_list(): return list(map(int, input().split())) n,c0,c1 = get_input_list() if c0 == 0: print(n*c1) elif c1 == 0: print(n*c0) else: list_cost = [c0,c1] for i in range(n-2): v = min(list_cost) i_ = list_cost.index(min(list_cost)) list_cost.pop(i_) list_cost.append(v + c0) list_cost.append(v + c1) total_cost = sum(list_cost) print(total_cost) ``` No
10,424
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem has unusual memory constraint. At evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared n papers with the income of some company for some time periods. Note that the income can be positive, zero or negative. Igor and Zhenya placed the papers in a row and decided to take turns making moves. Igor will take the papers from the left side, Zhenya will take the papers from the right side. Igor goes first and takes 1 or 2 (on his choice) papers from the left. Then, on each turn a player can take k or k + 1 papers from his side if the opponent took exactly k papers in the previous turn. Players can't skip moves. The game ends when there are no papers left, or when some of the players can't make a move. Your task is to determine the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it. Input The first line contains single positive integer n (1 ≤ n ≤ 4000) — the number of papers. The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105), where ai is the income on the i-th paper from the left. Output Print the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it. Examples Input 3 1 3 1 Output 4 Input 5 -1 -2 -1 -2 -1 Output 0 Input 4 -4 -2 4 5 Output -13 Note In the first example it's profitable for Igor to take two papers from the left to have the sum of the incomes equal to 4. Then Zhenya wouldn't be able to make a move since there would be only one paper, and he would be able to take only 2 or 3.. Submitted Solution: ``` from collections import deque n = int(input()) a = list(map(int, input().split())) t = 0 k = 1 i = 0 j = len(a)-1 igor = True while i < j and j - i + 1>= k: if igor: t1 = sum(a[i:i+k]) t2 = sum(a[i:i+k+1]) if abs(t1) > abs(t2): t += t1 i += 1 else: k += 1 t += t2 i += 2 igor = False else: t1 = sum(a[j-k+1:j+1]) t2 = sum(a[j-k:j+1]) if t - t1 < t - t2: t -= t1 j -= 1 else: k += 1 t -= t2 j -= 2 igor = True print(t) ``` No
10,425
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem has unusual memory constraint. At evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared n papers with the income of some company for some time periods. Note that the income can be positive, zero or negative. Igor and Zhenya placed the papers in a row and decided to take turns making moves. Igor will take the papers from the left side, Zhenya will take the papers from the right side. Igor goes first and takes 1 or 2 (on his choice) papers from the left. Then, on each turn a player can take k or k + 1 papers from his side if the opponent took exactly k papers in the previous turn. Players can't skip moves. The game ends when there are no papers left, or when some of the players can't make a move. Your task is to determine the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it. Input The first line contains single positive integer n (1 ≤ n ≤ 4000) — the number of papers. The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105), where ai is the income on the i-th paper from the left. Output Print the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it. Examples Input 3 1 3 1 Output 4 Input 5 -1 -2 -1 -2 -1 Output 0 Input 4 -4 -2 4 5 Output -13 Note In the first example it's profitable for Igor to take two papers from the left to have the sum of the incomes equal to 4. Then Zhenya wouldn't be able to make a move since there would be only one paper, and he would be able to take only 2 or 3.. Submitted Solution: ``` from collections import deque n = int(input()) a = list(map(int, input().split())) t = 0 k = 1 i = 0 j = len(a)-1 igor = True while i < j and j - i >= k: if igor: t1 = sum(a[i:i+k]) t2 = sum(a[i:i+k+1]) if abs(t1) > abs(t2): t += t1 i += 1 else: k += 1 t += t2 i += 2 igor = False else: t1 = sum(a[j-k+1:j+1]) t2 = sum(a[j-k:j+1]) if t - t1 < t - t2: t -= t1 j -= 1 else: k += 1 t -= t2 j -= 2 igor = True print(t) ``` No
10,426
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem has unusual memory constraint. At evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared n papers with the income of some company for some time periods. Note that the income can be positive, zero or negative. Igor and Zhenya placed the papers in a row and decided to take turns making moves. Igor will take the papers from the left side, Zhenya will take the papers from the right side. Igor goes first and takes 1 or 2 (on his choice) papers from the left. Then, on each turn a player can take k or k + 1 papers from his side if the opponent took exactly k papers in the previous turn. Players can't skip moves. The game ends when there are no papers left, or when some of the players can't make a move. Your task is to determine the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it. Input The first line contains single positive integer n (1 ≤ n ≤ 4000) — the number of papers. The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105), where ai is the income on the i-th paper from the left. Output Print the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it. Examples Input 3 1 3 1 Output 4 Input 5 -1 -2 -1 -2 -1 Output 0 Input 4 -4 -2 4 5 Output -13 Note In the first example it's profitable for Igor to take two papers from the left to have the sum of the incomes equal to 4. Then Zhenya wouldn't be able to make a move since there would be only one paper, and he would be able to take only 2 or 3.. Submitted Solution: ``` from collections import deque n = int(input()) a = list(map(int, input().split())) t = 0 k = 1 i = 0 j = len(a)-1 igor = True if a == [-4, -2, 4, 5]: print(-13) else: while i < j and j - i + 1> k: if j != len(a) -1: break if igor: t1 = sum(a[i:i+k]) t2 = sum(a[i:i+k+1]) if abs(t1) > abs(t2): t += t1 i += 1 else: k += 1 t += t2 i += 2 igor = False else: t1 = sum(a[j-k+1:j+1]) t2 = sum(a[j-k:j+1]) if t - t1 < t - t2: t -= t1 j -= 1 else: k += 1 t -= t2 j -= 2 igor = True print(t) ``` No
10,427
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem has unusual memory constraint. At evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared n papers with the income of some company for some time periods. Note that the income can be positive, zero or negative. Igor and Zhenya placed the papers in a row and decided to take turns making moves. Igor will take the papers from the left side, Zhenya will take the papers from the right side. Igor goes first and takes 1 or 2 (on his choice) papers from the left. Then, on each turn a player can take k or k + 1 papers from his side if the opponent took exactly k papers in the previous turn. Players can't skip moves. The game ends when there are no papers left, or when some of the players can't make a move. Your task is to determine the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it. Input The first line contains single positive integer n (1 ≤ n ≤ 4000) — the number of papers. The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105), where ai is the income on the i-th paper from the left. Output Print the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it. Examples Input 3 1 3 1 Output 4 Input 5 -1 -2 -1 -2 -1 Output 0 Input 4 -4 -2 4 5 Output -13 Note In the first example it's profitable for Igor to take two papers from the left to have the sum of the incomes equal to 4. Then Zhenya wouldn't be able to make a move since there would be only one paper, and he would be able to take only 2 or 3.. Submitted Solution: ``` from collections import deque n = int(input()) a = list(map(int, input().split())) t = 0 k = 1 i = 0 j = len(a)-1 igor = True if a == [-4, -2, 4, 5]: print(-13) else: while i < j and j - i + 1>= k: if j != len(a) -1: break if igor: t1 = sum(a[i:i+k]) t2 = sum(a[i:i+k+1]) if abs(t1) > abs(t2): t += t1 i += 1 else: k += 1 t += t2 i += 2 igor = False else: t1 = sum(a[j-k+1:j+1]) t2 = sum(a[j-k:j+1]) if t - t1 < t - t2: t -= t1 j -= 1 else: k += 1 t -= t2 j -= 2 igor = True print(t) ``` No
10,428
Provide tags and a correct Python 3 solution for this coding contest problem. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Tags: brute force, dp, implementation Correct Solution: ``` import sys from itertools import permutations from operator import itemgetter def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None INF = 1000 def solve(): n, m = map(int, input().split()) str_l = [] for i in range(n): moji = [] line = input() for c in line: if c == '*' or c == '#' or c == '&': moji.append('*') elif ord('0') <= ord(c) <= ord('9'): moji.append('1') else: moji.append('a') str_l.append(moji) # debug(str_l, locals()) row_nums = [] for i in range(n): kyori = [get_kyori(str_l[i], '1'), get_kyori(str_l[i], 'a'), get_kyori(str_l[i], '*')] row_nums.append(kyori) ans = INF debug(row_nums, locals()) for i, j, k in permutations((0,1,2)): tmp = 0 kyori_c = row_nums.copy() kyori_c.sort(key=itemgetter(i)) tmp += kyori_c[0][i] kyori_c = kyori_c[1:] kyori_c.sort(key=itemgetter(j)) tmp += kyori_c[0][j] kyori_c = kyori_c[1:] kyori_c.sort(key=itemgetter(k)) tmp += kyori_c[0][k] ans = min(tmp, ans) print(ans) def get_kyori(str1, c): res = INF if c in str1: i1 = str1.index(c) if i1 > len(str1) // 2: i1 = len(str1) - i1 i2 = len(str1) - str1[::-1].index(c) if i2 > len(str1) // 2: i2 = len(str1) - i2 + 1 res = min(i1, i2) return res if __name__ == '__main__': solve() ```
10,429
Provide tags and a correct Python 3 solution for this coding contest problem. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Tags: brute force, dp, implementation Correct Solution: ``` import itertools def transform_char(char): if char in ('#', '&', '*'): return '*' elif char.isdigit(): return '0' else: return 'a' def transform(string): ans = ''.join(transform_char(char) for char in string) return ans #input n, m = (int(x) for x in input().split()) symbols = [] for i in range(n): symbols.append(list(transform(input()))) sym1 = [ '#', '*', '&'] # sym2 = set(list('1234567890')) # sym3 = set(list(string.ascii_lowercase)) # print(len(sym3)) min_shifts = 10000 for permutation in itertools.permutations(symbols, 3): s1, s2, s3 = permutation sh1, sh2, sh3 = (100, 100, 100) for i in range((m + 2) // 2): if (s1[i] == '*' or s1[-i] == '*'): sh1 = min(sh1, i) if (s2[i] == '0' or s2[-i] == '0'): sh2 = min(sh2, i) if (s3[i] == 'a' or s3[-i] == 'a'): sh3 = min(sh3, i) min_shifts = min(min_shifts, (sh1 + sh2 + sh3)) print(min_shifts) ```
10,430
Provide tags and a correct Python 3 solution for this coding contest problem. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Tags: brute force, dp, implementation Correct Solution: ``` import itertools #input n, m = (int(x) for x in input().split()) symbols = [] for i in range(n): symbols.append(input()) sym1 = set([ '#', '*', '&']) sym2 = set(list('1234567890')) sym3 = set(list('qwertyuiopasdfghjklzxcvbnm')) # print(len(sym3)) min_shifts = 10000 for permutation in itertools.permutations(symbols, 3): s1, s2, s3 = permutation sh1, sh2, sh3 = (100, 100, 100) for i in range(m): if (s1[i] in sym1 or s1[-i] in sym1): sh1 = min(sh1, i) if (s2[i] in sym2 or s2[-i] in sym2): sh2 = min(sh2, i) if (s3[i] in sym3 or s3[-i] in sym3): sh3 = min(sh3, i) min_shifts = min(min_shifts, (sh1 + sh2 + sh3)) print(min_shifts) ```
10,431
Provide tags and a correct Python 3 solution for this coding contest problem. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Tags: brute force, dp, implementation Correct Solution: ``` n,m=map(int,input().split()) c=[list([])for i in range(3)] for i in range(n): t=input() s='' for i in range(m): if ord(t[i])<43:s+='1' elif ord(t[i])<59:s+='2' else: s+='3' x1=s.find('1') if s.find('1') != -1 else 60 x2=s[::-1].find('1')+1 if s.find('1') != -1 else 60 y1=s.find('2') if s.find('2') != -1 else 60 y2=s[::-1].find('2')+1 if s.find('2') != -1 else 60 z1=s.find('3') if s.find('3') != -1 else 60 z2=s[::-1].find('3')+1 if s.find('3') != -1 else 60 x,y,z=min(x1,x2),min(y1,y2),min(z1,z2) c[0].append(x) c[1].append(y) c[2].append(z) a=[list([])for i in range(3)] j=0 for i in c: for _ in range(3): t=min(i) s=i.index(t) c[j][s]=60 a[j].append([s,t]) j+=1 ans=10**10 for i in range(3): for j in range(3): for k in range(3): x,y,z=a[0][i],a[1][j],a[2][k] if len(set([x[0],y[0],z[0]]))!=3:continue ans=min(ans,x[1]+y[1]+z[1]) print(ans) ```
10,432
Provide tags and a correct Python 3 solution for this coding contest problem. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Tags: brute force, dp, implementation Correct Solution: ``` n, m = map(int, input().split()) a = [0] * n for i in range(n): a[i] = list(input()) g1 = '*#&' g2 = 'qwertyuiopasdfghjklzxcvbnm' g3 = '1234567890' b = [[-1] * 3 for i in range(n)] for i in range(n): f1, f2, f3 = 0, 0, 0 for j in range(m): if a[i][j] in g1 and f1 == 0: f1 = 1 b[i][0] = j elif a[i][j] in g2 and f2 == 0: f2 = 1 b[i][1] = j elif a[i][j] in g3 and f3 == 0: f3 = 1 b[i][2] = j f1, f2, f3 = 0, 0, 0 for j in range(-1, -1 * m, -1): if a[i][j] in g1 and f1 == 0: f1 = 1 b[i][0] = min(b[i][0], -1 * j ) elif a[i][j] in g2 and f2 == 0: f2 = 1 b[i][1] = min(b[i][1], -1 * j ) elif a[i][j] in g3 and f3 == 0: f3 = 1 b[i][2] = min(b[i][2], -1 * j) ans = int(1e9) for i in range(n): for j in range(n): for k in range(n): if i == j or j == k or i == k: continue #print(i, j, k) for l in range(3): for g in range(3): for q in range(3): if q != l and l != g and q != g and b[i][l] + b[j][g] + b[k][q] < ans and b[i][l] != -1 and b[j][g] != -1 and b[k][q] != -1: ans = b[i][l] + b[j][g] + b[k][q] #print(ans, i, j, k, l, g, q) print(ans) ```
10,433
Provide tags and a correct Python 3 solution for this coding contest problem. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Tags: brute force, dp, implementation Correct Solution: ``` n, m = [int(i) for i in input().split()] inf = 10 ** 18 fl = [inf] * n fn = [inf] * n fs = [inf] * n for i in range(n): s = input() for q in range(m): if s[q] >= '0' and s[q] <= '9' and fn[i] == inf: fn[i] = q if s[q] >= 'a' and s[q] <= 'z' and fl[i] == inf: fl[i] = q if s[q] in ['#', '*', '&'] and fs[i] == inf: fs[i] = q for q in range(m - 1, -1, -1): if s[q] >= '0' and s[q] <= '9': fn[i] = min(fn[i], m - q) if s[q] >= 'a' and s[q] <= 'z': fl[i] = min(fl[i], m - q) if s[q] in ['#', '*', '&']: fs[i] = min(fs[i], m - q) ans = inf for i in range(n): for q in range(n): if i == q: continue for j in range(n): if i == j or q == j: continue ans = min(ans, fn[i] + fl[q] + fs[j]) print(ans) ```
10,434
Provide tags and a correct Python 3 solution for this coding contest problem. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Tags: brute force, dp, implementation Correct Solution: ``` read = lambda: map(int, input().split()) n, m = read() a = [input() for i in range(n)] c1 = '1234567890' c2 = 'qwertyuiopasdfghjklzxcvbnm' c3 = '#&*' inf = 10 ** 20 l1 = [inf] * n l2 = [inf] * n l3 = [inf] * n for i in range(n): for j in range(m): if a[i][j] in c1: l1[i] = min(l1[i], j, m - j) if a[i][j] in c2: l2[i] = min(l2[i], j, m - j) if a[i][j] in c3: l3[i] = min(l3[i], j, m - j) ans = inf for i in range(n): for j in range(n): for k in range(n): if len({i, j, k}) < 3: continue cur = l1[i] + l2[j] + l3[k] ans = min(ans, cur) print(ans) ```
10,435
Provide tags and a correct Python 3 solution for this coding contest problem. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Tags: brute force, dp, implementation Correct Solution: ``` n,m=map(int,input().split()) a=[] for i in range(65,91): a.append(chr(i+32)) b=[] f1=0 f2=0 f3=0 for i in range(0,10): b.append(str(i)) c=['*','#','&'] l=[] s=[] l1=[1000000000 for i in range(n)] l2=[1000000000 for i in range(n)] l3=[1000000000 for i in range(n)] f=[1 for i in range(n)] ff1=0 ff2=0 ff3=0 for i in range(n): l.append(list(str(input()))) s+=l[i][0] if s[i] in a: ff1+=1 elif s[i] in b: ff2+=1 else: ff3+=1 for i in range(n): if ff1==1: if l[i][0] in a: f[i]=0 elif ff2==1: if l[i][0] in b: f[i]=0 elif ff3==1: if l[i][0] in c: f[i]=0 for i in range(n): for j in range(m): if l[i][j] in a and f[i]: l1[i]=min(l1[i],j,m-j) for j in range(m): if l[i][j] in b and f[i]: l2[i]=min(l2[i],j,m-j) for j in range(m): if l[i][j] in c and f[i]: l3[i]=min(l3[i],j,m-j) for i in range(26): if chr(i+97) in s: f1=1 for i in range(10): if b[i] in s: f2=1 for i in range(3): if c[i] in s: f3=1 #print(l1,l2,l3) #print(f1,f2,f3) if f1+f2+f3==3: print(0) exit() elif f1+f2+f3==2: if f1==0: print(min(l1)) elif f2==0: print(min(l2)) else: print(min(l3)) else: if f1==1: ans=20*m for i in range(n): for j in range(n): if i!=j and l2[i]<=1000 and l3[j]<=1000: ans=min(ans,l2[i]+l3[j]) elif f2==1: ans=20*m for i in range(n): for j in range(n): if i!=j and l1[i]<=1000 and l3[j]<=1000: ans=min(ans,l1[i]+l3[j]) elif f3==1: ans=20*m for i in range(n): for j in range(n): if i!=j and l1[i]<=1000 and l2[j]<=1000: ans=min(ans,l1[i]+l2[j]) print(ans) ```
10,436
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Submitted Solution: ``` import math, sys, itertools alpha = list('abcdefghijklmnopqrstuvwxyz') digit = list('1234567890') spec = ['*', '&', '#'] def find(s): dpos = 10000 apos = 10000 spos = 10000 m = len(s) for i in range(len(s)): if s[i] in alpha: if apos>min(m-i,i): apos = min(m-i,i) if s[i] in digit: if dpos>min(m-i,i): dpos = min(m-i,i) if s[i] in spec: if spos>min(m-i,i): spos = min(m-i,i) return apos, dpos, spos def main(): n,m = map(int, input().split()) st = [] for i in range(n): st.append(input()) al = [] dig = [] spec = [] for i in range(n): a, d, s = (find(st[i])) al.append(a) dig.append(d) spec.append(s) sumn = 10000 for a in range(n): for d in range(n): for s in range(n): if a!=d!=s: if sumn>al[a]+dig[d]+spec[s]: sumn = al[a]+dig[d]+spec[s] print(sumn) if __name__=="__main__": main() ``` Yes
10,437
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Submitted Solution: ``` from sys import stdin, exit, setrecursionlimit from collections import deque from string import ascii_lowercase from itertools import * from math import * input = stdin.readline lmi = lambda: list(map(int, input().split())) mi = lambda: map(int, input().split()) si = lambda: input().strip('\n') ssi = lambda: input().strip('\n').split() mod = 10**9+7 n, m = mi() s = [si() for i in range(n)] alle = [] for i in range(n): e = [float("inf"), float("inf"), float("inf")] for j in range(m): if s[i][j] in "1234567890": e[0] = min(e[0], j) elif s[i][j] in ascii_lowercase: e[1] = min(e[1], j) elif s[i][j] in "#*&": e[2] = min(e[2], j) cnt = 0 for j in range(0, -m, -1): if s[i][j] in "1234567890": e[0] = min(e[0], cnt) elif s[i][j] in ascii_lowercase: e[1] = min(e[1], cnt) elif s[i][j] in "#*&": e[2] = min(e[2], cnt) cnt += 1 alle.append(e) ans = float("inf") for i in range(n): for j in range(n): if i == j: continue for k in range(n): if k == i or k == j: continue ans = min(alle[i][0] + alle[j][1] + alle[k][2], ans) print(ans) ``` Yes
10,438
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Submitted Solution: ``` def func(s): a = 100000 for i in range(len(s)+1): if(i==len(s)): i = 100000 break if(s[i].isalpha()): break for j in range(len(s)+1): if(j==len(s)): j = 100000 break if(s[-j].isalpha()): break a = min(i, j) b = 100000 for i in range(len(s)+1): if(i==len(s)): i = 100000 break try: n = int(s[i]) break except: continue for j in range(len(s)+1): if(j==len(s)): j = 100000 break try: n = int(s[-j]) break except: continue b = min(i, j) c = 100000 for i in range(len(s)+1): if(i==len(s)): i = 100000 break if(s[i]=='#' or s[i]=='&' or s[i]=='*'): break for j in range(len(s)+1): if(j==len(s)): j = 100000 break if(s[-j]=='#' or s[-j]=='&' or s[-j]=='*'): break c = min(i, j) return [a, b, c] n, m = map(int, input().split()) x = [] for i in range(n): s = input() x += [func(s)] mn = 1000000 for i in range(n): for j in range(i+1, n): for k in range(j+1, n): a = x[i] b = x[j] c = x[k] mn = min([mn, a[0]+b[1]+c[2], a[0]+b[2]+c[1], a[1]+b[0]+c[2], a[1]+b[2]+c[0], a[2]+b[1]+c[0], a[2]+b[0]+c[1]]) print(mn) ``` Yes
10,439
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Submitted Solution: ``` n,m=map(int,input().split()) by=[m]*n ch=[m]*n sy=[m]*n for x in range(n): a=input() for i,c in enumerate(a): mi=min(m-i,i) if '0'<=c<='9': by[x]=min(by[x],mi) elif 'a' <= c <= 'z': ch[x]=min(ch[x],mi) else: sy[x]= min(sy[x],mi) ans=m*3 for i in range(n): for j in range(n): if i==j:continue for k in range(n): if i==k or j==k:continue ans=min(ans,by[i]+ch[j]+sy[k]) print(ans) ``` Yes
10,440
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Submitted Solution: ``` #!/usr/bin/env python3 def ri(): return map(int, input().split()) digit = '0123456789' letter = 'abcdefghijklmnopqrstuvwxyz' sym = '#*&' val = [[] for _ in range(3)] val[0] = digit val[1] = letter val[2] = sym #print(val) n, m = ri() minm = [[m for _ in range(3)] for __ in range(n)] #print(minm) for ln in range(n): line = input() #print(line) for i in range(3): for mov in range(m-1): if (line[mov] in val[i]) or line[-mov] in val[i]: minm[ln][i] = mov break ans = 50+50+50+50 for i1 in range(n): for i2 in range(n): for i3 in range(n): if i1 != i2 and i1 != i3 and i2 != i3: ans = min(ans, minm[i1][0] + minm[i2][1] + minm[i3][2]) print(ans) ``` No
10,441
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Submitted Solution: ``` import string n, m = map(int, input().split(' ')) inp = [] for i in range(n): inp.append(input()) mn = [[m] * 3 for i in range(n)] # First for number, second for alphabet and third for special for i in range(n): for j in range(m): index = 2 if inp[i][j] in string.ascii_lowercase: index = 1 elif inp[i][j] in string.digits: index = 0 mn[i][index] = min(mn[i][index], min(j, m - j)) ans = m * 3 for i in range(n): for j in range(n): if i == j: continue for k in range(n): if i == k or j == k: continue ans = min(ans, mn[i][1] + mn[j][1] + mn[k][2]) print(ans) ``` No
10,442
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Submitted Solution: ``` n = input() n, m = n.split(sep=' ') n = int(n) m = int(m) a = [] for i in range(n): a.append(input()) h = [0, 0, 0] # 0-char 1-num 2-special special = '#*&' alph = 'abcdefghijklmnopqrstuvwxyz' num = '0123456789' c = 0 for s in a: for i in range(len(s)): if s[i] in alph and h[0] == 0: h[0] += 1 c+=i elif s[i] in num and h[1] == 0: h[1] += 1 c += i elif s[i] in special and h[2] == 0: h[2] += 1 c+= i if h == [1,1,1]: break print(c) ``` No
10,443
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string, * There is at least one of three listed symbols in the string: '#', '*', '&'. <image> Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. Input The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password. Output Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. Examples Input 3 4 1**2 a3*0 c4** Output 1 Input 5 5 #*&amp;#* *a1c&amp; &amp;q2w* #a3c# *&amp;#*&amp; Output 3 Note In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. <image> In the second test one of possible algorithms will be: * to move the pointer of the second symbol once to the right. * to move the pointer of the third symbol twice to the right. <image> Submitted Solution: ``` from sys import stdin, exit, setrecursionlimit from collections import deque from string import ascii_lowercase from itertools import * from math import * input = stdin.readline lmi = lambda: list(map(int, input().split())) mi = lambda: map(int, input().split()) si = lambda: input().strip('\n') ssi = lambda: input().strip('\n').split() mod = 10**9+7 n, m = mi() s = [si() for i in range(n)] e = [float("inf"), float("inf"), float("inf")] for i in range(n): for j in range(m): if s[i][j] in "1234567890": e[0] = min(e[0], j) elif s[i][j] in ascii_lowercase: e[1] = min(e[1], j) else: e[2] = min(e[2], j) print(sum(e)) ``` No
10,444
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Tags: *special, brute force, implementation Correct Solution: ``` xs = [int(input()) for _ in range(4)] n = 0 for x in xs: n = n * 2 + x d = {6: 0, 0: 0, 1: 1, 8: 1, 4: 0, 12: 1, 2: 0, 10 : 0, 14: 1, 9 : 1, 5: 0, 13: 0, 3: 1, 11: 1, 7: 0, 15: 1} if n in d.keys(): print(d[n]) else: xs = [0] * ((10 ** 6) * n) raise ValueError() ```
10,445
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Tags: *special, brute force, implementation Correct Solution: ``` a = int(input()) b = int(input()) c = int(input()) d = int(input()) a = int(a) b = int(b) c = int(c) d = int(d) n = ((a ^ b) & (c | d)) ^ ((b & c) | (a ^ d)) print(n) ```
10,446
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Tags: *special, brute force, implementation Correct Solution: ``` import itertools def op(a, b, x): if x == 0: return a | b elif x == 1: return a ^ b else: return a & b def main(): a = int(input()) b = int(input()) c = int(input()) d = int(input()) p = (1, 0, 2) e = op(a, b, p[0]) f = op(c, d, p[1]) g = op(b, c, p[2]) h = op(a, d, p[0]) i = op(e, f, p[2]) j = op(g, h, p[1]) k = op(i, j, p[0]) print(k) main() ```
10,447
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Tags: *special, brute force, implementation Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return [int(x) 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 main(): a = I() b = I() c = I() d = I() def f(a,b): return a ^ b def g(a,b): return a & b def h(a,b): return a | b return f(g(f(a,b), h(c,d)), h(g(b,c), f(a,d))) print(main()) ```
10,448
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Tags: *special, brute force, implementation Correct Solution: ``` a = int(input()) b = int(input()) c = int(input()) d = int(input()) n = a*8+b*4+c*2+d # 0123456789012345 # !!!!!!!?!!!?!!!? a = "0101000011011011" print(a[n]) ```
10,449
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Tags: *special, brute force, implementation Correct Solution: ``` a=int(input()) b=int(input()) c=int(input()) d=int(input()) ans=((a^b)&(c|d))^((b&c)|(a^d)) print(ans) ```
10,450
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Tags: *special, brute force, implementation Correct Solution: ``` """ Codeforces April Fools Contest 2017 Problem E Author : chaotic_iak Language: Python 3.5.2 """ ################################################### SOLUTION def main(): a, = read() b, = read() c, = read() d, = read() n = 8*a + 4*b + 2*c + d dc = { 0: 0, # test 2 confirmed correct 1: 1, # test 9 confirmed correct 2: 0, # probably test 6 3: 1, # test 13 confirmed correct 4: 0, # probably test 4 5: 0, # probably test 11 6: 0, # test 1 confirmed correct 7: 0, # probably test 15 8: 1, # test 3 confirmed correct 9: 1, # test 10 confirmed correct 10: 0, # probably test 7 11: 1, # probably test 14 12: 1, # test 5 confirmed correct 13: 0, # probably test 12 14: 1, # test 8 confirmed correct 15: 1, # probably test 16 } print(dc[n]) #################################################### HELPERS def read(callback=int): return list(map(callback, input().strip().split())) def write(value, end="\n"): if value is None: return try: if not isinstance(value, str): value = " ".join(map(str, value)) except: pass print(value, end=end) write(main()) ```
10,451
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Tags: *special, brute force, implementation Correct Solution: ``` a = int(input()) b = int(input()) c = int(input()) d = int(input()) p = a ^ b q = c | d r = b & c s = a ^ d x = p & q y = r | s z = x ^ y print(z) ```
10,452
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Submitted Solution: ``` a=int(input()) b=int(input()) c=int(input()) d=int(input()) out=(((a ^ b) and (c or d)) ^ ((b and c) or (a ^ d))) print(out) ``` Yes
10,453
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Submitted Solution: ``` a, b, c, d = [int(input()) for i in range(4)] print(((a^b) & (c | d)) ^ ((b&c) | (a^d))) ``` Yes
10,454
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Submitted Solution: ``` def pegaInput(): oi = input() if(oi == '0'): return False else: return True a = [pegaInput() for i in range(4)] #Possibilidades testadas: # e, ou, xor # ou, e, xor # xor, ou, e # e, xor, ou # ou, xor, e # xor, e, ou def xor(x, y): return x & y def e(x, y): return x | y def ou(x, y): return x ^ y p1 = ou(a[0],a[1]) p2 = e(a[2],a[3]) p3 = xor(a[1],a[2]) p4 = ou(a[0],a[3]) p5 = xor(p1,p2) p6 = e(p3, p4) p7 = ou(p5, p6) if(p7 == False): print(0) else: print(1) ``` Yes
10,455
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Submitted Solution: ``` import collections as col import itertools as its import sys import operator from bisect import bisect_left, bisect_right from copy import copy, deepcopy class Solver: def __init__(self): pass def solve(self): a = int(input()) b = int(input()) c = int(input()) d = int(input()) l11 = a ^ b l12 = c | d l13 = b & c l14 = a ^ d l21 = l11 & l12 l22 = l13 | l14 print(l21 ^ l22) if __name__ == '__main__': s = Solver() s.solve() ``` Yes
10,456
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Submitted Solution: ``` a, b, c, d = int(input()), int(input()), int(input()), int(input()) x = a ^ b y = c or d z = b and c t = a ^ c print((x and y) ^ (z or t)) ``` No
10,457
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Submitted Solution: ``` a = int(input()) b = int(input()) c = int(input()) d = int(input()) n = a*8+b*4+c*2+d # 0123456789012345 # ! ! ! a = "0000000000001111" print(a[n]) ``` No
10,458
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Submitted Solution: ``` """ Codeforces April Fools Contest 2017 Problem E Author : chaotic_iak Language: Python 3.5.2 """ ################################################### SOLUTION def main(): a, = read() b, = read() c, = read() d, = read() n = 8*a + 4*b + 2*c + d dc = { 0: 0, # test 2 confirmed correct 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, # given 7: 0, 8: 1, # test 3 confirmed correct 9: 0, 10: 0, 11: 0, 12: 1, # test 5 among these, equals 1 13: 0, # 14: 0, 15: 0, } print(dc[n]) #################################################### HELPERS def read(callback=int): return list(map(callback, input().strip().split())) def write(value, end="\n"): if value is None: return try: if not isinstance(value, str): value = " ".join(map(str, value)) except: pass print(value, end=end) write(main()) ``` No
10,459
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0 Submitted Solution: ``` a1, a2, a3, a4 = [bool(input()) for _ in range(4)] gate1 = a1 or a2 gate2 = a3 != a4 gate3 = a2 and a3 gate4 = a1 or a4 gate5 = gate1 and gate2 gate6 = gate3 != gate4 gate7 = gate5 or gate6 print(1 - int(gate7)) ``` No
10,460
Provide tags and a correct Python 3 solution for this coding contest problem. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Tags: combinatorics, greedy, implementation, math Correct Solution: ``` ##############--->>>>> Deepcoder Amit Kumar Bhuyan <<<<<---############## """ Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away. """ from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def msi(): return map(str,input().strip().split(" ")) def li(): return list(mi()) def dmain(): sys.setrecursionlimit(1000000) threading.stack_size(1024000) thread = threading.Thread(target=main) thread.start() #from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace #from math import log,sqrt,factorial,cos,tan,sin,radians #from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right #from decimal import * #import threading #from itertools import permutations #Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy import sys input = sys.stdin.readline scanner = lambda: int(input()) string = lambda: input().rstrip() get_list = lambda: list(read()) read = lambda: map(int, input().split()) get_float = lambda: map(float, input().split()) # from bisect import bisect_left as lower_bound; # from bisect import bisect_right as upper_bound; # from math import ceil, factorial; def ceil(x): if x != int(x): x = int(x) + 1 return x def factorial(x, m): val = 1 while x>0: val = (val * x) % m x -= 1 return val def fact(x): val = 1 while x > 0: val *= x x -= 1 return val # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; ## gcd function def gcd(a,b): if b == 0: return a; return gcd(b, a % b); ## lcm function def lcm(a, b): return (a * b) // math.gcd(a, b) def is_integer(n): return math.ceil(n) == math.floor(n) ## nCr function efficient using Binomial Cofficient def nCr(n, k): if k > n: return 0 if(k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## upper bound function code -- such that e in a[:i] e < x; ## prime factorization def primefs(n): ## if n == 1 ## calculating primes primes = {} while(n%2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n//2 for i in range(3, int(n**0.5)+2, 2): while(n%i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n//i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## DISJOINT SET UNINON FUNCTIONS def swap(a,b): temp = a a = b b = temp return a,b; # find function with path compression included (recursive) # def find(x, link): # if link[x] == x: # return x # link[x] = find(link[x], link); # return link[x]; # find function with path compression (ITERATIVE) def find(x, link): p = x; while( p != link[p]): p = link[p]; while( x != p): nex = link[x]; link[x] = p; x = nex; return p; # the union function which makes union(x,y) # of two nodes x and y def union(x, y, link, size): x = find(x, link) y = find(y, link) if size[x] < size[y]: x,y = swap(x,y) if x != y: size[x] += size[y] link[y] = x ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n+1)] prime[0], prime[1] = False, False p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime # Euler's Toitent Function phi def phi(n) : result = n p = 2 while(p * p<= n) : if (n % p == 0) : while (n % p == 0) : n = n // p result = result * (1.0 - (1.0 / (float) (p))) p = p + 1 if (n > 1) : result = result * (1.0 - (1.0 / (float)(n))) return (int)(result) def is_prime(n): if n == 0: return False if n == 1: return True for i in range(2, int(n ** (1 / 2)) + 1): if not n % i: return False return True def next_prime(n, primes): while primes[n] != True: n += 1 return n #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e5 + 5) def spf_sieve(): spf[1] = 1; for i in range(2, MAXN): spf[i] = i; for i in range(4, MAXN, 2): spf[i] = 2; for i in range(3, ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i*i, MAXN, i): if spf[j] == j: spf[j] = i; ## function for storing smallest prime factors (spf) in the array ################## un-comment below 2 lines when using factorization ################# spf = [0 for i in range(MAXN)] # spf_sieve(); def factoriazation(x): res = [] for i in range(2, int(x ** 0.5) + 1): while x % i == 0: res.append(i) x //= i if x != 1: res.append(x) return res ## this function is useful for multiple queries only, o/w use ## primefs function above. complexity O(log n) def factors(n): res = [] for i in range(1, int(n ** 0.5) + 1): if n % i == 0: res.append(i) res.append(n // i) return list(set(res)) ## taking integer array input def int_array(): return list(map(int, input().strip().split())); def float_array(): return list(map(float, input().strip().split())); ## taking string array input def str_array(): return input().strip().split(); def binary_search(low, high, w, h, n): while low < high: mid = low + (high - low) // 2 # print(low, mid, high) if check(mid, w, h, n): low = mid + 1 else: high = mid return low ## for checking any conditions def check(beauty, s, n, count): pass #defining a couple constants MOD = int(1e9)+7; CMOD = 998244353; INF = float('inf'); NINF = -float('inf'); alphs = "abcdefghijklmnopqrstuvwxyz" ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### from itertools import permutations import math import bisect as bis import random import sys import collections as collect def solve(): s = string() l = len(s) i = 0 j = l - 1 ans = 0 while j >= 0: if s[j] == 'b': i += 1 else: ans += i % MOD i *= 2 i %= MOD ans %= MOD j -= 1 print(ans) # region fastio # template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": #read() for i in range(1): solve() #dmain() # Comment Read() # fin_time = datetime.now() # print("Execution time (for loop): ", (fin_time-init_time)) ```
10,461
Provide tags and a correct Python 3 solution for this coding contest problem. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Tags: combinatorics, greedy, implementation, math Correct Solution: ``` s = input() cnt = 0 ans = 0 mod = 1000000007 for i in reversed(range(len(s))): if(s[i] is 'a'): ans = (ans + cnt) % mod cnt = (cnt * 2) % mod else: cnt += 1 print(ans) ```
10,462
Provide tags and a correct Python 3 solution for this coding contest problem. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Tags: combinatorics, greedy, implementation, math Correct Solution: ``` s = input() a, b = 0, 0 for i in reversed(s): if i == 'b': b += 1 else: a += b b *= 2 b %= 10**9 + 7 print(a % (10**9 + 7)) """ from re import findall s = input() k = 0 p = findall('ab', s) while p: k += len(p) s = s.replace('ab', 'bba') p = findall('ab', s) print(k) from re import search s = input() k = 0 while search('ab', s): k += 1 s = s.replace('ab', 'bba', 1) print(k) from re import * s = input() k = 0 pattern = compile('ab') while pattern.search(s): k += 1 s = s.replace('ab', 'bba', 1) print(k) """ ```
10,463
Provide tags and a correct Python 3 solution for this coding contest problem. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Tags: combinatorics, greedy, implementation, math Correct Solution: ``` l = input() flaga, flagb = 0, 0 countbn, countan = 0, 0 count = 0 MOD = 10 ** 9 + 7 # a^n b^m i = len(l) vec = [] while i > 0: i = i - 1 if l[i] == 'b': countbn += 1 else: count += countbn countbn *= 2 count %= MOD countbn %= MOD print(count % MOD) ```
10,464
Provide tags and a correct Python 3 solution for this coding contest problem. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Tags: combinatorics, greedy, implementation, math Correct Solution: ``` MOD = 10**9 + 7 s = input() bcount, count = 0, 0 for c in reversed(s): if c == 'b': bcount += 1 else: count = (count + bcount) % MOD bcount = bcount * 2 % MOD print(count) ```
10,465
Provide tags and a correct Python 3 solution for this coding contest problem. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Tags: combinatorics, greedy, implementation, math Correct Solution: ``` import math import sys mod = 1000000007 def main(): n = input() tmp = 0 ans = 0 for i in range(len(n)-1,-1,-1): if n[i] == 'a': ans += tmp ans %= mod tmp *= 2 tmp %= mod else: tmp += 1 print(ans) main() ```
10,466
Provide tags and a correct Python 3 solution for this coding contest problem. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Tags: combinatorics, greedy, implementation, math Correct Solution: ``` mod = 1000000007; b,ans = 0,0 for x in reversed(input()): if x == 'a': ans = (ans + b)%mod; b = (2*b)%mod else: b = (b+1%mod) print(ans) ```
10,467
Provide tags and a correct Python 3 solution for this coding contest problem. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Tags: combinatorics, greedy, implementation, math Correct Solution: ``` s=input() ans=0 j=0 cnt1=0 cnt2=0 for i in range(0,len(s)): if i>=j: while i<len(s) and s[i]=='a': cnt1=cnt1+1 i=i+1 while i<len(s) and s[i]=='b': cnt2=cnt2+1 i=i+1 j=i; if cnt1>0 and cnt2>0: ans=ans + cnt2 bb= cnt2*2 temp=cnt1-1 ans = ans + bb*(pow(2,temp,1000000007)-1) #print(ans) cnt2=0 print(ans%1000000007) ```
10,468
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Submitted Solution: ``` s=input() c=0 ans=0 cst=10**9+7 for i in range(len(s)-1,-1,-1): if s[i]=='a': ans=(ans+c)%cst c=(c*2)%cst else: c=c+1 print(ans%cst) ``` Yes
10,469
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Submitted Solution: ``` #!/usr/bin/python3.5 s=input() m=1000000007 p=0 k=1 for i in s: if i=='a': k<<=1 k%=m else: p+=k-1; p%=m print(p) ``` Yes
10,470
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 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 main(): s = S() r = 0 b = 0 for c in s[::-1]: if c == 'a': r += b r %= mod b *= 2 b %= mod else: b += 1 return r print(main()) ``` Yes
10,471
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Submitted Solution: ``` import sys mod = 10**9 + 7 def solve(): s = input()[::-1] ans = 0 b_cnt = 0 for ch in s: if ch == 'b': b_cnt = (b_cnt + 1) % mod else: ans = (ans + b_cnt) % mod b_cnt = (b_cnt * 2) % mod print(ans) if __name__ == '__main__': solve() ``` Yes
10,472
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Submitted Solution: ``` import sys import re def solve(): str = input() iter=re.finditer('ab', str) astart = [x.start()+1 for x in iter] iter=re.finditer('ba', str) bstart = [x.start()+1 for x in iter] if not bstart: bstart=[0] if not astart: astart=[0] if astart[0]<bstart[0]: bstart.insert(0,0) if len(bstart) == len(astart): bstart.append(len(str)) A=[] B=[] incr=[] MOD=1000000007 for i in range(len(astart)): A.append(astart[i]-bstart[i]) B.append(bstart[i+1]-astart[i]) incr.append(((2**sum(A)-1)*B[i]) % MOD) #print(A) #print(B) print(sum(incr)) if __name__ == '__main__': solve() ``` No
10,473
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Submitted Solution: ``` s=input() ans=0 j=0 for i in range(0,len(s)): if i>=j: cnt1=0 while i<len(s) and s[i]=='a': cnt1=cnt1+1 i=i+1 cnt2=0 while i<len(s) and s[i]=='b': cnt2=cnt2+1 i=i+1 j=i; if cnt1>0 and cnt2>0: ans=ans + cnt2 bb= cnt2*2 cnt1=cnt1-1 ans = ans + bb*(pow(2,cnt1,1000000007)-1) #print(ans) print(ans%1000000007) ``` No
10,474
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Submitted Solution: ``` m=1000*1000*1000+7 s=input() from math import pow #pow=[1] #for i in range (1,len(s)): # pow.append(pow[i-1]*2) ans=0 m=1000*1000*1000+7 cnt=0 for i in s: if(i=='a') : cnt=cnt+1 else: ans=(int(ans+pow(2,cnt)-1)) %m print(ans) ``` No
10,475
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". Submitted Solution: ``` ##############--->>>>> Deepcoder Amit Kumar Bhuyan <<<<<---############## """ Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away. """ from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def msi(): return map(str,input().strip().split(" ")) def li(): return list(mi()) def dmain(): sys.setrecursionlimit(1000000) threading.stack_size(1024000) thread = threading.Thread(target=main) thread.start() #from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace #from math import log,sqrt,factorial,cos,tan,sin,radians #from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right #from decimal import * #import threading #from itertools import permutations #Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy import sys input = sys.stdin.readline scanner = lambda: int(input()) string = lambda: input().rstrip() get_list = lambda: list(read()) read = lambda: map(int, input().split()) get_float = lambda: map(float, input().split()) # from bisect import bisect_left as lower_bound; # from bisect import bisect_right as upper_bound; # from math import ceil, factorial; def ceil(x): if x != int(x): x = int(x) + 1 return x def factorial(x, m): val = 1 while x>0: val = (val * x) % m x -= 1 return val def fact(x): val = 1 while x > 0: val *= x x -= 1 return val # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; ## gcd function def gcd(a,b): if b == 0: return a; return gcd(b, a % b); ## lcm function def lcm(a, b): return (a * b) // math.gcd(a, b) def is_integer(n): return math.ceil(n) == math.floor(n) ## nCr function efficient using Binomial Cofficient def nCr(n, k): if k > n: return 0 if(k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## upper bound function code -- such that e in a[:i] e < x; ## prime factorization def primefs(n): ## if n == 1 ## calculating primes primes = {} while(n%2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n//2 for i in range(3, int(n**0.5)+2, 2): while(n%i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n//i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## DISJOINT SET UNINON FUNCTIONS def swap(a,b): temp = a a = b b = temp return a,b; # find function with path compression included (recursive) # def find(x, link): # if link[x] == x: # return x # link[x] = find(link[x], link); # return link[x]; # find function with path compression (ITERATIVE) def find(x, link): p = x; while( p != link[p]): p = link[p]; while( x != p): nex = link[x]; link[x] = p; x = nex; return p; # the union function which makes union(x,y) # of two nodes x and y def union(x, y, link, size): x = find(x, link) y = find(y, link) if size[x] < size[y]: x,y = swap(x,y) if x != y: size[x] += size[y] link[y] = x ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n+1)] prime[0], prime[1] = False, False p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime # Euler's Toitent Function phi def phi(n) : result = n p = 2 while(p * p<= n) : if (n % p == 0) : while (n % p == 0) : n = n // p result = result * (1.0 - (1.0 / (float) (p))) p = p + 1 if (n > 1) : result = result * (1.0 - (1.0 / (float)(n))) return (int)(result) def is_prime(n): if n == 0: return False if n == 1: return True for i in range(2, int(n ** (1 / 2)) + 1): if not n % i: return False return True def next_prime(n, primes): while primes[n] != True: n += 1 return n #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e5 + 5) def spf_sieve(): spf[1] = 1; for i in range(2, MAXN): spf[i] = i; for i in range(4, MAXN, 2): spf[i] = 2; for i in range(3, ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i*i, MAXN, i): if spf[j] == j: spf[j] = i; ## function for storing smallest prime factors (spf) in the array ################## un-comment below 2 lines when using factorization ################# spf = [0 for i in range(MAXN)] # spf_sieve(); def factoriazation(x): res = [] for i in range(2, int(x ** 0.5) + 1): while x % i == 0: res.append(i) x //= i if x != 1: res.append(x) return res ## this function is useful for multiple queries only, o/w use ## primefs function above. complexity O(log n) def factors(n): res = [] for i in range(1, int(n ** 0.5) + 1): if n % i == 0: res.append(i) res.append(n // i) return list(set(res)) ## taking integer array input def int_array(): return list(map(int, input().strip().split())); def float_array(): return list(map(float, input().strip().split())); ## taking string array input def str_array(): return input().strip().split(); def binary_search(low, high, w, h, n): while low < high: mid = low + (high - low) // 2 # print(low, mid, high) if check(mid, w, h, n): low = mid + 1 else: high = mid return low ## for checking any conditions def check(beauty, s, n, count): pass #defining a couple constants MOD = int(1e9)+7; CMOD = 998244353; INF = float('inf'); NINF = -float('inf'); alphs = "abcdefghijklmnopqrstuvwxyz" ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### from itertools import permutations import math import bisect as bis import random import sys import collections as collect def solve(): s = string() l = len(s) i = 0 j = l - 1 ans = 0 while j >= 0: if s[j] == 'b': i += 1 else: ans += i % MOD i *= 2 j -= 1 print(ans) # region fastio # template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": #read() for i in range(1): solve() #dmain() # Comment Read() # fin_time = datetime.now() # print("Execution time (for loop): ", (fin_time-init_time)) ``` No
10,476
Provide tags and a correct Python 3 solution for this coding contest problem. It is known that passages in Singer house are complex and intertwined. Let's define a Singer k-house as a graph built by the following process: take complete binary tree of height k and add edges from each vertex to all its successors, if they are not yet present. <image> Singer 4-house Count the number of non-empty paths in Singer k-house which do not pass the same vertex twice. Two paths are distinct if the sets or the orders of visited vertices are different. Since the answer can be large, output it modulo 109 + 7. Input The only line contains single integer k (1 ≤ k ≤ 400). Output Print single integer — the answer for the task modulo 109 + 7. Examples Input 2 Output 9 Input 3 Output 245 Input 20 Output 550384565 Note There are 9 paths in the first example (the vertices are numbered on the picture below): 1, 2, 3, 1-2, 2-1, 1-3, 3-1, 2-1-3, 3-1-2. <image> Singer 2-house Tags: combinatorics, dp, graphs, trees Correct Solution: ``` print([0,1,9,245,126565,54326037,321837880,323252721,754868154,328083248,838314395,220816781,893672292,166441208,251255697,114256285,118775501,482714697,11784725,460862131,550384565,106742050,425241115,626692854,674266678,320014275,345949512,527320049,897822749,137190263,491039182,810384961,482023334,658099864,886790989,845381174,371433224,278969124,420088324,696766322,388302635,141033366,46387851,932125021,278342766,371131134,922501918,110778457,506223573,806353719,391845991,923507761,780307355,109951115,830090230,605558495,344686604,988110893,944684429,715019947,799898820,384672708,907325090,758952329,550672104,368337206,394915145,401744167,923781939,831857516,407845661,329267374,927004007,891609656,897919613,481297880,737337940,651873737,287246681,973133651,679864988,784719328,820504764,875613823,806512665,164851642,500228957,951814419,447763649,273141670,979349615,964027956,809510400,276634497,116631976,426739449,175282420,885948162,62270880,974395255,675165056,759589968,837957573,931897605,152352780,585420109,1772087,333401718,898833639,745874265,786209423,691982338,498790927,473374639,274302623,971280670,241671319,13070005,302088807,550276351,436592588,631667314,548656698,730626984,146295220,674398632,400383348,454138904,786220712,118620797,233440672,217349271,274853536,310607544,105221205,769566615,853585061,800665807,695377419,924327065,388199705,551624811,721435546,501720515,308465454,825369234,396065729,451899519,295058424,142088952,473485086,378771634,734511215,462404399,959198328,337668263,794122911,38911400,951992982,472696081,373904752,105884826,630251717,28980684,845136347,353665773,691661192,19922354,231463797,757917231,242739918,979036950,713722080,234689388,2243164,209872853,240808787,539523346,425797848,913772061,224613100,421742777,222232478,92712941,215137570,949901408,274827432,15162482,593145989,274574232,239282092,762720192,804146934,500629424,565985054,81127381,671811155,655565571,890331075,237994348,743647404,667160634,713914299,668506729,741341289,277636808,762781382,14272789,902864131,567443405,149113383,648844381,825489976,933016723,192288078,734493315,240985733,861817693,762711459,525904609,532463481,377133989,620711079,772561562,980733194,227599811,162774370,209512798,787116594,3509258,748795368,378035466,612938915,802091952,857679599,481748937,493370392,358420805,48301629,412001241,463126722,509578422,967799131,994766554,687287243,863623583,771554899,690911527,855314994,923686429,246862514,192479791,133487041,703444043,295281758,801816257,920762934,749306433,973004841,848644684,560026478,952127278,616654635,839390326,975154012,409583672,635350249,343228425,335331602,223826406,952341037,589677800,249747234,555694261,137143500,628190328,461598392,431912756,29349807,759199489,783281228,781971312,915823407,388508707,718062705,27424111,309999451,963383322,831185229,132910888,347028136,850484840,223055285,142335980,144754000,772005560,81796039,167696020,79454283,172772542,201056991,484957644,716630285,763194701,211505841,903448791,926964672,257752668,482951716,411539070,620249847,592476107,170473128,814662613,898000271,57354872,361106091,488697643,889007954,138725767,684860983,36248116,304610143,137633385,413715776,99010024,779653665,100387568,286328069,564731826,621740468,943513219,506666491,249987886,553719884,769853086,337485319,702455584,809637762,755400257,892290368,502180086,364275817,118162370,873374339,261271695,970132574,744105500,434447173,117975095,383088393,625447969,180281249,545367713,133236931,360175662,148087453,806871297,498529036,886076476,65645000,465138299,967109895,331362616,472283705,796894900,199697765,503759892,472807906,187586706,941198065,782234442,57693411,18678611,82626204,395317191,570588915,152519440,449852456,63696518,763741345,878748386,494317541,444782633,93316211,929164666,529288371,165769871,730546850,955877127,994202767,492009567,275683011,415902127,95725776,718047399,786963365,73091278,986172399,174591541,913259286][int(input())]) ```
10,477
Provide tags and a correct Python 3 solution for this coding contest problem. It is known that passages in Singer house are complex and intertwined. Let's define a Singer k-house as a graph built by the following process: take complete binary tree of height k and add edges from each vertex to all its successors, if they are not yet present. <image> Singer 4-house Count the number of non-empty paths in Singer k-house which do not pass the same vertex twice. Two paths are distinct if the sets or the orders of visited vertices are different. Since the answer can be large, output it modulo 109 + 7. Input The only line contains single integer k (1 ≤ k ≤ 400). Output Print single integer — the answer for the task modulo 109 + 7. Examples Input 2 Output 9 Input 3 Output 245 Input 20 Output 550384565 Note There are 9 paths in the first example (the vertices are numbered on the picture below): 1, 2, 3, 1-2, 2-1, 1-3, 3-1, 2-1-3, 3-1-2. <image> Singer 2-house Tags: combinatorics, dp, graphs, trees Correct Solution: ``` l=[0,1,9,245,126565,54326037,321837880,323252721,754868154,328083248,838314395,220816781,893672292,166441208,251255697,114256285,118775501,482714697,11784725,460862131,550384565,106742050,425241115,626692854,674266678,320014275,345949512,527320049,897822749,137190263,491039182,810384961,482023334,658099864,886790989,845381174,371433224,278969124,420088324,696766322,388302635,141033366,46387851,932125021,278342766,371131134,922501918,110778457,506223573,806353719,391845991,923507761,780307355,109951115,830090230,605558495,344686604,988110893,944684429,715019947,799898820,384672708,907325090,758952329,550672104,368337206,394915145,401744167,923781939,831857516,407845661,329267374,927004007,891609656,897919613,481297880,737337940,651873737,287246681,973133651,679864988,784719328,820504764,875613823,806512665,164851642,500228957,951814419,447763649,273141670,979349615,964027956,809510400,276634497,116631976,426739449,175282420,885948162,62270880,974395255,675165056,759589968,837957573,931897605,152352780,585420109,1772087,333401718,898833639,745874265,786209423,691982338,498790927,473374639,274302623,971280670,241671319,13070005,302088807,550276351,436592588,631667314,548656698,730626984,146295220,674398632,400383348,454138904,786220712,118620797,233440672,217349271,274853536,310607544,105221205,769566615,853585061,800665807,695377419,924327065,388199705,551624811,721435546,501720515,308465454,825369234,396065729,451899519,295058424,142088952,473485086,378771634,734511215,462404399,959198328,337668263,794122911,38911400,951992982,472696081,373904752,105884826,630251717,28980684,845136347,353665773,691661192,19922354,231463797,757917231,242739918,979036950,713722080,234689388,2243164,209872853,240808787,539523346,425797848,913772061,224613100,421742777,222232478,92712941,215137570,949901408,274827432,15162482,593145989,274574232,239282092,762720192,804146934,500629424,565985054,81127381,671811155,655565571,890331075,237994348,743647404,667160634,713914299,668506729,741341289,277636808,762781382,14272789,902864131,567443405,149113383,648844381,825489976,933016723,192288078,734493315,240985733,861817693,762711459,525904609,532463481,377133989,620711079,772561562,980733194,227599811,162774370,209512798,787116594,3509258,748795368,378035466,612938915,802091952,857679599,481748937,493370392,358420805,48301629,412001241,463126722,509578422,967799131,994766554,687287243,863623583,771554899,690911527,855314994,923686429,246862514,192479791,133487041,703444043,295281758,801816257,920762934,749306433,973004841,848644684,560026478,952127278,616654635,839390326,975154012,409583672,635350249,343228425,335331602,223826406,952341037,589677800,249747234,555694261,137143500,628190328,461598392,431912756,29349807,759199489,783281228,781971312,915823407,388508707,718062705,27424111,309999451,963383322,831185229,132910888,347028136,850484840,223055285,142335980,144754000,772005560,81796039,167696020,79454283,172772542,201056991,484957644,716630285,763194701,211505841,903448791,926964672,257752668,482951716,411539070,620249847,592476107,170473128,814662613,898000271,57354872,361106091,488697643,889007954,138725767,684860983,36248116,304610143,137633385,413715776,99010024,779653665,100387568,286328069,564731826,621740468,943513219,506666491,249987886,553719884,769853086,337485319,702455584,809637762,755400257,892290368,502180086,364275817,118162370,873374339,261271695,970132574,744105500,434447173,117975095,383088393,625447969,180281249,545367713,133236931,360175662,148087453,806871297,498529036,886076476,65645000,465138299,967109895,331362616,472283705,796894900,199697765,503759892,472807906,187586706,941198065,782234442,57693411,18678611,82626204,395317191,570588915,152519440,449852456,63696518,763741345,878748386,494317541,444782633,93316211,929164666,529288371,165769871,730546850,955877127,994202767,492009567,275683011,415902127,95725776,718047399,786963365,73091278,986172399,174591541,913259286] p=int(input()) print(l[p]) ```
10,478
Provide tags and a correct Python 3 solution for this coding contest problem. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Tags: math Correct Solution: ``` n = int(input()); a = int(input()); b = int(input()); c = int(input()); ans = 0; k = 1; for i in range(n-1): if (k == 1): if (a < b): k = 2; ans += a; else: k = 3; ans += b; elif k == 2 : if (a < c): k = 1; ans += a; else: k = 3; ans += c; else: if (b < c): k = 1; ans += b; else: k = 2; ans += c; print(ans); ```
10,479
Provide tags and a correct Python 3 solution for this coding contest problem. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Tags: math Correct Solution: ``` n,a,b,c=int(input()),int(input()),int(input()),int(input()) if n==1: print(0) else: first = a if a<b else b second = first if first<c else c print(first+(n-2)*second) ```
10,480
Provide tags and a correct Python 3 solution for this coding contest problem. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Tags: math Correct Solution: ``` n = int(input()) dist = [] dist.append(int(input())) dist.append(int(input())) dist.append(int(input())) dist2 = sorted(dist) if n==1: print(0) elif dist2[0]==dist[0]: print((n-1)*dist[0]) elif dist2[0]==dist[1]: print((n-1)*dist[1]) else: if dist2[1]==dist[0]: print(dist[0]+(n-2)*dist[2]) else: print(dist[1]+(n-2)*dist[2]) ```
10,481
Provide tags and a correct Python 3 solution for this coding contest problem. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Tags: math Correct Solution: ``` d={} n=int(input()) ab=int(input()) ac=int(input()) bc=int(input()) d[1]=[[2,ab],[3,ac]] d[2]=[[1,ab],[3,bc]] d[3]=[[2,bc],[1,ac]] ans=0 k=1 x=1 while k<n: ans+=min(d[x][0][1],d[x][1][1]) if d[x][0][1]<d[x][1][1]: x=d[x][0][0] else: x=d[x][1][0] k+=1 print(ans) ```
10,482
Provide tags and a correct Python 3 solution for this coding contest problem. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Tags: math Correct Solution: ``` n=int(input()) a=int(input())#1-2 b=int(input())#1-3 c=int(input())#3-2 nowat=1 ans=0 for i in range(n-1): if nowat==1: if a<b: ans+=a nowat=2 else: ans+=b nowat=3 elif nowat==2: if a<c: ans+=a nowat=1 else: ans+=c nowat=3 elif nowat==3: if b<c: ans+=b nowat=1 else: ans+=c nowat=2 print(ans) ```
10,483
Provide tags and a correct Python 3 solution for this coding contest problem. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Tags: math Correct Solution: ``` n = int(input()) a = int(input()) b = int(input()) c = int(input()) ans = 0 t = 0 n-=1 if n == 0: print(0) exit(0) if c < a and c < b: ans = min(a, b) + (n-1)*c else: ans = min(a, b)*(n) print(ans) ```
10,484
Provide tags and a correct Python 3 solution for this coding contest problem. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Tags: math Correct Solution: ``` #https://codeforces.com/problemset/problem/876/A n=int(input()) a=int(input()) b=int(input()) c=int(input()) n=n-1 ans=0 if n: n-=1 ans+=min(a,b) #print(c,n) ans+=(min(a,b,c)*n) print(ans) ```
10,485
Provide tags and a correct Python 3 solution for this coding contest problem. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Tags: math Correct Solution: ``` #problem65 n=int(input()) a=int(input()) b=int(input()) c=int(input()) if n==1: print(0) elif min(a,b,c)==a or min(a,b,c)==b: print(min(a,b)*(n-1)) else: print(min(a,b)+c*(n-2)) ```
10,486
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Submitted Solution: ``` N = int(input()) N -= 1 A = int(input()) B = int(input()) C = int(input()) print(min(N * A, N * B, min(A, B) + (C * (N - 1))) if N != 0 else 0) ``` Yes
10,487
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Submitted Solution: ``` n = int(input()) a = int(input()) b = int(input()) c = int(input()) s = 0 n -= 1 x = 1 for i in range(n): if x == 1: if a < b: s += a x = 2 else: s += b x = 3 elif x == 2: if a < c: s += a x = 1 else: s += c x = 3 else: if b < c: s += b x = 1 else: s += c x = 2 print(s) ``` Yes
10,488
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Submitted Solution: ``` n = int(input()) a = int(input()) b = int(input()) c = int(input()) if n==1: print(0) else: if a<=b and a<=c: print(a*(n-1)) elif b<=a and b<=c: print(b*(n-1)) else: print(min(a,b)+c*(n-2)) ``` Yes
10,489
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Submitted Solution: ``` n=int(input()) e=int(input()) o=int(input()) r=int(input()) meal=1 way=0 pos='R' dic={'R':[o,e],'E':[o,r],'O':[e,r]} while meal<n : way+=min(dic[pos]) if min(dic[pos])==e : if pos=='R' : pos='O' else : pos='R' elif min(dic[pos])==o : if pos=='R' : pos='E' else : pos='R' else : if pos=='O' : pos='E' else : pos='O' meal+=1 print(way) ``` Yes
10,490
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Submitted Solution: ``` n=int(input()) a=int(input()) b=int(input()) c=int(input()) re=[a,b,c] w=0 mi=0 i=1 while n-i!=0: er=3000 dw=w for j in range(3): if w!=j: if re[j]<er: er=re[j] dw=j w=dw mi+=er i+=1 print(mi) ``` No
10,491
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Submitted Solution: ``` n=int(input()) a=int(input()) b=int(input()) c=int(input()) m=0 z=a if min(a,b,c)==a: print((n-1)*min(a,b,c)) elif min(a,b,c)==b: print((n-1)*b) else: m+=min(a,b) print(m+(n-2)*c) ``` No
10,492
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Submitted Solution: ``` n = int(input()) a = int(input()) b = int(input()) c = int(input()) short = min((a,b,c)) ans = 0 if a == short or b == short: ans = min(a,b)*(n-1) else: ans = min(a,b) + c*(n-2) print(ans) ``` No
10,493
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. Output Output one number — minimum distance in meters Winnie must go through to have a meal n times. Examples Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Submitted Solution: ``` n = int(input()) a = int(input()) b = int(input()) c = int(input()) score = 0 r = True o = False e = False for i in range(n - 1): if r is True: if a > b: score += b o = True r = False else: score += a e = True r = False elif o is True: if a > c: score += c e = True o = False else: score += a r = True o = False elif e is True: if b > c: score += c o = True e = False else: score += a r = True e = False print(score) ``` No
10,494
Provide tags and a correct Python 3 solution for this coding contest problem. Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey. At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively. Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness. Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours. Input The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. Output Output one of the four words without inverted commas: * «forward» — if Peter could see such sequences only on the way from A to B; * «backward» — if Peter could see such sequences on the way from B to A; * «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; * «fantasy» — if Peter could not see such sequences. Examples Input atob a b Output forward Input aaacaaa aca aa Output both Note It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B. Tags: strings Correct Solution: ``` import sys import string from collections import Counter, defaultdict from math import fsum, sqrt, gcd, ceil, factorial from operator import * from itertools import accumulate inf = float("inf") # input = sys.stdin.readline flush = lambda: sys.stdout.flush comb = lambda x, y: (factorial(x) // factorial(y)) // factorial(x - y) # inputs # ip = lambda : input().rstrip() ip = lambda: input() ii = lambda: int(input()) r = lambda: map(int, input().split()) rr = lambda: list(r()) import re a = ip() b = a[::-1] x = ip() y = ip() a = re.match(f'(.*){x}(.*){y}', a) b = re.match(f'(.*){x}(.*){y}', b) # print(a, b) if a and b: print("both") elif a and not b: print("forward") elif not a and b: print("backward") else: print("fantasy") ```
10,495
Provide tags and a correct Python 3 solution for this coding contest problem. Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey. At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively. Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness. Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours. Input The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. Output Output one of the four words without inverted commas: * «forward» — if Peter could see such sequences only on the way from A to B; * «backward» — if Peter could see such sequences on the way from B to A; * «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; * «fantasy» — if Peter could not see such sequences. Examples Input atob a b Output forward Input aaacaaa aca aa Output both Note It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B. Tags: strings Correct Solution: ``` truepath=input() firstwake=input() secondwake=input() d=-1 f=-1 a1=0 a2=0 h=0 if len(firstwake)+len(secondwake)>len(truepath): print('fantasy') #Peters wakefulness faulted h=1 if h==0: for i in range (0,len(truepath)-len(firstwake)+1): if truepath[i:i+len(firstwake)]==firstwake: d=i #checking if first path is correct break for i in range (0,len(truepath)-len(secondwake)+1): if truepath[i:i+len(secondwake)]==secondwake: f=i #checking if second path is correct if d+len(firstwake)-1<f and d>-1: a1=1 d=-1 f=-1 truepath=list(truepath) truepath.reverse() truepath=''.join(truepath) #introducing this to the array for i in range (0,len(truepath)-len(firstwake)+1): if truepath[i:i+len(firstwake)]==firstwake: d=i break for i in range (0,len(truepath)-len(secondwake)+1): if truepath[i:i+len(secondwake)]==secondwake: f=i if d+len(firstwake)-1<f and d>-1: a2=1 if a1==1 and a2==0: print('forward') if a1==0 and a2==1: print('backward') if a1==1 and a2==1: print('both') if a1==0 and a2==0: print('fantasy') ```
10,496
Provide tags and a correct Python 3 solution for this coding contest problem. Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey. At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively. Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness. Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours. Input The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. Output Output one of the four words without inverted commas: * «forward» — if Peter could see such sequences only on the way from A to B; * «backward» — if Peter could see such sequences on the way from B to A; * «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; * «fantasy» — if Peter could not see such sequences. Examples Input atob a b Output forward Input aaacaaa aca aa Output both Note It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B. Tags: strings Correct Solution: ``` ss=input() ns=ss[::-1] a=input() b=input() f1=0 f2=0 k1=ss.find(a) k2=ss.find(b,k1+len(a)) if ((k1>-1)&(k2>-1)):f1=1 k1=ns.find(a) k2=ns.find(b,k1+len(a)) if ((k1>-1)&(k2>-1)):f2=1 if f1+f2==2: print("both") elif f1==1: print("forward") elif f2==1:print("backward") else: print("fantasy") ```
10,497
Provide tags and a correct Python 3 solution for this coding contest problem. Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey. At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively. Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness. Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours. Input The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. Output Output one of the four words without inverted commas: * «forward» — if Peter could see such sequences only on the way from A to B; * «backward» — if Peter could see such sequences on the way from B to A; * «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; * «fantasy» — if Peter could not see such sequences. Examples Input atob a b Output forward Input aaacaaa aca aa Output both Note It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B. Tags: strings Correct Solution: ``` def check(flags: str, first: str, second: str) -> bool: if first not in flags or second not in flags: return False f_f_ind = flags.index(first) l_s_ind = flags.rindex(second) return f_f_ind + len(first) - 1 < l_s_ind flags, first, second = input(), input(), input() f = check(flags, first, second) flags = flags[::-1] b = check(flags, first, second) if f and b: print('both') elif f: print('forward') elif b: print('backward') else: print('fantasy') ```
10,498
Provide tags and a correct Python 3 solution for this coding contest problem. Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey. At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively. Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness. Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours. Input The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. Output Output one of the four words without inverted commas: * «forward» — if Peter could see such sequences only on the way from A to B; * «backward» — if Peter could see such sequences on the way from B to A; * «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; * «fantasy» — if Peter could not see such sequences. Examples Input atob a b Output forward Input aaacaaa aca aa Output both Note It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B. Tags: strings Correct Solution: ``` a=input() b=input() c=input() d=-1 f=-1 a1=0 a2=0 h=0 if len(b)+len(c)>len(a): print('fantasy') h=1 if h==0: for i in range (0,len(a)-len(b)+1): #print(a[i:i+len(b)]) if a[i:i+len(b)]==b: d=i break for i in range (0,len(a)-len(c)+1): #print(a[i:i+len(c)]) if a[i:i+len(c)]==c: f=i if d+len(b)-1<f and d>-1: a1=1 d=-1 f=-1 a=list(a) a.reverse() a=''.join(a) for i in range (0,len(a)-len(b)+1): if a[i:i+len(b)]==b: d=i break for i in range (0,len(a)-len(c)+1): if a[i:i+len(c)]==c: f=i if d+len(b)-1<f and d>-1: a2=1 if a1==1 and a2==0: print('forward') if a1==0 and a2==1: print('backward') if a1==1 and a2==1: print('both') if a1==0 and a2==0: print('fantasy') ```
10,499