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. We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds. Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation: * If s does not contain X_i: add X_i to the end of s. * If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s. Find the elements of s after Snuke finished the operations. Constraints * 1 \leq N \leq 2 \times 10^5 * 1 \leq K \leq 10^{12} * 1 \leq A_i \leq 2 \times 10^5 * All values in input are integers. Input Input is given from Standard Input in the following format: N K A_0 A_1 \cdots A_{N-1} Output Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between. Examples Input 3 2 1 2 3 Output 2 3 Input 5 10 1 2 3 2 3 Output 3 Input 6 1000000000000 1 1 2 2 3 3 Output Input 11 97 3 1 4 1 5 9 2 6 5 3 5 Output 9 2 6 Submitted Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) s = [] for i in a: if i in s: while i ! s.pop(-1): break else : s.append(i) print(s) ``` No
9,700
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds. Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation: * If s does not contain X_i: add X_i to the end of s. * If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s. Find the elements of s after Snuke finished the operations. Constraints * 1 \leq N \leq 2 \times 10^5 * 1 \leq K \leq 10^{12} * 1 \leq A_i \leq 2 \times 10^5 * All values in input are integers. Input Input is given from Standard Input in the following format: N K A_0 A_1 \cdots A_{N-1} Output Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between. Examples Input 3 2 1 2 3 Output 2 3 Input 5 10 1 2 3 2 3 Output 3 Input 6 1000000000000 1 1 2 2 3 3 Output Input 11 97 3 1 4 1 5 9 2 6 5 3 5 Output 9 2 6 Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy sys.setrecursionlimit(10**7) inf=10**20 mod=10**9+7 dd=[(-1,0),(0,1),(1,0),(0,-1)] ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS(): return sys.stdin.readline().split() def S(): return input() def main(): n,k=LI() l=LI() l=l+l a=[] for x in l: y=a.count(x) if y>0: while True: if y==0: break p=a.pop() if p==x: y-=1 else: a.append(x) return ' '.join([str(x) for x in a]) # main() print(main()) ``` No
9,701
Provide a correct Python 3 solution for this coding contest problem. A museum exhibits N jewels, Jewel 1, 2, ..., N. The coordinates of Jewel i are (x_i, y_i) (the museum can be regarded as a two-dimensional plane), and the value of that jewel is v_i. Snuke the thief will steal some of these jewels. There are M conditions, Condition 1, 2, ..., M, that must be met when stealing jewels, or he will be caught by the detective. Each condition has one of the following four forms: * (t_i =`L`, a_i, b_i) : Snuke can only steal at most b_i jewels whose x coordinates are a_i or smaller. * (t_i =`R`, a_i, b_i) : Snuke can only steal at most b_i jewels whose x coordinates are a_i or larger. * (t_i =`D`, a_i, b_i) : Snuke can only steal at most b_i jewels whose y coordinates are a_i or smaller. * (t_i =`U`, a_i, b_i) : Snuke can only steal at most b_i jewels whose y coordinates are a_i or larger. Find the maximum sum of values of jewels that Snuke the thief can steal. Constraints * 1 \leq N \leq 80 * 1 \leq x_i, y_i \leq 100 * 1 \leq v_i \leq 10^{15} * 1 \leq M \leq 320 * t_i is `L`, `R`, `U` or `D`. * 1 \leq a_i \leq 100 * 0 \leq b_i \leq N - 1 * (x_i, y_i) are pairwise distinct. * (t_i, a_i) are pairwise distinct. * (t_i, b_i) are pairwise distinct. Input Input is given from Standard Input in the following format: N x_1 y_1 v_1 x_2 y_2 v_2 : x_N y_N v_N M t_1 a_1 b_1 t_2 a_2 b_2 : t_M a_M b_M Output Print the maximum sum of values of jewels that Snuke the thief can steal. Examples Input 7 1 3 6 1 5 9 3 1 8 4 3 8 6 2 9 5 4 11 5 7 10 4 L 3 1 R 2 3 D 5 3 U 4 2 Output 36 Input 3 1 2 3 4 5 6 7 8 9 1 L 100 0 Output 0 Input 4 1 1 10 1 2 11 2 1 12 2 2 13 3 L 8 3 L 9 2 L 10 1 Output 13 Input 10 66 47 71040136000 65 77 74799603000 80 53 91192869000 24 34 24931901000 91 78 49867703000 68 71 46108236000 46 73 74799603000 56 63 93122668000 32 51 71030136000 51 26 70912345000 21 L 51 1 L 7 0 U 47 4 R 92 0 R 91 1 D 53 2 R 65 3 D 13 0 U 63 3 L 68 3 D 47 1 L 91 5 R 32 4 L 66 2 L 80 4 D 77 4 U 73 1 D 78 5 U 26 5 R 80 2 R 24 5 Output 305223377000 "Correct Solution: ``` import sys input=sys.stdin.readline sys.setrecursionlimit(10**9) from collections import deque from bisect import bisect_left,bisect_right class MinCostFlow: def __init__(self,n): self.n=n self.edges=[[] for i in range(n)] def add_edge(self,fr,to,cap,cost): self.edges[fr].append([to,cap,cost,len(self.edges[to])]) self.edges[to].append([fr,0,-cost,len(self.edges[fr])-1]) def MinCost(self,source,sink,flow): inf=10**15+1 n=self.n; E=self.edges mincost=0 prev_v=[0]*n; prev_e=[0]*n while flow: dist=[inf]*n dist[source]=0 q=deque([source]) Flag=[False]*n Flag[source]=True while q: v=q.popleft() if not Flag[v]: continue Flag[v]=False for i,(to,cap,cost,_) in enumerate(E[v]): if cap>0 and dist[to]>dist[v]+cost: dist[to]=dist[v]+cost prev_v[to],prev_e[to]=v,i q.append(to) Flag[to]=True if dist[sink]==inf: return 1 f,v=flow,sink while v!=source: f=min(f,E[prev_v[v]][prev_e[v]][1]) v=prev_v[v] flow-=f mincost+=f*dist[sink] v=sink while v!=source: E[prev_v[v]][prev_e[v]][1]-=f rev=E[prev_v[v]][prev_e[v]][3] E[v][rev][1]+=f v=prev_v[v] return mincost n=int(input()) J=[] L_org,D_org=[1]*n,[1]*n for _ in range(n): x,y,v=map(int,input().split()) J.append((x,y,v)) m=int(input()) T=[] for _ in range(m): t,a,b=input().split() a,b=int(a),int(b) T.append((t,a,b)) if t=='L': L_org[b]=a+1 elif t=='D': D_org[b]=a+1 for i in range(1,n): L_org[i]=max(L_org[i-1],L_org[i]) D_org[i]=max(D_org[i-1],D_org[i]) def solve(k): L,D=L_org[:k],D_org[:k] R,U=[100]*k,[100]*k for t,a,b in T: if k-b-1>=0: if t=='R': R[k-b-1]=a-1 elif t=='U': U[k-b-1]=a-1 for i in range(k-2,-1,-1): R[i]=min(R[i],R[i+1]) U[i]=min(U[i],U[i+1]) solver=MinCostFlow(2*n+2*k+2) for i in range(1,k+1): solver.add_edge(0,i,1,0) solver.add_edge(2*n+k+i,2*n+2*k+1,1,0) for i in range(n): v=J[i][2] solver.add_edge(k+i+1,n+k+i+1,1,-v) for i in range(n): x,y=J[i][0],J[i][1] l=bisect_right(L,x) r=bisect_left(R,x)+1 d=bisect_right(D,y) u=bisect_left(U,y)+1 for j in range(r,l+1): solver.add_edge(j,k+i+1,1,0) for j in range(u,d+1): solver.add_edge(n+k+i+1,2*n+k+j,1,0) return -solver.MinCost(0,2*n+2*k+1,k) ans=0 k=1 while True: tmp=solve(k) ans=max(ans,tmp) if tmp==-1 or k==n: break k+=1 print(ans) ```
9,702
Provide a correct Python 3 solution for this coding contest problem. A museum exhibits N jewels, Jewel 1, 2, ..., N. The coordinates of Jewel i are (x_i, y_i) (the museum can be regarded as a two-dimensional plane), and the value of that jewel is v_i. Snuke the thief will steal some of these jewels. There are M conditions, Condition 1, 2, ..., M, that must be met when stealing jewels, or he will be caught by the detective. Each condition has one of the following four forms: * (t_i =`L`, a_i, b_i) : Snuke can only steal at most b_i jewels whose x coordinates are a_i or smaller. * (t_i =`R`, a_i, b_i) : Snuke can only steal at most b_i jewels whose x coordinates are a_i or larger. * (t_i =`D`, a_i, b_i) : Snuke can only steal at most b_i jewels whose y coordinates are a_i or smaller. * (t_i =`U`, a_i, b_i) : Snuke can only steal at most b_i jewels whose y coordinates are a_i or larger. Find the maximum sum of values of jewels that Snuke the thief can steal. Constraints * 1 \leq N \leq 80 * 1 \leq x_i, y_i \leq 100 * 1 \leq v_i \leq 10^{15} * 1 \leq M \leq 320 * t_i is `L`, `R`, `U` or `D`. * 1 \leq a_i \leq 100 * 0 \leq b_i \leq N - 1 * (x_i, y_i) are pairwise distinct. * (t_i, a_i) are pairwise distinct. * (t_i, b_i) are pairwise distinct. Input Input is given from Standard Input in the following format: N x_1 y_1 v_1 x_2 y_2 v_2 : x_N y_N v_N M t_1 a_1 b_1 t_2 a_2 b_2 : t_M a_M b_M Output Print the maximum sum of values of jewels that Snuke the thief can steal. Examples Input 7 1 3 6 1 5 9 3 1 8 4 3 8 6 2 9 5 4 11 5 7 10 4 L 3 1 R 2 3 D 5 3 U 4 2 Output 36 Input 3 1 2 3 4 5 6 7 8 9 1 L 100 0 Output 0 Input 4 1 1 10 1 2 11 2 1 12 2 2 13 3 L 8 3 L 9 2 L 10 1 Output 13 Input 10 66 47 71040136000 65 77 74799603000 80 53 91192869000 24 34 24931901000 91 78 49867703000 68 71 46108236000 46 73 74799603000 56 63 93122668000 32 51 71030136000 51 26 70912345000 21 L 51 1 L 7 0 U 47 4 R 92 0 R 91 1 D 53 2 R 65 3 D 13 0 U 63 3 L 68 3 D 47 1 L 91 5 R 32 4 L 66 2 L 80 4 D 77 4 U 73 1 D 78 5 U 26 5 R 80 2 R 24 5 Output 305223377000 "Correct Solution: ``` import sys input=sys.stdin.readline sys.setrecursionlimit(10**9) from bisect import bisect_left,bisect_right class MinCostFlow: def __init__(self,n): self.n=n self.edges=[[] for i in range(n)] def add_edge(self,fr,to,cap,cost): self.edges[fr].append([to,cap,cost,len(self.edges[to])]) self.edges[to].append([fr,0,-cost,len(self.edges[fr])-1]) def MinCost(self,source,sink,flow): inf=10**15+1 n,E=self.n,self.edges prev_v,prev_e=[0]*n,[0]*n mincost=0 while flow: dist=[inf]*n dist[source]=0 flag=True while flag: flag=False for v in range(n): if dist[v]==inf: continue Ev=E[v] for i in range(len(Ev)): to,cap,cost,rev=Ev[i] if cap>0 and dist[v]+cost<dist[to]: dist[to]=dist[v]+cost prev_v[to],prev_e[to]=v,i flag=True if dist[sink]==inf: return 1 f=flow v=sink while v!=source: f=min(f,E[prev_v[v]][prev_e[v]][1]) v=prev_v[v] flow-=f mincost+=f*dist[sink] v=sink while v!=source: E[prev_v[v]][prev_e[v]][1]-=f rev=E[prev_v[v]][prev_e[v]][3] E[v][rev][1]+=f v=prev_v[v] return mincost n=int(input()) J=[] L_org,D_org=[1]*n,[1]*n for _ in range(n): x,y,v=map(int,input().split()) J.append((x,y,v)) m=int(input()) T=[] for _ in range(m): t,a,b=input().split() a,b=int(a),int(b) T.append((t,a,b)) if t=='L': L_org[b]=a+1 elif t=='D': D_org[b]=a+1 for i in range(1,n): L_org[i]=max(L_org[i-1],L_org[i]) D_org[i]=max(D_org[i-1],D_org[i]) def solve(k): L,D=L_org[:k],D_org[:k] R,U=[100]*k,[100]*k for t,a,b in T: if k-b-1>=0: if t=='R': R[k-b-1]=a-1 elif t=='U': U[k-b-1]=a-1 for i in range(k-2,-1,-1): R[i]=min(R[i],R[i+1]) U[i]=min(U[i],U[i+1]) solver=MinCostFlow(2*n+2*k+2) for i in range(1,k+1): solver.add_edge(0,i,1,0) solver.add_edge(2*n+k+i,2*n+2*k+1,1,0) for i in range(n): v=J[i][2] solver.add_edge(k+i+1,n+k+i+1,1,-v) for i in range(n): x,y=J[i][0],J[i][1] l=bisect_right(L,x) r=bisect_left(R,x)+1 d=bisect_right(D,y) u=bisect_left(U,y)+1 for j in range(r,l+1): solver.add_edge(j,k+i+1,1,0) for j in range(u,d+1): solver.add_edge(n+k+i+1,2*n+k+j,1,0) return -solver.MinCost(0,2*n+2*k+1,k) ans=0 k=1 while True: tmp=solve(k) ans=max(ans,tmp) if tmp==-1 or k==n: break k+=1 print(ans) ```
9,703
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A museum exhibits N jewels, Jewel 1, 2, ..., N. The coordinates of Jewel i are (x_i, y_i) (the museum can be regarded as a two-dimensional plane), and the value of that jewel is v_i. Snuke the thief will steal some of these jewels. There are M conditions, Condition 1, 2, ..., M, that must be met when stealing jewels, or he will be caught by the detective. Each condition has one of the following four forms: * (t_i =`L`, a_i, b_i) : Snuke can only steal at most b_i jewels whose x coordinates are a_i or smaller. * (t_i =`R`, a_i, b_i) : Snuke can only steal at most b_i jewels whose x coordinates are a_i or larger. * (t_i =`D`, a_i, b_i) : Snuke can only steal at most b_i jewels whose y coordinates are a_i or smaller. * (t_i =`U`, a_i, b_i) : Snuke can only steal at most b_i jewels whose y coordinates are a_i or larger. Find the maximum sum of values of jewels that Snuke the thief can steal. Constraints * 1 \leq N \leq 80 * 1 \leq x_i, y_i \leq 100 * 1 \leq v_i \leq 10^{15} * 1 \leq M \leq 320 * t_i is `L`, `R`, `U` or `D`. * 1 \leq a_i \leq 100 * 0 \leq b_i \leq N - 1 * (x_i, y_i) are pairwise distinct. * (t_i, a_i) are pairwise distinct. * (t_i, b_i) are pairwise distinct. Input Input is given from Standard Input in the following format: N x_1 y_1 v_1 x_2 y_2 v_2 : x_N y_N v_N M t_1 a_1 b_1 t_2 a_2 b_2 : t_M a_M b_M Output Print the maximum sum of values of jewels that Snuke the thief can steal. Examples Input 7 1 3 6 1 5 9 3 1 8 4 3 8 6 2 9 5 4 11 5 7 10 4 L 3 1 R 2 3 D 5 3 U 4 2 Output 36 Input 3 1 2 3 4 5 6 7 8 9 1 L 100 0 Output 0 Input 4 1 1 10 1 2 11 2 1 12 2 2 13 3 L 8 3 L 9 2 L 10 1 Output 13 Input 10 66 47 71040136000 65 77 74799603000 80 53 91192869000 24 34 24931901000 91 78 49867703000 68 71 46108236000 46 73 74799603000 56 63 93122668000 32 51 71030136000 51 26 70912345000 21 L 51 1 L 7 0 U 47 4 R 92 0 R 91 1 D 53 2 R 65 3 D 13 0 U 63 3 L 68 3 D 47 1 L 91 5 R 32 4 L 66 2 L 80 4 D 77 4 U 73 1 D 78 5 U 26 5 R 80 2 R 24 5 Output 305223377000 Submitted Solution: ``` import sys input=sys.stdin.readline sys.setrecursionlimit(10**9) from bisect import bisect_left,bisect_right class MinCostFlow: def __init__(self,n): self.n=n self.edges=[[] for i in range(n)] def add_edge(self,fr,to,cap,cost): self.edges[fr].append([to,cap,cost,len(self.edges[to])]) self.edges[to].append([fr,0,-cost,len(self.edges[fr])-1]) def MinCost(self,source,sink,flow): inf=10**15+1 n,E=self.n,self.edges prev_v,prev_e=[0]*n,[0]*n mincost=0 while flow: dist=[inf]*n dist[source]=0 flag=True while flag: flag=False for v in range(n): if dist[v]==inf: continue Ev=E[v] for i in range(len(Ev)): to,cap,cost,rev=Ev[i] if cap>0 and dist[v]+cost<dist[to]: dist[to]=dist[v]+cost prev_v[to],prev_e[to]=v,i flag=True if dist[sink]==inf: return -1 f=flow v=sink while v!=source: f=min(f,E[prev_v[v]][prev_e[v]][1]) v=prev_v[v] flow-=f mincost+=f*dist[sink] v=sink while v!=source: E[prev_v[v]][prev_e[v]][1]-=f rev=E[prev_v[v]][prev_e[v]][3] E[v][rev][1]+=f v=prev_v[v] return mincost n=int(input()) J=[] L_org,D_org=[1]*n,[1]*n for _ in range(n): x,y,v=map(int,input().split()) J.append((x,y,v)) m=int(input()) T=[] for _ in range(m): t,a,b=input().split() a,b=int(a),int(b) T.append((t,a,b)) if t=='L': L_org[b]=a+1 elif t=='D': D_org[b]=a+1 for i in range(1,n): L_org[i]=max(L_org[i-1],L_org[i]) D_org[i]=max(D_org[i-1],D_org[i]) def solve(k): L,D=L_org[:k],D_org[:k] R,U=[100]*k,[100]*k for t,a,b in T: if k-b-1>=0: if t=='R': R[k-b-1]=a-1 elif t=='U': U[k-b-1]=a-1 for i in range(k-2,-1,-1): R[i]=min(R[i],R[i+1]) U[i]=min(U[i],U[i+1]) solver=MinCostFlow(2*n+2*k+2) for i in range(1,k+1): solver.add_edge(0,i,1,0) solver.add_edge(2*n+k+i,2*n+2*k+1,1,0) for i in range(n): v=J[i][2] solver.add_edge(k+i+1,n+k+i+1,1,-v) for i in range(n): x,y=J[i][0],J[i][1] l=bisect_right(L,x) r=bisect_left(R,x)+1 d=bisect_right(D,y) u=bisect_left(U,y)+1 for j in range(r,l+1): solver.add_edge(j,k+i+1,1,0) for j in range(u,d+1): solver.add_edge(n+k+i+1,2*n+k+j,1,0) return -solver.MinCost(0,2*n+2*k+1,k) ans=0 k=1 while True: tmp=solve(k) ans=max(ans,tmp) if tmp==-1 or k==n: break k+=1 print(ans) ``` No
9,704
Provide a correct Python 3 solution for this coding contest problem. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD "Correct Solution: ``` N = int(input()) XY = [list(map(int, input().split())) for _ in range(N)] MOD = sum(XY[0]) % 2 for x, y in XY: if MOD != (x + y) % 2: print(-1) exit() m = 33 - MOD print(m) D = [2 ** i for i in range(31, -1, -1)] if MOD == 0: D.append(1) print(" ".join(map(str, D))) for x, y in XY: w = "" for d in D: if x + y >= 0 and x - y >= 0: w += "R" x -= d elif x + y < 0 and x - y >= 0: w += "D" y += d elif x + y >= 0 and x - y < 0: w += "U" y -= d else: w += "L" x += d print(w) ```
9,705
Provide a correct Python 3 solution for this coding contest problem. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD "Correct Solution: ``` # -*- coding: utf-8 -*- def solve(): D = list(map((2).__pow__, range(31)[::-1])) wdict = {(True, True):('R',-1,-1), (True, False):('U',-1,1), (False, False):('L',1,1), (False, True):('D',1,-1)} mode = None for _ in [None]*int(input()): x, y = map(int, input().split()) u = x+y if mode is None: mode = 1-u%2 res = str(31+mode) + '\n' + ' '.join(map(str, [1]*mode+D)) W0 = '\n'+'R'*mode elif mode != 1-u%2: return('-1') res += W0 u -= mode v = x-y-mode for d in D: w, a, b = wdict[u>0, v>0] res += w u += a*d v += b*d return str(res) if __name__ == '__main__': print(solve()) ```
9,706
Provide a correct Python 3 solution for this coding contest problem. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD "Correct Solution: ``` n = int(input()) place = [tuple(map(int, input().split())) for _ in range(n)] m = 0 def bitlist(x): ret = [0] * 31 for i in reversed(range(31)): if x > 0: x -= 1 << i ret[i] = 1 else: x += 1 << i ret[i] = -1 return ret pre = (place[0][0] + place[0][1] + 1) % 2 for x, y in place: if (x + y + 1) % 2 != pre: print(-1) exit() print(31 + pre) if pre: print(1, end = ' ') for i in reversed(range(31)): print(1 << i, end = ' ') print() for x, y in place: u = x + y v = x - y if pre: u -= 1 v -= 1 ubit = bitlist(u) vbit = bitlist(v) if pre: print('R', end = '') for i in reversed(range(31)): if ubit[i] == 1 and vbit[i] == 1: print('R', end = '') elif ubit[i] == 1 and vbit[i] == -1: print('U', end = '') elif ubit[i] == -1 and vbit[i] == -1: print('L', end = '') else: print('D', end = '') print() ```
9,707
Provide a correct Python 3 solution for this coding contest problem. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD "Correct Solution: ``` n = int(input()) grid = [list(map(int, input().split())) for i in range(n)] for i in range(n - 1): if (grid[i][0] + grid[i][1]) % 2 != (grid[i + 1][0] + grid[i + 1][1]) % 2: print(-1) exit() m = 31 D = [2 ** i for i in range(m)] if (grid[0][0] + grid[0][1]) % 2 == 0: D.insert(0, 1) m += 1 w = [[] for i in range(n)] for i, g in enumerate(grid): x, y = g for d in D[::-1]: if abs(x) >= abs(y): if x > 0: x -= d w[i].append('R') else: x += d w[i].append('L') else: if y > 0: y -= d w[i].append('U') else: y += d w[i].append('D') print(m) print(*D) for ans in w: print(*ans[::-1], sep='') ```
9,708
Provide a correct Python 3 solution for this coding contest problem. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD "Correct Solution: ``` N = int(input()) XY = [] parity = [] for _ in range(N): xy = list(map(int, input().split())) XY.append(xy) parity.append(sum(xy)) def check(ds, l, xy): x = 0 y = 0 for i in range(len(ds)): if l[i] == "R": x += ds[i] elif l[i] == "L": x -= ds[i] elif l[i] == "U": y += ds[i] elif l[i] == "D": y -= ds[i] else: raise Exception return (x == xy[0]) & (y == xy[1]) if len(list(set([i % 2 for i in parity]))) == 2: print(-1) elif parity[0] % 2 == 0: print(33) ds = [1, 1] + [2 ** k for k in range(1, 32)] print(*ds) for xy in XY: rev_ans = "" curr_x, curr_y = 0, 0 for d in ds[::-1]: x_diff = xy[0] - curr_x y_diff = xy[1] - curr_y if abs(x_diff) >= abs(y_diff): if x_diff >= 0: rev_ans += "R" curr_x += d else: rev_ans += "L" curr_x -= d else: if y_diff >= 0: rev_ans += "U" curr_y += d else: rev_ans += "D" curr_y -= d print(rev_ans[::-1]) # print(check(ds, list(rev_ans[::-1]), xy)) else: # odd print(32) ds = [2 ** k for k in range(32)] print(*ds) for xy in XY: rev_ans = "" curr_x, curr_y = 0, 0 for d in ds[::-1]: x_diff = xy[0] - curr_x y_diff = xy[1] - curr_y if abs(x_diff) >= abs(y_diff): if x_diff >= 0: rev_ans += "R" curr_x += d else: rev_ans += "L" curr_x -= d else: if y_diff >= 0: rev_ans += "U" curr_y += d else: rev_ans += "D" curr_y -= d print(rev_ans[::-1]) # print(check(ds, list(rev_ans[::-1]), xy)) ```
9,709
Provide a correct Python 3 solution for this coding contest problem. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD "Correct Solution: ``` N = int(input()) point = [tuple(map(int, input().split())) for i in range(N)] point_farthest = max(point, key=lambda p: abs(p[0]) + abs(p[1])) mod = sum(point_farthest) % 2 D = [1, 1] if mod == 0 else [1] while sum(D) < abs(point_farthest[0]) + abs(point_farthest[1]): D.append(D[-1] * 2) D.reverse() W = [] for x, y in point: if (x + y) % 2 != mod: print(-1) exit() w = '' for d in D: if abs(x) >= abs(y): if x > 0: w += 'R' x -= d else: w += 'L' x += d else: if y > 0: w += 'U' y -= d else: w += 'D' y += d W.append(w) print(len(D)) print(*D) print(*W, sep='\n') ```
9,710
Provide a correct Python 3 solution for this coding contest problem. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD "Correct Solution: ``` import sys def f(s,t): if s>=t and -s<=t: return 0 elif s<=t and -s<=t: return 1 elif s<=t and -s>=t: return 2 else: return 3 n=int(input()) xy=[list(map(int,input().split())) for i in range(n)] for i in range(1,n): if sum(xy[i])%2!=sum(xy[i-1])%2: print(-1) sys.exit() data_1=["R","U","L","D"] data_2=[[1,0],[0,1],[-1,0],[0,-1]] arms=[2**i for i in range(32)] if sum(xy[0])%2==1: print(len(arms)) print(*arms) for X,Y in xy: x,y=X,Y ans=[] i=31 while i>=0: c=f(x,y) ans.append(data_1[c]) x-=arms[i]*data_2[c][0] y-=arms[i]*data_2[c][1] i-=1 print("".join(ans[::-1])) else: arms=[1]+arms print(len(arms)) print(*arms) for X,Y in xy: x,y=X,Y ans=[] i=32 while i>=1: c=f(x,y) ans.append(data_1[c]) x-=arms[i]*data_2[c][0] y-=arms[i]*data_2[c][1] i-=1 if x==1: ans.append("R") elif x==-1: ans.append("L") elif y==1: ans.append("U") else: ans.append("D") print("".join(ans[::-1])) ```
9,711
Provide a correct Python 3 solution for this coding contest problem. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD "Correct Solution: ``` N, *XY = map(int, open(0).read().split()) XY = list(zip(*[iter(XY)] * 2)) mod = sum(XY[0]) % 2 if any((x + y) % 2 != mod for x, y in XY): print(-1) quit() D = [2 ** i for i in reversed(range(32))] + [1] * (mod == 0) print(len(D)) print(*D) for x, y in XY: A = [] for d in D: if 0 <= x - y and 0 <= x + y: A.append("R") x -= d elif x - y < 0 and 0 <= x + y: A.append("U") y -= d elif 0 <= x - y and x + y < 0: A.append("D") y += d else: A.append("L") x += d print("".join(A)) ```
9,712
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD Submitted Solution: ``` n=int(input()) xy=[list(map(int,input().split()))for _ in range(n)] g=39 a=[] if sum(xy[0])%2==0:a.append(1) for i in range(g):a.append(1<<i) g=len(a) for x,y in xy: if (x+y)%2!=sum(xy[0])%2:exit(print(-1)) print(g) print(*a) def f(s): t=s ans=[] for i in a[::-1]: if abs(t-i)<abs(t+i): ans.append(-i) t-=i else: ans.append(i) t+=i return ans[::-1] for x,y in xy: xpy=f(-(x+y)) xmy=f(-(x-y)) ans="" for p,m in zip(xpy,xmy): if 0<p and 0<m:ans+="R" if p<0 and m<0:ans+="L" if 0<p and m<0:ans+="U" if p<0 and 0<m:ans+="D" print(ans) ``` Yes
9,713
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD Submitted Solution: ``` def cal(i,j): if i==1 and j==1: return "R" elif i==1 and j==0: return "U" elif i==0 and j==1: return "D" elif i==0 and j==0: return "L" import sys N=int(input()) a=[list(map(int,input().split())) for i in range(N)] mod=sum(a[0])%2 for i in range(N): if sum(a[i])%2!=mod: print(-1) sys.exit() if mod==0: a=[[ a[i][0]-1 ,a[i][1] ] for i in range(N)] if mod==0: print(32) print(1,end=" ") for i in range(30): print(2**i, end=" ") print(2**30) else: print(31) for i in range(30): print(2**i, end=" ") print(2**30) for i in range(N): [x,y]=a[i] u=bin((x+y+2**31-1)//2)[2:].zfill(31) v=bin((x-y+2**31-1)//2)[2:].zfill(31) if mod==0: s="R" else: s="" for i in range(30,-1,-1): s=s+cal( int(u[i]),int(v[i]) ) print(s) ``` Yes
9,714
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD Submitted Solution: ``` import sys input = sys.stdin.readline N = int(input()) a = [] mx = 0 for _ in range(N): x, y = map(int, input().split()) u = x + y v = x - y a.append((u, v)) mx = max(mx, max(abs(u), abs(v))) t = a[0][0] % 2 for u, _ in a: if u % 2 != t: print(-1) exit(0) d = [pow(2, i) for i in range(mx.bit_length())] if t == 0: d = [1] + d print(len(d)) print(*d) for u, v in a: s = [0] * len(d) t = [0] * len(d) x = 0 y = 0 res = [] for i in range(len(d) - 1, -1, -1): z = d[i] if u < x: x -= z s[i] = -1 else: x += z s[i] = 1 if v < y: y -= z t[i] = -1 else: y += z t[i] = 1 for i in range(len(d)): if s[i] == 1 and (t[i] == 1): res.append("R") elif s[i] == -1 and (t[i] == -1): res.append("L") elif s[i] == 1 and (t[i] == -1): res.append("U") elif s[i] == -1 and (t[i] == 1): res.append("D") print("".join(res)) ``` Yes
9,715
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD Submitted Solution: ``` def main(): """ ロボットアーム 腕、関節 arm_1, arm_2,...,arm_m k_0, k_1, k_2,..., k_m k_i-1, arm_i, k_i arm_i_length: d_i mode: L, R, D, U (x0, y0) = (0, 0) L: (x_i, y_i) = (x_i-1 - d_i, y_i-1) R: (x_i, y_i) = (x_i-1 + d_i, y_i-1) U: (x_i, y_i) = (x_i-1, y_i-1 - d_i) D: (x_i, y_i) = (x_i-1, y_i-1 + d_i) input: 1 <= N <= 10^3 -10^9 <= Xi <= 10^9 -10^9 <= Yi <= 10^9 output: NG: -1 OK: m d1 d2 ... dm w1 w2 ... wN 1 <= m <= 40 1 <= d_i <= 10^12 w_i: {L, R, U, D}, w_i_lenght = m 動かし方の例は、入力例1参照 """ N = int(input()) X, Y = zip(*( map(int, input().split()) for _ in range(N) )) # m, d, w = part_300(N, X, Y) m, d, w = ref(N, X, Y) if m == -1: print(-1) else: print(m) print(*d) print(*w, sep="\n") def ex1(N, X, Y): m = 2 d = [1, 2] w = ["RL", "UU", "DR"] return m, d, w def part_300(N, X, Y): """ 1つ1つのクエリに対する操作は独立 ただし、使うパラメータm, d は共通 部分点は以下の制約 -10 <= i <= 10 -10 <= i <= 10 探索範囲 20 * 20 この範囲においてm<=40で到達するためのd d=1のとき|X|+|Y|の偶奇 揃っている場合、mは最大に合わせる、余っているときはRLのように移動なしにできる 揃っていない場合, d=1では不可能? 2と1およびLR,UDを駆使して-1を再現して偶奇を揃える? 無理っぽい: 奇数しか作れない """ dists = [] for x, y in zip(X, Y): dist = abs(x) + abs(y) dists.append(dist) m = -1 d = [] w = [] mod = list(map(lambda x: x % 2, dists)) if len(set(mod)) == 1: m = max(dists) d = [1] * m for x, y, dist in zip(X, Y, dists): x_dir = "R" if x > 0 else "L" y_dir = "U" if y > 0 else "D" _w = x_dir * abs(x) + y_dir * abs(y) rest = m - len(_w) if rest > 0: _w += "LR" * (rest // 2) w.append(_w) return m, d, w def editorial(N, X, Y): """ 2冪の数の組合せにより、どの点にでも移動できるようになる ※ただし、奇数のみ。偶数に対応させたいときは1での移動を追加する 1, 2, 4, 8, 2^0, 2^1, 2^2, 2^3, ... {1} だけでの移動、原点からの1の距離。当たり前 x: 原点 b -------cxa------ d {1, 2} での移動、原点から1の距離から2移動できる a-d を基準に考えると a-d をa方向に2移動: a方向に菱形の移動範囲が増える a-d をb方向に2移動: b a-d をc方向に2移動: c a-d をd方向に2移動: d b b b c b a c cxa a c d a d d d https://twitter.com/CuriousFairy315/status/1046073372315209728 https://twitter.com/schwarzahl/status/1046031849221316608 どうして(u, v)=(x+y, x-y)的な変換を施す必要があるのか? https://twitter.com/ILoveTw1tter/status/1046062363831660544 http://drken1215.hatenablog.com/entry/2018/09/30/002900 x 座標, y 座標両方頑張ろうと思うと、60 個くらい欲しくなる。で、困っていた。 U | L----o----R | D # TODO U\ /R \ / \/ / \ / \ L/ \D """ pass def ref(N, X, Y): dists = [] for x, y in zip(X, Y): dist = (abs(x) + abs(y)) % 2 dists.append(dist) m = -1 d = [] w = [] mod = set(map(lambda x: x % 2, dists)) if len(mod) != 1: return m, d, w for i in range(30, 0-1, -1): d.append(1 << i) if 0 in mod: d.append(1) m = len(d) w1 = transform_xy(N, X, Y, d) # w2 = no_transform_xy(N, X, Y, d) # assert w1 == w2 return m, d, w1 def transform_xy(N, X, Y, d): """ http://kagamiz.hatenablog.com/entry/2014/12/21/213931 """ # 変換: θ=45°, 分母は共通の√2 なので払ってしまうと下記の式になる trans_x = [] trans_y = [] for x, y in zip(X, Y): trans_x.append(x + y) trans_y.append(x - y) plot = False if plot: import matplotlib.pyplot as plt plt.axhline(0, linestyle="--") plt.axvline(0, linestyle="--") # denominator: 分母 deno = 2 ** 0.5 plt.scatter(X, Y, label="src") plt.scatter([x / deno for x in trans_x], [y / deno for y in trans_y], label="trans") for x, y, x_src, y_src in zip(trans_x, trans_y, X, Y): plt.text(x_src, y_src, str((x_src, y_src))) plt.text(x / deno, y / deno, str((x_src, y_src))) plt.legend() plt.show() # print(*zip(X, Y)) # print(*zip(trans_x, trans_y)) w = [] dirs = { # dir: x', y' (-1, -1): "L", # 本来の座標(x, y): (-1, 0), 変換後: (-1+0, -1-0) (+1, +1): "R", # 本来の座標(x, y): (+1, 0), 変換後: (+1+0, +1-0) # 感覚と違うのは、変換の仕方 (+1, -1): "U", # 本来の座標(x, y): ( 0, +1), 変換後: ( 0+1, 0-(-1)) (-1, +1): "D", # 本来の座標(x, y): ( 0, -1), 変換後: ( 0-1, 0-(+1)) } for x, y in zip(trans_x, trans_y): x_sum = 0 y_sum = 0 _w = "" for _d in d: # 変換後の座標でx',y'を独立に求めている if x_sum <= x: x_dir = 1 x_sum += _d else: x_dir = -1 x_sum -= _d if y_sum <= y: y_dir = 1 y_sum += _d else: y_dir = -1 y_sum -= _d _w += dirs[(x_dir, y_dir)] w.append(_w) return w def no_transform_xy(N, X, Y, d): w = [] for x, y in zip(X, Y): x_sum, y_sum = 0, 0 _w = "" for _d in d: # 変化量の大きい方を優先する if abs(x_sum - x) >= abs(y_sum - y): if x_sum >= x: x_sum -= _d _w += "L" else: x_sum += _d _w += "R" else: if y_sum >= y: y_sum -= _d _w += "D" else: y_sum += _d _w += "U" w.append(_w) return w if __name__ == '__main__': main() ``` Yes
9,716
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD Submitted Solution: ``` N = int(input()) point = [] dist = [] for _ in range(N) : x, y = map(int, input().split()) point.append((x, y)) dist.append(abs(x) + abs(y)) distSort = sorted(dist) maxDist = dist[-1] for d in distSort : if (maxDist - d) % 2 == 1 : # 実現不可能 print(-1) break else : # 実現可能 print(maxDist) # 腕の数 for _ in range(maxDist) : print('1 ', end='') print('') for x, y in point : for _ in range(abs(x)) : if x < 0 : print('L', end='') else : print('R', end='') for _ in range(abs(y)) : if y < 0 : print('D', end='') else : print('U', end='') for i in range((maxDist - (abs(x) + abs(y))) // 2) : print('LR', end='') print('') ``` No
9,717
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD Submitted Solution: ``` import sys N = int(input()) XY = [[int(_) for _ in input().split()] for i in range(N)] mc = [0, 0] maxl = 0 for x, y in XY: l = abs(x) + abs(y) maxl = max(maxl, l) mc[l % 2] += 1 if mc[0] > 0 and mc[1] > 0: print(-1) sys.exit() #if maxl > 20: # raise def calc(sx, sy, dx, dy, d): #print("#", sx, sy, dx, dy) x = dx - sx y = dy - sy tx = x + 3 * d - y ty = x + 3 * d + y dirs = ("LL", "LD", "DD"), ("LU", "UD", "RD"), ("UU", "RU", "RR") ds = {"R": (+d, 0), "L": (-d, 0), "U": (0, +d), "D": (0, -d)} dir = dirs[ty // (2 * d)][tx // (2 * d)] ex, ey = sx, sy for d in dir: ex += ds[d][0] ey += ds[d][1] #print("*", dir, ex, ey) return dir, ex, ey ds = [] ds0 = [] for i in range(19): d = 3 ** (19 - i) ds.append(d) ds0.append(d) ds0.append(d) w0 = "" x0, y0 = 0, 0 if mc[1] > 0: ds0 = [1] + ds0 w0 += "R" x0 += 1 print(len(ds0)) print(*ds0) for i in range(N): w = w0 x, y = x0, y0 for j, d in enumerate(ds): wc, x, y = calc(x, y, XY[i][0], XY[i][1], d) w += wc print(w) ``` No
9,718
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD Submitted Solution: ``` from collections import defaultdict N = int(input()) XY = [list(map(int, input().split())) for _ in [0] * N] md = lambda xy: sum(map(abs,xy)) s = md(XY[0]) % 2 for xy in XY: if s != md(xy) % 2: print(-1) exit() mdxy = [md(xy) for xy in XY] m = max(mdxy) print(m) print(*[1] * m) for x, y in XY: res = [] for i in range(m): if x: if x > 0: res += ['R'] x -= 1 elif x < 0: res += ['L'] x += 1 elif y: if y > 0: res += ['U'] y += 1 elif y < 0: res += ['D'] y -= 1 else: if i % 2: res += ['R'] else: res += ['L'] print(''.join(res)) ``` No
9,719
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)): * (x_0, y_0) = (0, 0). * If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}). * If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}). * If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}). * If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}). Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections. Is this possible? If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j). Constraints * All values in input are integers. * 1 \leq N \leq 1000 * -10^9 \leq X_i \leq 10^9 * -10^9 \leq Y_i \leq 10^9 Input Input is given from Standard Input in the following format: N X_1 Y_1 X_2 Y_2 : X_N Y_N Output If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print `-1`. m d_1 d_2 ... d_m w_1 w_2 : w_N m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers. w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the letters `L`, `R`, `D` and `U`, representing the mode of Section i. Examples Input 3 -1 0 0 3 2 -1 Output 2 1 2 RL UU DR Input 5 0 0 1 0 2 0 3 0 4 0 Output -1 Input 2 1 1 1 1 Output 2 1 1 RU UR Input 3 -7 -3 7 3 -3 -7 Output 5 3 1 4 1 5 LRDUL RDULR DULRD Submitted Solution: ``` n = int(input()) x = [list(map(int, input().split())) for _ in range(n)] a = [abs(p[0])+abs(p[1]) for p in x] t = max(a) b = [q%2 for q in a] if len(set(b)) != 1: print(-1) exit() print(t) for i in range(t): print("1 ", end="") print() for i in range(n): ch1 = ch2 = "" if x[i][0] >= 0: ch1 = "R" else: ch1 = "L" if x[i][1] >= 0: ch2 = "U" else: ch2 = "D" for j in range((t-a[i])//2): print("RL", end="") for j in range(abs(x[i][0])): print(ch1, end="") for j in range(abs(x[i][1])): print(ch2, end="") print() ``` No
9,720
Provide a correct Python 3 solution for this coding contest problem. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 "Correct Solution: ``` x=int(input()) y=int(input()) print(y+(y-x)) ```
9,721
Provide a correct Python 3 solution for this coding contest problem. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 "Correct Solution: ``` r = int(input());g = int(input()); print(2 * g - r) ```
9,722
Provide a correct Python 3 solution for this coding contest problem. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 "Correct Solution: ``` l = int(input()) l2 = int(input()) print(l+(l2-l)*2) ```
9,723
Provide a correct Python 3 solution for this coding contest problem. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 "Correct Solution: ``` r=int(input()) g=int(input()) x = int((g*2)-r) print(x) ```
9,724
Provide a correct Python 3 solution for this coding contest problem. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 "Correct Solution: ``` r=int(input()) s=int(input()) print(2*s-r) ```
9,725
Provide a correct Python 3 solution for this coding contest problem. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 "Correct Solution: ``` a = int(input()) g = int(input()) print(g-a+g) ```
9,726
Provide a correct Python 3 solution for this coding contest problem. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 "Correct Solution: ``` R=int(input()) G=int(input()) print((G-R)+G) ```
9,727
Provide a correct Python 3 solution for this coding contest problem. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 "Correct Solution: ``` a = int(input()) g = 2 * int(input()) print(g - a) ```
9,728
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 Submitted Solution: ``` x=int(input()) y=int(input()) print(y+y-x) ``` Yes
9,729
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 Submitted Solution: ``` x = int(input()) y = int(input()) print(y - x + y) ``` Yes
9,730
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 Submitted Solution: ``` n=int(input()) m=int(input()) l=m*2-n print(l) ``` Yes
9,731
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 Submitted Solution: ``` R=int(input()) G=int(input()) a=2*G-R print(a) ``` Yes
9,732
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 Submitted Solution: ``` R,G = map(int,input().split()) print((2*G)-R) ``` No
9,733
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 Submitted Solution: ``` r=int(input()) g=int(input()) print(g*2−r) ``` No
9,734
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 Submitted Solution: ``` g,r=map(int,input().split()) print(2*g-r) ``` No
9,735
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. * Then, the new rating of the user will be the avarage of a and b. For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000. Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest. Find the performance required to achieve it. Constraints * 0 \leq R, G \leq 4500 * All input values are integers. Input Input is given from Standard Input in the following format: R G Output Print the performance required to achieve the objective. Examples Input 2002 2017 Output 2032 Input 4500 0 Output -4500 Submitted Solution: ``` s = list(input()) t = list(input()) def eq(s, t): for i in range(len(s)): if s[i] != t[i] and s[i] != '?': return False return True for i in reversed(range(len(s) - len(t)+1)): if eq(s[i:i+len(t)], t[:]): s[i:i + len(t)] = t[:] ans = ''.join(s) print(ans.replace('?', 'b')) quit() print('UNRESTORABLE') ``` No
9,736
Provide a correct Python 3 solution for this coding contest problem. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 "Correct Solution: ``` from collections import deque INF = float("inf") TO = 0; CAP = 1; REV = 2 class Dinic: def __init__(self, N): self.N = N self.V = [[] for _ in range(N)] # to, cap, rev # 辺 e = V[n][m] の逆辺は V[e[TO]][e[REV]] self.level = [0] * N def add_edge(self, u, v, cap): self.V[u].append([v, cap, len(self.V[v])]) self.V[v].append([u, 0, len(self.V[u])-1]) def add_edge_undirected(self, u, v, cap): # 未検証 self.V[u].append([v, cap, len(self.V[v])]) self.V[v].append([u, cap, len(self.V[u])-1]) def bfs(self, s: int) -> bool: self.level = [-1] * self.N self.level[s] = 0 q = deque() q.append(s) while len(q) != 0: v = q.popleft() for e in self.V[v]: if e[CAP] > 0 and self.level[e[TO]] == -1: # capが1以上で未探索の辺 self.level[e[TO]] = self.level[v] + 1 q.append(e[TO]) return True if self.level[self.g] != -1 else False # 到達可能 def dfs(self, v: int, f) -> int: if v == self.g: return f for i in range(self.ite[v], len(self.V[v])): self.ite[v] = i e = self.V[v][i] if e[CAP] > 0 and self.level[v] < self.level[e[TO]]: d = self.dfs(e[TO], min(f, e[CAP])) if d > 0: # 増加路 e[CAP] -= d # cap を減らす self.V[e[TO]][e[REV]][CAP] += d # 反対方向の cap を増やす return d return 0 def solve(self, s, g): self.g = g flow = 0 while self.bfs(s): # 到達可能な間 self.ite = [0] * self.N f = self.dfs(s, INF) while f > 0: flow += f f = self.dfs(s, INF) return flow H, W = map(int, input().split()) dinic = Dinic(H+W+2) for i in range(H): a = input() for j, a_ in enumerate(a): if a_=="S": start = i, j elif a_=="T": goal = i, j if a_!=".": dinic.add_edge_undirected(H + j, i, 1) dinic.add_edge_undirected(H+W, start[0], 1<<30) dinic.add_edge_undirected(H+W, start[1]+H, 1<<30) dinic.add_edge_undirected(H+W+1, goal[0], 1<<30) dinic.add_edge_undirected(H+W+1, goal[1]+H, 1<<30) if start[0]==goal[0] or start[1]==goal[1]: print(-1) else: print(dinic.solve(H+W, H+W+1)) ```
9,737
Provide a correct Python 3 solution for this coding contest problem. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 "Correct Solution: ``` import sys sys.setrecursionlimit(1000000) def FF(E, s, t): NN = H+W+2 G = [[] for _ in range(NN)] for a, b, f in E: G[a].append([b, f, len(G[b])]) G[b].append([a, 0, len(G[a])-1]) def dfs(s, t, f): if s == t: return f used[s] = 1 for i, (b, _f, r) in enumerate(G[s]): if used[b] or _f == 0: continue d = dfs(b, t, min(f, _f)) if d > 0: G[s][i][1] -= d G[b][r][1] += d return d return 0 flow = 0 while 1: used = [0] * NN f = dfs(s, t, 10**100) if f == 0: return flow flow += f E = [] H, W = map(int, input().split()) for i in range(H): A = input() for j in range(W): if A[j] == "o": E.append((i, j+H, 1)) E.append((j+H, i, 1)) elif A[j] == "S": S = (i, j+H) elif A[j] == "T": T = (i, j+H) E.append((H+W, S[0], 10**6)) E.append((H+W, S[1], 10**6)) E.append((T[0], H+W+1, 10**6)) E.append((T[1], H+W+1, 10**6)) ff = FF(E, H+W, H+W+1) print(ff if ff < 10**6 else -1) ```
9,738
Provide a correct Python 3 solution for this coding contest problem. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 "Correct Solution: ``` # https://tjkendev.github.io/procon-library/python/max_flow/dinic.html # Dinic's algorithm from collections import deque class Dinic: def __init__(self, N): self.N = N self.G = [[] for i in range(N)] def add_edge(self, fr, to, cap): forward = [to, cap, None] forward[2] = backward = [fr, 0, forward] self.G[fr].append(forward) self.G[to].append(backward) def add_multi_edge(self, v1, v2, cap1, cap2): edge1 = [v2, cap1, None] edge1[2] = edge2 = [v1, cap2, edge1] self.G[v1].append(edge1) self.G[v2].append(edge2) def bfs(self, s, t): self.level = level = [None]*self.N deq = deque([s]) level[s] = 0 G = self.G while deq: v = deq.popleft() lv = level[v] + 1 for w, cap, _ in G[v]: if cap and level[w] is None: level[w] = lv deq.append(w) return level[t] is not None def dfs(self, v, t, f): if v == t: return f level = self.level for e in self.it[v]: w, cap, rev = e if cap and level[v] < level[w]: d = self.dfs(w, t, min(f, cap)) if d: e[1] -= d rev[1] += d return d return 0 def flow(self, s, t): flow = 0 INF = 10**9 + 7 G = self.G while self.bfs(s, t): *self.it, = map(iter, self.G) f = INF while f: f = self.dfs(s, t, INF) flow += f return flow # coding: utf-8 # Your code here! import sys read = sys.stdin.read readline = sys.stdin.readline h,w = map(int,readline().split()) b = read().split() #g = [[] for _ in range(h+w+2)] S = h+w T = h+w+1 D = Dinic(h+w+2) for i in range(h): for j in range(w): if b[i][j] == "S": #print("S") sh,sw = i,j D.add_edge(S, i, 200) D.add_edge(S, j+h, 200) #g[S].append((i,200)) #g[S].append((j+h,200)) elif b[i][j] == "T": #print("T") th,tw = i,j D.add_edge(i, T, 200) D.add_edge(j+h, T, 200) #g[i].append((T,200)) #g[j+h].append((T,200)) elif b[i][j] == "o": #print("o") D.add_edge(i, j+h, 1) D.add_edge(j+h, i, 1) #g[i].append((j+h,1)) #g[j+h].append((i,1)) if sh==th or sw==tw: print(-1) else: print(D.flow(S,T)) ```
9,739
Provide a correct Python 3 solution for this coding contest problem. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 "Correct Solution: ``` from collections import deque class mf_graph: n=1 g=[[] for i in range(1)] pos=[] def __init__(self,N): self.n=N self.g=[[] for i in range(N)] def add_edge(self,From,To,cap): assert 0<=From and From<self.n assert 0<=To and To<self.n assert 0<=cap m=len(self.pos) self.pos.append((From,len(self.g[From]))) self.g[From].append({"to":To,"rev":len(self.g[To]),"cap":cap}) self.g[To].append({"to":From,"rev":len(self.g[From])-1,"cap":0}) return m def get_edge(self,i): m=len(self.pos) assert 0<=i and i<m _e=self.g[self.pos[i][0]][self.pos[i][1]] _re=self.g[_e["to"]][_e["rev"]] return {"from":self.pos[i][0], "to":_e["to"], "cap":_e["cap"]+_re["cap"], "flow":_re["cap"]} def edges(self): m=len(self.pos) result=[] for i in range(m): result.append(self.get_edge(i)) return result def change_edge(self,i,new_cap,new_flow): m=len(self.pos) assert 0<=i and i<m assert 0<=new_flow and new_flow<=new_cap _e=self.g[self.pos[i][0]][self.pos[i][1]] _re=self.g[_e["to"]][_e["rev"]] _e["cap"]=new_cap-new_flow _re["cap"]=new_flow def flow(self,s,t,flow_limit=(2**31)-1): assert 0<=s and s<self.n assert 0<=t and t<self.n level=[0 for i in range(self.n)] Iter=[0 for i in range(self.n)] que=deque([]) def bfs(): for i in range(self.n): level[i]=-1 level[s]=0 que=deque([]) que.append(s) while(len(que)>0): v=que.popleft() for e in self.g[v]: if e["cap"]==0 or level[e["to"]]>=0:continue level[e["to"]]=level[v]+1 if e["to"]==t:return que.append(e["to"]) def dfs(func,v,up): if (v==s):return up res=0 level_v=level[v] for i in range(Iter[v],len(self.g[v])): e=self.g[v][i] if (level_v<=level[e["to"]] or self.g[e["to"]][e["rev"]]["cap"]==0):continue d=func(func,e["to"],min(up-res,self.g[e["to"]][e["rev"]]["cap"])) if d<=0:continue self.g[v][i]["cap"]+=d self.g[e["to"]][e["rev"]]["cap"]-=d res+=d if res==up:break return res flow=0 while(flow<flow_limit): bfs() if level[t]==-1: break for i in range(self.n): Iter[i]=0 while(flow<flow_limit): f=dfs(dfs,t,flow_limit-flow) if not(f):break flow+=f return flow def min_cut(self,s): visited=[False for i in range(self.n)] que=deque([]) que.append(s) while(len(que)>0): p=que.popleft() visited[p]=True for e in self.g[p]: if e["cap"] and not(visited[e["to"]]): visited[e["to"]]=True que.append(e["to"]) return visited H,W=map(int,input().split()) a=[list(input()) for i in range(H)] G=mf_graph(H+W+2) INF=10**9 s=H+W t=H+W+1 for i in range(H): for j in range(W): if a[i][j]=="S": G.add_edge(s,i,INF) G.add_edge(s,j+H,INF) if a[i][j]=="T": G.add_edge(i,t,INF) G.add_edge(j+H,t,INF) if a[i][j]!=".": G.add_edge(i,j+H,1) G.add_edge(j+H,i,1) ans=G.flow(s,t) if ans>=INF: print(-1) else: print(ans) ```
9,740
Provide a correct Python 3 solution for this coding contest problem. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 "Correct Solution: ``` """ .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo グラフを作る ⇛ SからTにたどり着く個数を全探索 ⇛ たどり着く直前の座標を保持 ⇛ 直前のバリエーション 解説AC ⇛ 行内、列内は自由に動ける ⇛ 行/列のどこかにいる状態でもたせる ⇛ 点の上は行⇔列の切り替えが出来るので、cap==1とする ⇛ 結局MaxCutをしているのと一緒!! """ from collections import deque from collections import defaultdict import sys sys.setrecursionlimit(100000) class Dinic: def __init__(self): # self.N = N self.G = defaultdict(list) def add_edge(self, fr, to, cap): """ :param fr: 始点 :param to: 終点 :param cap: 容量 """ # forwardの最後には、キャパのうちどれだけ使ったかが入る forward = [to, cap, None] backward = [fr, 0, forward] forward[-1] = backward self.G[fr].append(forward) self.G[to].append(backward) def add_multi_edge(self, v1, v2, cap1, cap2): """ :param v1: 始点 :param v2: 終点 :param cap1: 容量1 :param cap2: 容量2 """ edge1 = [v2, cap1, None] edge2 = [v1, cap2, edge1] edge1[-1] = edge2 self.G[v1].append(edge1) self.G[v2].append(edge2) def bfs(self, s, t): """ :param s: bfsの始点(source) :param t: bfsの終点(sink) :return: tに到達したかどうか。(sourceからの距離を保存しながら) """ self.level = level = defaultdict(int) q = deque([s]) level[s] = 1 G = self.G while len(q) > 0: v = q.popleft() lv = level[v] + 1 nexts = G[v] for w, cap, _ in nexts: if cap > 0 and level[w] == 0: level[w] = lv q.append(w) is_reach = (level[t] > 0) return is_reach def dfs(self, v, t, f): """ :param v: 点v :param t: 終点(sink) :param f: v時点でのフロー :return: 終点到達時のフローを返す """ if v == t: return f level = self.level nexts = self.G[v] for edge in nexts: w, cap, rev = edge # まだキャパがあるならば if cap > 0 and level[v] < level[w]: # キャパが余ってるなら全部流すし # カツカツならキャパのmaxまで流す d = self.dfs(w, t, min(f, cap)) # 帰りがけに、更新 if d > 0: # 順方向のキャパをd下げる # 逆方向のキャパをd増やす edge[1] -= d rev[1] += d return d # 次の道が見つからなければ終了 return 0 def flow(self, s, t): """ :param s: 始点 :param t: 終点 :return : 最大フロー """ flow = 0 INF = 10**10 G = self.G # ルートが存在する限り、続ける while self.bfs(s, t): f = INF while f > 0: f = self.dfs(s, t, INF) flow += f return flow ans = set() H, W = map(int, input().split()) fields = [] for i in range(H): inp = list(input()) fields.append(inp) dinic = Dinic() start = -1 end = -2 INF = 10**10 for i in range(H): for j in range(W): if fields[i][j] == "T": dinic.add_edge(i,end,INF) dinic.add_edge(j+H,end,INF) if fields[i][j] == "S": dinic.add_edge(start,i,INF) dinic.add_edge(start,j+H,INF) if fields[i][j] != ".": dinic.add_edge(i,j+H,1) dinic.add_edge(j+H,i,1) ans = dinic.flow(start,end) if ans > INF:print(-1) else:print(ans) ```
9,741
Provide a correct Python 3 solution for this coding contest problem. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 "Correct Solution: ``` import collections class Dinic: def __init__(self, vnum): self.edge = [[] for i in range(vnum)] self.n = vnum self.inf = float('inf') def addedge(self, st, en, c): self.edge[st].append([en, c, len(self.edge[en])]) self.edge[en].append([st, 0, len(self.edge[st])-1]) def bfs(self, vst): dist = [-1]*self.n dist[vst] = 0 Q = collections.deque([vst]) while Q: nv = Q.popleft() for vt, c, r in self.edge[nv]: if dist[vt] == -1 and c > 0: dist[vt] = dist[nv] + 1 Q.append(vt) self.dist = dist def dfs(self, nv, en, nf): nextv = self.nextv if nv == en: return nf dist = self.dist ist = nextv[nv] for i, (vt, c, r) in enumerate(self.edge[nv][ist:], ist): if dist[nv] < dist[vt] and c > 0: df = self.dfs(vt, en, min(nf, c)) if df > 0: self.edge[nv][i][1] -= df self.edge[vt][r][1] += df return df nextv[nv] += 1 return 0 def getmf(self, st, en): mf = 0 while True: self.bfs(st) if self.dist[en] == -1: break self.nextv = [0]*self.n while True: fl = self.dfs(st, en, self.inf) if fl > 0: mf += fl else: break return mf H, W = map(int, input().split()) G = [input() for _ in range(H)] T = Dinic(H+W) inf = 10**9+7 SS = [] for i in range(H): for j in range(W): if G[i][j] == '.': continue if G[i][j] == 'o': T.addedge(i, H+j, 1) T.addedge(H+j, i, 1) continue SS.append(i) SS.append(H + j) T.addedge(i, H+j, inf) T.addedge(H+j, i, inf) ans = T.getmf(SS[0], SS[-1]) if ans >= 10**9: print(-1) else: print(ans) ```
9,742
Provide a correct Python 3 solution for this coding contest problem. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 "Correct Solution: ``` # 最大流 NUMERIC_LIMITS = 10 ** 18 import queue class maxFlow: class edge: def __init__(s, frm, to, cap, flow): s.frm, s.to = frm, to s.cap, s.flow = cap, flow def __init__(s, n): s._n = n s.g = [[] for _ in range(n)] s.pos = [] def add_edge(s, frm, to, cap): m = len(s.pos) s.pos.append([frm, len(s.g[frm])]) s.g[frm].append(s._edge(to, len(s.g[to]), cap)) s.g[to].append(s._edge(frm,len(s.g[frm]) - 1, 0)) return m def get_edge(s, i): m = len(s.pos) _e = s.g[s.pos[i][0]][s.pos[i][1]] _re = s.g[_e.to][_e.rev] return s.edge(s.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap) def edges(s): m = len(s.pos) result = [] for i in range(m): result.append(s.get_edge(i)) return result def change_edge(s, i, new_cap, new_flow): m = len(s.pos) _e = s.g[s.pos[i].to][s.pos[i].rev] _re = s.g[_e.to][_e.rev] _e.cap = new_cap - new_flow _re.cap = new_flow def flow(self, s, t, flow_limit = NUMERIC_LIMITS): level = [0] * self._n iter = [0] * self._n def bfs(): for i in range(self._n): level[i] = -1 level[s] = 0 que = queue.Queue() que.put(s) while not que.empty(): v = que.get() for e in self.g[v]: if e.cap == 0 or level[e.to] >= 0: continue level[e.to] = level[v] + 1 if e.to == t: return que.put(e.to) def dfs(this, v, up): if v == s: return up res = 0 level_v = level[v] for i in range(iter[v], len(self.g[v])): e = self.g[v][i] if level_v <= level[e.to] or self.g[e.to][e.rev].cap == 0: continue d = this(this, e.to, min(up - res, self.g[e.to][e.rev].cap)) if d <= 0: continue self.g[v][i].cap += d self.g[e.to][e.rev].cap -= d res += d if res == up: break return res flow = 0 while flow < flow_limit: bfs() if level[t] == -1: break for i in range(self._n): iter[i] while flow < flow_limit: f = dfs(dfs, t, flow_limit - flow) if not f: break flow += f return flow def min_cut(self, s): visited = [False] * self._n que = queue.Queue() que.put(s) while not que.empty(): p = que.get() visited[p] = True for e in self.g[p]: if e.cap and not visited[e.to]: visited[e.to] = True que.put(e.to) return visited class _edge: def __init__(s, to, rev, cap): s.to, s.rev = to, rev s.cap = cap H, W = list(map(int, input().split())) a = [list(input()) for _ in range(H)] flow = maxFlow(H + W + 2) s = H + W t = H + W + 1 for h in range(H): for w in range(W): if a[h][w] == "S": flow.add_edge(s, h, H + W + 1) flow.add_edge(s, H + w, H + W + 1) elif a[h][w] == "T": flow.add_edge(h, t, H + W + 1) flow.add_edge(H + w, t, H + W + 1) if a[h][w] != ".": flow.add_edge(h, H + w, 1) flow.add_edge(H + w, h, 1) ans = flow.flow(s, t) if ans > H + W: print(-1) else: print(ans) ```
9,743
Provide a correct Python 3 solution for this coding contest problem. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 "Correct Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from collections import deque H,W = map(int,readline().split()) A = [line.rstrip().decode('utf-8') for line in readlines()] class Dinic: def __init__(self, N, source, sink): self.N = N self.G = [[] for _ in range(N)] self.source = source self.sink = sink def add_edge(self, fr, to, cap): n1 = len(self.G[fr]) n2 = len(self.G[to]) self.G[fr].append([to, cap, n2]) self.G[to].append([fr, 0, n1]) # 逆辺を cap 0 で追加 def bfs(self): level = [0] * self.N G = self.G; source = self.source; sink = self.sink q = deque([source]) level[source] = 1 pop = q.popleft; append = q.append while q: v = pop() lv = level[v] + 1 for to, cap, rev in G[v]: if not cap: continue if level[to]: continue level[to] = lv if to == sink: self.level = level return append(to) self.level = level def dfs(self,v,f): if v == self.sink: return f G = self.G prog = self.progress level = self.level lv = level[v] E = G[v] for i in range(prog[v],len(E)): to, cap, rev = E[i] prog[v] = i if not cap: continue if level[to] <= lv: continue x = f if f < cap else cap ff = self.dfs(to, x) if ff: E[i][1] -= ff G[to][rev][1] += ff return ff return 0 def max_flow(self): INF = 10**18 flow = 0 while True: self.bfs() if not self.level[self.sink]: return flow self.progress = [0] * self.N while True: f = self.dfs(self.source, INF) if not f: break flow += f return flow source = 0 sink = H+W+1 dinic = Dinic(H+W+2, source, sink) add = dinic.add_edge INF = 10 ** 18 for h in range(1,H+1): for w,ox in enumerate(A[h-1],1): if ox == 'x': continue elif ox == 'o': add(h,H+w,1) add(H+w,h,1) elif ox == 'S': add(source,h,INF) add(h,source,INF) add(source,H+w,INF) add(H+w,source,INF) elif ox == 'T': add(sink,h,INF) add(h,sink,INF) add(sink,H+w,INF) add(H+w,sink,INF) f = dinic.max_flow() answer = f if f < INF else -1 print(answer) ```
9,744
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 Submitted Solution: ``` from collections import deque class MaxFlow: """ Example. mf = MaxFlow(N) mf.add_edge(0, 1, 1) mf.add_edge(1, 2, 3) print(mf.max_flow(0, 2)) for fr, to, cap, flow in mf.edges(): print(fr, to, flow) """ def __init__(self, n): self.n = n self.graph = [[] for _ in range(n)] self.pos = [] def add_edge(self, fr, to, cap): m = len(self.pos) self.pos.append((fr, len(self.graph[fr]))) self.graph[fr].append([to, len(self.graph[to]), cap]) self.graph[to].append([fr, len(self.graph[fr]) - 1, 0]) return m def get_edge(self, idx): to, rev, cap = self.graph[self.pos[idx][0]][self.pos[idx][1]] rev_to, rev_rev, rev_cap = self.graph[to][rev] return rev_to, to, cap + rev_cap, rev_cap def edges(self): m = len(self.pos) for i in range(m): yield self.get_edge(i) def change_edge(self, idx, new_cap, new_flow): to, rev, cap = self.graph[self.pos[idx][0]][self.pos[idx][1]] self.graph[self.pos[idx][0]][self.pos[idx][1]][2] = new_cap - new_flow self.graph[to][rev][2] = new_flow def dfs(self, s, v, up): if v == s: return up res = 0 lv = self.level[v] for i in range(self.iter[v], len(self.graph[v])): to, rev, cap = self.graph[v][i] if lv <= self.level[to] or self.graph[to][rev][2] == 0: continue d = self.dfs(s, to, min(up - res, self.graph[to][rev][2])) if d <= 0: continue self.graph[v][i][2] += d self.graph[to][rev][2] -= d res += d if res == up: break self.iter[v] += 1 return res def max_flow(self, s, t): return self.max_flow_with_limit(s, t, 2 ** 63 - 1) def max_flow_with_limit(self, s, t, limit): flow = 0 while flow < limit: self.level = [-1] * self.n self.level[s] = 0 queue = deque() queue.append(s) while queue: v = queue.popleft() for to, rev, cap in self.graph[v]: if cap == 0 or self.level[to] >= 0: continue self.level[to] = self.level[v] + 1 if to == t: break queue.append(to) if self.level[t] == -1: break self.iter = [0] * self.n while flow < limit: f = self.dfs(s, t, limit - flow) if not f: break flow += f return flow def min_cut(self, s): visited = [0] * self.n queue = deque() queue.append(s) while queue: p = queue.popleft() visited[p] = True for to, rev, cap in self.graph[p]: if cap and not visited[to]: visited[to] = True queue.append(to) return visited H, W = map(int, input().split()) a = [list(input().rstrip()) for _ in range(H)] mf = MaxFlow(H + W + 2) start = H + W terminal = H + W + 1 INF = 10**6 for i in range(H): for j in range(W): if a[i][j] == 'S': mf.add_edge(start, i, INF) mf.add_edge(start, H + j, INF) elif a[i][j] == 'T': mf.add_edge(i, terminal, INF) mf.add_edge(H + j, terminal, INF) elif a[i][j] == 'o': mf.add_edge(i, H + j, 1) mf.add_edge(H + j, i, 1) ans = mf.max_flow(start, terminal) if ans >= INF: print(-1) else: print(ans) ``` Yes
9,745
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 Submitted Solution: ``` from collections import deque INF = 10**9 class Dinic: def __init__(self, n): self.n = n self.edge = [[] for _ in range(n)] self.level = [None] * self.n self.it = [None] * self.n def add_edge(self, fr, to, cap): # edge consists of [dest, cap, id of reverse edge] forward = [to, cap, None] backward = [fr, 0, forward] forward[2] = backward self.edge[fr].append(forward) self.edge[to].append(backward) def add_bidirect_edge(self, v1, v2, cap1, cap2): edge1 = [v2, cap1, None] edge2 = [v1, cap2, edge1] edge1[2] = edge2 self.edge[v1].append(edge1) self.edge[v2].append(edge2) # takes start node and terminal node # create new self.level, return you can flow more or not def bfs(self, s, t): self.level = [None] * self.n dq = deque([s]) self.level[s] = 0 while dq: v = dq.popleft() lv = self.level[v] + 1 for dest, cap, _ in self.edge[v]: if cap > 0 and self.level[dest] is None: self.level[dest] = lv dq.append(dest) return self.level[t] is not None # takes vertex, terminal, flow in vertex def dfs(self, v, t, f): if v == t: return f for e in self.it[v]: to, cap, rev = e if cap and self.level[v] < self.level[to]: ret = self.dfs(to, t, min(f, cap)) # find flow if ret: e[1] -= ret rev[1] += ret return ret # no more flow return 0 def flow(self, s, t): flow = 0 while self.bfs(s, t): for i in range(self.n): self.it[i] = iter(self.edge[i]) # *self.it, = map(iter, self.edge) f = INF while f > 0: f = self.dfs(s, t, INF) flow += f return flow N, M = [int(item) for item in input().split()] n = N + M + 2 dinic = Dinic(n) for i in range(N): line = input().rstrip() for j, ch in enumerate(line): if ch == ".": pass elif ch == "o": v1 = i + 1 v2 = N + j + 1 dinic.add_bidirect_edge(v1, v2, 1, 1) elif ch == "S": v1 = i + 1 v2 = N + j + 1 dinic.add_edge(0, v1, INF) dinic.add_edge(0, v2, INF) elif ch == "T": v1 = i + 1 v2 = N + j + 1 dinic.add_edge(v1, n-1, INF) dinic.add_edge(v2, n-1, INF) ans = dinic.flow(0, n-1) if ans >= INF: print(-1) else: print(ans) ``` Yes
9,746
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 Submitted Solution: ``` from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys from pprint import pprint from copy import deepcopy import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor from operator import mul from functools import reduce from pprint import pprint sys.setrecursionlimit(2147483647) INF = 10 ** 15 def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def I(): return int(sys.stdin.buffer.readline()) def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split() def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8') def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 1000000007 class Dinic: def __init__(self, n): self.n = n self.G = [[] for _ in range(n)] self.level = None self.it = None def add_edge(self, fr, to, cap): forward = [to, cap, None] forward[2] = backward = [fr, 0, forward] self.G[fr].append(forward) self.G[to].append(backward) def add_multi_edge(self, v1, v2, cap1, cap2): edge1 = [v2, cap1, None] edge1[2] = edge2 = [v1, cap2, edge1] self.G[v1].append(edge1) self.G[v2].append(edge2) def bfs(self, s, t): self.level = level = [-1] * self.n deq = deque([s]) level[s] = 0 G = self.G while deq: v = deq.popleft() lv = level[v] + 1 for w, cap, _ in G[v]: if cap and level[w] == -1: level[w] = lv deq.append(w) return level[t] != -1 def dfs(self, v, t, f): if v == t: return f for e in self.it[v]: w, cap, rev = e if cap and self.level[v] < self.level[w]: d = self.dfs(w, t, min(f, cap)) if d: e[1] -= d rev[1] += d return d return 0 def flow(self, s, t): flow = 0 INF = 10 ** 18 while self.bfs(s, t): *self.it, = map(iter, self.G) f = INF while f: f = self.dfs(s, t, INF) flow += f return flow h, w = LI() dinic = Dinic(h + w + 2) s = SR(h) for i in range(h): for j in range(w): if s[i][j] == 'o': dinic.add_multi_edge(i, h + j, 1, 1) elif s[i][j] == 'S': dinic.add_edge(h + w, i, INF) dinic.add_edge(h + w, h + j, INF) elif s[i][j] == 'T': dinic.add_edge(i, h + w + 1, INF) dinic.add_edge(h + j, h + w + 1, INF) ans = dinic.flow(h + w, h + w + 1) print(ans if ans < INF else -1) ``` Yes
9,747
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 Submitted Solution: ``` from collections import deque class Dinic: def __init__(self, n: int): self.INF = 10**9 + 7 self.n = n self.graph = [[] for _ in range(n)] def add_edge(self, _from: int, to: int, capacity: int): """残余グラフを構築 1. _fromからtoへ向かう容量capacityの辺をグラフに追加する 2. toから_fromへ向かう容量0の辺をグラフに追加する """ forward = [to, capacity, None] forward[2] = backward = [_from, 0, forward] self.graph[_from].append(forward) self.graph[to].append(backward) def bfs(self, s: int, t: int): """capacityが正の辺のみを通ってsからtに移動可能かどうかBFSで探索 level: sからの最短路の長さ """ self.level = [-1] * self.n q = deque([s]) self.level[s] = 0 while q: _from = q.popleft() for to, capacity, _ in self.graph[_from]: if capacity > 0 and self.level[to] < 0: self.level[to] = self.level[_from] + 1 q.append(to) def dfs(self, _from: int, t: int, f: int) -> int: """流量が増加するパスをDFSで探索 BFSによって作られた最短路に従ってfを更新する """ if _from == t: return f for edge in self.itr[_from]: to, capacity, reverse_edge = edge if capacity > 0 and self.level[_from] < self.level[to]: d = self.dfs(to, t, min(f, capacity)) if d > 0: edge[1] -= d reverse_edge[1] += d return d return 0 def max_flow(self, s: int, t: int): """s-tパス上の最大流を求める 計算量: O(|E||V|^2) """ flow = 0 while True: self.bfs(s, t) if self.level[t] < 0: break self.itr = list(map(iter, self.graph)) f = self.dfs(s, t, self.INF) while f > 0: flow += f f = self.dfs(s, t, self.INF) return flow h, w = map(int, input().split()) a = [list(input()) for i in range(h)] di = Dinic(h + w + 2) for i in range(h): for j in range(w): if a[i][j] == "o": di.add_edge(i, h + j, 1) di.add_edge(h + j, i, 1) if a[i][j] == "S": di.add_edge(h + w, i, 10 ** 5) di.add_edge(h + w, h + j, 10 ** 5) if a[i][j] == "T": di.add_edge(i, h + w + 1, 10 ** 5) di.add_edge(h + j, h + w + 1, 10 ** 5) ans = di.max_flow(h + w, h + w + 1) if ans >= 10 ** 5: print(-1) else: print(ans) ``` Yes
9,748
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 Submitted Solution: ``` from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys from pprint import pprint from copy import deepcopy import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor from operator import mul from functools import reduce from pprint import pprint sys.setrecursionlimit(2147483647) INF = 10 ** 15 def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def I(): return int(sys.stdin.buffer.readline()) def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split() def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8') def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 1000000007 class Dinic(): def __init__(self, G, source, sink): self.G = G self.sink = sink self.source = source def add_edge(self, u, v, cap): self.G[u][v] = cap self.G[v][u] = 0 def bfs(self): level = defaultdict(int) q = [self.source] level[self.source] = 1 d = 1 while q: if level[self.sink]: break qq = [] d += 1 for u in q: for v, cap in self.G[u].items(): if cap == 0: continue if level[v]: continue level[v] = d qq += [v] q = qq self.level = level def dfs(self, u, f): if u == self.sink: return f for v, cap in self.iter[u]: if cap == 0 or self.level[v] != self.level[u] + 1: continue d = self.dfs(v, min(f, cap)) if d: self.G[u][v] -= d self.G[v][u] += d return d return 0 def max_flow(self): flow = 0 while True: self.bfs() if self.level[self.sink] == 0: break self.iter = {u: iter(self.G[u].items()) for u in self.G} while True: f = self.dfs(self.source, INF) if f == 0: break flow += f return flow h, w = LI() s = SR(h) G = defaultdict(lambda:defaultdict(int)) for i in range(h): for j in range(w): if s[i][j] == 'o': G[i][h + j] = 1 G[h + j][i] = 1 elif s[i][j] == 'S': G[h + w][i] = INF G[h + w][h + j] = INF elif s[i][j] == 'T': G[i][h + w + 1] = INF G[h + j][h + w + 1] = INF ans = Dinic(G, h + w, h + w + 1).max_flow() if ans == INF: print(-1) else: print(ans) ``` No
9,749
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 Submitted Solution: ``` class FordFulkerson: """max-flow-min-cut O(F|E|) """ def __init__(self,V:int): """ Arguments: V:num of vertex adj:adjedscent list(adj[from]=(to,capacity,id)) """ self.V = V self.adj=[[] for _ in range(V)] self.used=[False]*V def add_edge(self,fro:int,to:int,cap:int): """ Arguments: fro:from to: to cap: capacity of the edge f: max flow value """ #edge self.adj[fro].append([to,cap,len(self.adj[to])]) #rev edge self.adj[to].append([fro,0,len(self.adj[fro])-1]) def dfs(self,v,t,f): """ search increasing path """ if v==t: return f self.used[v]=True for i in range(len(self.adj[v])): (nex_id,nex_cap,nex_rev) = self.adj[v][i] if not self.used[nex_id] and nex_cap>0: d = self.dfs(nex_id,t,min(f,nex_cap)) if d>0: #decrease capacity to denote use it with d flow self.adj[v][i][1]-=d self.adj[nex_id][nex_rev][1]+=d return d return 0 def max_flow(self,s:int,t:int): """calculate maxflow from s to t """ flow=0 self.used = [False]*self.V #while no increasing path is found while True: self.used = [False]*self.V f = self.dfs(s,t,float("inf")) if f==0: return flow else: flow+=f H,W = map(int,input().split()) grid=[[v for v in input()] for _ in range(H)] F = FordFulkerson(H*W*2) for i in range(H): for j in range(W): if grid[i][j]=="S": sy,sx = i,j grid[i][j]="o" if grid[i][j]=="T": gy,gx=i,j grid[i][j]="o" if grid[i][j]=="o": #in node and out node F.add_edge(i*W+j+H*W,i*W+j,1) for i in range(H): for j in range(W): for k in range(j+1,W): if grid[i][j]=="o" and grid[i][k]=="o": #out->in F.add_edge(i*W+j,i*W+k+H*W,float("inf")) F.add_edge(i*W+k,i*W+j+H*W,float("inf")) for i in range(W): for j in range(H): for k in range(j+1,H): if grid[j][i]=="o" and grid[k][i]=="o": F.add_edge(j*W+i,k*W+i+H*W,float("inf")) F.add_edge(k*W+i,j*W+i+H*W,float("inf")) if sy==gy or sx==gx: print(-1) exit() print(F.max_flow(sy*W+sx,gy*W+gx+H*W)) ``` No
9,750
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 Submitted Solution: ``` def examC(): ans = 0 print(ans) return def examD(): ans = 0 print(ans) return def examE(): ans = 0 print(ans) return def examF(): # 引用 # https://ikatakos.com/pot/programming_algorithm/graph_theory/maximum_flow class Dinic: def __init__(self, n): self.n = n self.links = [[] for _ in range(n)] self.depth = None self.progress = None def add_link(self, _from, to, cap): self.links[_from].append([cap, to, len(self.links[to])]) self.links[to].append([0, _from, len(self.links[_from]) - 1]) def bfs(self, s): depth = [-1] * self.n depth[s] = 0 q = deque([s]) while q: v = q.popleft() for cap, to, rev in self.links[v]: if cap > 0 and depth[to] < 0: depth[to] = depth[v] + 1 q.append(to) self.depth = depth def dfs(self, v, t, flow): if v == t: return flow links_v = self.links[v] for i in range(self.progress[v], len(links_v)): self.progress[v] = i cap, to, rev = link = links_v[i] if cap == 0 or self.depth[v] >= self.depth[to]: continue d = self.dfs(to, t, min(flow, cap)) if d == 0: continue link[0] -= d self.links[to][rev][0] += d return d return 0 def max_flow(self, s, t): flow = 0 while True: self.bfs(s) if self.depth[t] < 0: return flow self.progress = [0] * self.n current_flow = self.dfs(s, t, inf) while current_flow > 0: flow += current_flow current_flow = self.dfs(s, t, inf) H, W = LI() A = [SI()for _ in range(H)] din = Dinic(H+W+2) for h in range(H): for w in range(W): if A[h][w]==".": continue if A[h][w]=="S": din.add_link(0, h + W + 1, H * W) din.add_link(h + W + 1, 0, H * W) din.add_link(0, w + 1, H * W) din.add_link(w + 1, 0, H * W) continue if A[h][w]=="T": din.add_link(H + W + 1, h + W + 1, H * W) din.add_link(h + W + 1, H + W + 1, H * W) din.add_link(H + W + 1, w + 1, H * W) din.add_link(w + 1, H + W + 1, H * W) continue din.add_link(h+W+1,w+1,1) din.add_link(w+1,h+W+1,1) ans = din.max_flow(0,H+W+1) if ans==H*W: ans = -1 print(ans) return from decimal import getcontext,Decimal as dec import sys,bisect,itertools,heapq,math,random from copy import deepcopy from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines def I(): return int(input()) def LI(): return list(map(int,sys.stdin.readline().split())) def DI(): return dec(input()) def LDI(): return list(map(dec,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,mod2,inf,alphabet,_ep mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 _ep = dec("0.000000000001") alphabet = [chr(ord('a') + i) for i in range(26)] alphabet_convert = {chr(ord('a') + i): i for i in range(26)} getcontext().prec = 28 sys.setrecursionlimit(10**7) if __name__ == '__main__': examF() """ 142 12 9 1445 0 1 asd dfg hj o o aidn """ ``` No
9,751
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows: * `.` : A square without a leaf. * `o` : A square with a leaf floating on the water. * `S` : A square with the leaf S. * `T` : A square with the leaf T. The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located." Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove. Constraints * 2 ≤ H, W ≤ 100 * a_{ij} is `.`, `o`, `S` or `T`. * There is exactly one `S` among a_{ij}. * There is exactly one `T` among a_{ij}. Input Input is given from Standard Input in the following format: H W a_{11} ... a_{1W} : a_{H1} ... a_{HW} Output If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead. Examples Input 3 3 S.o .o. o.T Output 2 Input 3 4 S... .oo. ...T Output 0 Input 4 3 .S. .o. .o. .T. Output -1 Input 10 10 .o...o..o. ....o..... ....oo.oo. ..oooo..o. ....oo.... ..o..o.... o..o....So o....T.... ....o..... ........oo Output 5 Submitted Solution: ``` import sys sys.setrecursionlimit(10**9) def dfs(v,t,f,used,graph): if v==t: return f used[v] = True for to in graph[v]: c = graph[v][to] if used[to] or c==0: continue d = dfs(to,t,min(f,c),used,graph) if d>0: graph[v][to] -= d graph[to][v] += d return d return 0 def max_flow(s,t,graph): flow = 0 while True: used = [False]*len(graph) f = dfs(s,t,float('inf'),used,graph) flow += f if f==0 or f==float('inf'): return flow H,W = map(int,input().split()) a = [input() for _ in range(H)] a = [[s for s in a[i]] for i in range(H)] def encode(h,w): return h*W+w def decode(d): return (d//W,d%W) for h in range(H): for w in range(W): if a[h][w]=='S': s = encode(h,w) a[h][w]='o' if a[h][w]=='T': t = encode(h,w) a[h][w]='o' ans = 0 for h in range(H): for w in range(W): if a[h][w]=='o': if (h==decode(s)[0] or w==decode(s)[1]) and (h==decode(t)[0] or w==decode(t)[1]): ans += 1 a[h][w] = '.' graph = [{} for _ in range(H*W)] for h in range(H): for w in range(W): if a[h][w]=='.': continue for i in range(H): if i==h: continue if a[i][w]=='.': continue graph[encode(h,w)][encode(i,w)] = 1 graph[encode(i,w)][encode(h,w)] = 1 for j in range(W): if j==w: continue if a[h][j]=='.': continue graph[encode(h,w)][encode(h,j)] = 1 graph[encode(h,j)][encode(h,w)] = 1 for d in graph[s]: graph[s][d] = float('inf') graph[d][s] = 0 for d in graph[t]: graph[t][d] = 0 graph[d][t] = float('inf') ans += max_flow(s,t,graph) if ans == float('inf'): ans = -1 print(ans) ``` No
9,752
Provide a correct Python 3 solution for this coding contest problem. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 "Correct Solution: ``` def main(): from bisect import bisect_left as bl n = int(input()) a = [int(input()) for _ in [0]*n] b = [int(input()) for _ in [0]*n] a.sort() b.sort() for i in range(n): if a[i] > b[i]: a[i], b[i] = b[i], a[i] # print(a) # print(b) mod = 10**9+7 ans = 1 for i in range(n): ans = ans*(i+1-bl(b, a[i])) % mod print(ans) main() ```
9,753
Provide a correct Python 3 solution for this coding contest problem. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 "Correct Solution: ``` N=int(input()) A=[] mod=10**9+7 for i in range(N): a=int(input()) A.append((a,-1)) for i in range(N): a=int(input()) A.append((a,1)) A.sort() a=0 s=A[0][1] ans=1 for i in range(2*N): if A[i][1]==s: a+=1 else: ans*=a ans%=mod a-=1 if a==0 and i<2*N-1: s=A[i+1][1] #print(a,s,ans) print(ans) ```
9,754
Provide a correct Python 3 solution for this coding contest problem. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 "Correct Solution: ``` N = int(input()) src = [] for i in range(2*N): src.append((int(input()), i//N)) ans = 1 MOD = 10**9+7 mem = [0, 0] for a,t in sorted(src): if mem[1-t] > 0: ans = (ans * mem[1-t]) % MOD mem[1-t] -= 1 else: mem[t] += 1 print(ans) ```
9,755
Provide a correct Python 3 solution for this coding contest problem. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 "Correct Solution: ``` import sys n = int(input()) lines = sys.stdin.readlines() aaa = list(map(int, lines[:n])) bbb = list(map(int, lines[n:])) coords = [(a, 0) for a in aaa] + [(b, 1) for b in bbb] coords.sort() MOD = 10 ** 9 + 7 remain_type = 0 remain_count = 0 ans = 1 for x, t in coords: if remain_type == t: remain_count += 1 continue if remain_count == 0: remain_type = t remain_count = 1 continue ans = ans * remain_count % MOD remain_count -= 1 print(ans) ```
9,756
Provide a correct Python 3 solution for this coding contest problem. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 "Correct Solution: ``` N = int(input()) A = [(int(input()), 0) for i in range(N)] B = [(int(input()), 1) for i in range(N)] mod = 10 ** 9 + 7 X = A + B X.sort() ans = 1 Ar, Br = 0, 0 for x, i in X: if i == 0: if Br > 0: ans *= Br ans %= mod Br -= 1 else: Ar += 1 else: if Ar > 0: ans *= Ar ans %= mod Ar -= 1 else: Br += 1 print(ans) ```
9,757
Provide a correct Python 3 solution for this coding contest problem. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 "Correct Solution: ``` N = int(input()) Q = sorted([[int(input()), i//N] for i in range(2*N)]) mod = 10**9 + 7 ans = 1 S = [0, 0] for i in Q: if S[1-i[1]] == 0: S[i[1]] += 1 else: ans = (ans*S[1-i[1]]) % mod S[1-i[1]] -= 1 print(ans) ```
9,758
Provide a correct Python 3 solution for this coding contest problem. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 "Correct Solution: ``` mod = 10 ** 9 + 7 N = int(input()) A = [(int(input()), -1) for _ in range(N)] B = [(int(input()), 1) for _ in range(N)] C = sorted(A + B) res = 1 cnt = 0 for _, delta in C: if cnt != 0 and cnt * delta < 0: res *= abs(cnt) res %= mod cnt += delta print(res) ```
9,759
Provide a correct Python 3 solution for this coding contest problem. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 "Correct Solution: ``` N = int(input()) E = [] for _ in range(N): E += [(int(input()), 1)] for _ in range(N): E += [(int(input()), -1)] E.sort() mod = 10**9 + 7 ans = 1 ab = 0 for e in E: if e[1] * ab < 0: ans *= abs(ab) ans %= mod ab += e[1] print(ans) ```
9,760
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 Submitted Solution: ``` N = int(input()) mod = int(1e9+7) A = [] for _ in range(N): A.append([int(input()),1]) for _ in range(N): A.append([int(input()),2]) A.sort() ans = 1 ca,cb = 0,0 for a in A: if a[1] == 1: if cb == 0: ca += 1 else: ans = ans * cb % mod cb -= 1 else: if ca == 0: cb += 1 else: ans = ans * ca % mod ca -= 1 print(ans) ``` Yes
9,761
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 Submitted Solution: ``` n=int(input()) ans=1 mod=10**9+7 A=[0,0] AB=[] for i in range(n): a=int(input()) AB.append((a,0)) for i in range(n): b=int(input()) AB.append((b,1)) AB.sort(key=lambda x:x[0]) for i in range(2*n): a,b=AB[i] if b==0: if A[1]>0: ans=(ans*A[1])%mod A[1]-=1 else: A[0]+=1 else: if A[0]>0: ans=(ans*A[0])%mod A[0]-=1 else: A[1]+=1 print(ans) ``` Yes
9,762
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 Submitted Solution: ``` from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,datetime sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inpl(): return list(map(int, input().split())) def inpls(): return list(input().split()) N = int(input()) points = [] for i in range(N): a = int(input()) points.append([a,True]) for i in range(N): b = int(input()) points.append([b,False]) points.sort() ans = 1 an = bn = 0 for x,c in points: if c: if bn > 0: ans = (ans*bn)%mod bn -= 1 else: an += 1 else: if an > 0: ans = (ans*an)%mod an -= 1 else: bn += 1 print(ans%mod) ``` Yes
9,763
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 Submitted Solution: ``` n = int(input()) M = 10**9+7 L = [] for _ in range(n): a = int(input()) L.append((a, 1)) for _ in range(n): b = int(input()) L.append((b, 0)) L.sort() C = [0, 0] ans = 1 for d, f in L: if C[f^1]: ans *= C[f^1] ans %= M C[f^1] -= 1 else: C[f] += 1 print(ans) ``` Yes
9,764
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 Submitted Solution: ``` N = int(input()) mod = 10**9 + 7 fac = [1 for _ in range(N+1)] for i in range(N): fac[i+1] = (i+1)*fac[i]%mod a = sorted([int(input()) for _ in range(N)]) b = sorted([int(input()) for _ in range(N)]) ab = list(zip(a,b)) X = [-2, -1] ctr = 1 H = [] for i, j in ab: if i < X[1]: X = [i,X[1]] ctr += 1 else: H.append(ctr) ctr = 1 X = i, j ans = fac[ctr] for i in H: ans = ans*fac[i]%mod print(ans%mod) ``` No
9,765
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 Submitted Solution: ``` N = int(input()) mod = 10**9 + 7 fac = [1 for _ in range(N+1)] for i in range(N): fac[i+1] = (i+1)*fac[i]%mod a = sorted([int(input()) for _ in range(N)]) b = sorted([int(input()) for _ in range(N)]) ab = list(zip(a,b)) X = [-2, -1] ctr = 1 H = [] for i, j in ab: if i > j: i, j = j, i if i < X[1]: X = [i,X[1]] ctr += 1 else: H.append(ctr) ctr = 1 X = i, j ans = fac[ctr] for i in H: ans = ans*fac[i]%mod print(ans%mod) ``` No
9,766
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 Submitted Solution: ``` import sys input = sys.stdin.readline n = int(input()) a = [(int(input()),1) for i in range(n)] a += [(int(input()),2) for i in range(n)] a.sort() b = list(zip(*a))[1] mod = 10**9+7 cnt = 0 ans = 1 prv = -1 for i in range(2*n): if b[i] == 1: cnt += 1 else: cnt -= 1 if cnt == 0: ans *= ((i-prv)//2)**2 ans %= mod prv = i print(ans) ``` No
9,767
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1 Submitted Solution: ``` # -*- coding: utf-8 -*- import sys from math import factorial def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(): return list(map(int, input().split())) def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10 ** 9) INF = float('inf') MOD = 10 ** 9 + 7 N=INT() A=sorted([INT() for i in range(N)]) B=sorted([INT() for i in range(N)]) i=j=cur=cnt=0 L=[] if A[0]>B[0]: cur=1 while i<N and j<N: if cur==0 and A[i]<B[j]: i+=1 cnt+=1 elif cur==1 and A[i]<B[j]: i=j if cnt: L.append(cnt) cnt=0 cur=0 elif cur==1 and A[i]>B[j]: j+=1 cnt+=1 elif cur==0 and A[i]>B[j]: j=i if cnt: L.append(cnt) cnt=0 cur=1 if cnt!=0: L.append(cnt) ans=1 for a in L: ans=(ans*factorial(a))%MOD print(ans) ``` No
9,768
Provide a correct Python 3 solution for this coding contest problem. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 "Correct Solution: ``` n,m = input().split() k=int(n) l = list(input().split()) for i in range(k,100000): for e in l: if e in str(i): break else: print(i) break ```
9,769
Provide a correct Python 3 solution for this coding contest problem. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 "Correct Solution: ``` def ri(): return int(input()) def rli(): return list(map(int, input().split())) def rls(): return list(input()) def pli(a): return "".join(list(map(str, a))) N, K = rli() D = set(map(int, input().split())) All = {1,2,3,4,5,6,7,8,9,0} All.difference_update(D) ans = N for i in range(N*10): ls = set(map(int, str(ans))) ls.difference_update(All) if(ls == set()): print(ans) break ans += 1 ```
9,770
Provide a correct Python 3 solution for this coding contest problem. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 "Correct Solution: ``` n,k=map(int,input().split()) d=sorted(list(map(int,input().split()))) ans=n while True: flag=0 for i in d: if str(i) in str(ans): ans+=1 flag+=1 if flag==0: break print(ans) ```
9,771
Provide a correct Python 3 solution for this coding contest problem. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 "Correct Solution: ``` def slove(): import sys input = sys.stdin.readline n, k = list(map(int, input().rstrip('\n').split())) d = list(map(int, input().rstrip('\n').split())) for i in range(n, 10 ** 10): t = list(str(i)) b = True for j in range(len(t)): if int(t[j]) in d: b = False break if b: print(i) exit() if __name__ == '__main__': slove() ```
9,772
Provide a correct Python 3 solution for this coding contest problem. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 "Correct Solution: ``` N, K = map(int, input().split()) *D, = map(int, input().split()) D = set(D) L = {1,2,3,4,5,6,7,8,9,0} - D for i in range(N, N*10): tmp = i num = set() while i > 0: num.add(i%10) i = i // 10 if num.isdisjoint(D): print(tmp) exit() ```
9,773
Provide a correct Python 3 solution for this coding contest problem. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 "Correct Solution: ``` # coding: utf-8 n,k=map(int,input().split()) d=input().split() while True: for c in d: if c in str(n): break else: print(n) break n+=1 ```
9,774
Provide a correct Python 3 solution for this coding contest problem. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 "Correct Solution: ``` import itertools N, K = map(int, input().split()) Ds = list(map(int, input().split())) NDs = list(set([i for i in range(10)]) - set(Ds)) NDs = list(map(str, NDs)) min_price = 100000 for p in itertools.product(NDs, repeat=len(str(N))): if p[0] == '0': continue price = int(''.join(p)) if price < N: continue min_price = min(price, min_price) if min_price == 100000: for p in itertools.product(NDs, repeat=len(str(N))+1): if p[0] == '0': continue price = int(''.join(p)) min_price = min(price, min_price) print(min_price) ```
9,775
Provide a correct Python 3 solution for this coding contest problem. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 "Correct Solution: ``` import itertools n,_=map(int,input().split()) b=map(int,input().split()) l=len(str(n)) c=set(b)^set([0,1,2,3,4,5,6,7,8,9]) for i in range(l,l+2): for x in itertools.product(c,repeat=i): d=''.join(map(str,x)) if int(d)>=n:print(d);exit() ```
9,776
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 Submitted Solution: ``` def dig_check(i,d): for k in [int(j) for j in str(i)]: if k in d: return False return True N,K = input().split() N = int(N) d = [int(i) for i in input().split()] for i in range(100001): if i >= N : if dig_check(i,d): print(i) break ``` Yes
9,777
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 Submitted Solution: ``` input_1st=input() input_2nd=input() N, K = input_1st.split(" ") D = input_2nd.split(" ") for ans in range(int(N), 100000): flg = True for i in range(len(str(ans))): if str(ans)[i] in D: flg = False break if flg: print(ans) break ``` Yes
9,778
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 Submitted Solution: ``` N, K=map(int,input().split()) D=list(map(int,input().split())) for i in range (N,100000): a=str(i) b=list(map(int,a)) l=len(b) c=0 for j in range(l): if(b[j] in D): c=1 if(c==0): ans=i break print(ans) ``` Yes
9,779
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 Submitted Solution: ``` N, K = map(int, input().split()) D = set(input().split()) while any(s in D for s in str(N)): N += 1 print(N) ``` Yes
9,780
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) n,k = list(map(int, input().split())) d = list(map(int, input().split())) d.sort() e = 0 for i in range(10): if i not in d: e = i break a = list(map(int, str(n))) s = a[:] l = len(s) for i in range(l+1): if i == l: break if s[i] in d: break if i == l: print(n) else: while i >= 0: while s[i] in d: s[i] += 1 for j in range(i+1,l): s[j] = e if s[i] > 9: if i != 0: s[i-1] += 1 s[i] = e i -= 1 if s[0] == 10: for i in range(1,10): if i not in d: s[0] = i*10+e if 0 not in d and i == e: s[0] -+ e print("".join(list(map(str, s)))) ``` No
9,781
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 Submitted Solution: ``` #!usr/bin/env python3 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def LIR(n): return [LI() for i in range(n)] #A """ s = S() if s[0] != "A": print("WA") else: count = [] for i in range(2,len(s)-1): if s[i] == "C": count.append(i) if len(count) != 1: print("WA") else: for i in range(1,len(s)): if i not in count: if s[i] == s[i].upper(): print("WA") quit() print("AC") """ #B """ n,m,k = LI() for i in range((n+1)//2): if (k - m*i) % (n - 2*i) == 0 and (k-m*i)//(n-2*i) >= 0 and (k-m*i)//(n-2*i) <= m: print("Yes") quit() print("No") """ #C """ from collections import defaultdict n,k = LI() d = defaultdict(int) for i in range(n): a,b = LI() d[a] += b s = list(d.items()) s.sort(key = lambda x:x[0]) su = 0 for i in range(len(s)): su += s[i][1] if su >= k: print(s[i][0]) break """ #D n,k = LI() d = LI() lis = [0,1,2,3,4,5,6,7,8,9] for i in d: if i in lis: lis.remove(i) n = list(str(n)) i = 0 while i < len(n): while int(n[i]) not in lis and n[i] != "10": n[i] = str(int(n[i])+1) if n[i] == "10": if i == 0: n[i] = "0" n.insert(i,"1") else: n[i-1] = str(int(n[i-1])+1) n[i] = "0" i -= 1 i -= 1 i += 1 for i in n: print(i,end = "") print() #E #F #G #H #I #J #K #L #M #N #O #P #Q #R #S #T ``` No
9,782
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 Submitted Solution: ``` N, K = (int(i) for i in input().split()) D = [int(i) for i in input().split()] for i in range(N, 100000): for d in D: if d not in str(i): break print(i) ``` No
9,783
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money. Find the amount of money that she will hand to the cashier. Constraints * 1 ≦ N < 10000 * 1 ≦ K < 10 * 0 ≦ D_1 < D_2 < … < D_K≦9 * \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\} Input The input is given from Standard Input in the following format: N K D_1 D_2 … D_K Output Print the amount of money that Iroha will hand to the cashier. Examples Input 1000 8 1 3 4 5 6 7 8 9 Output 2000 Input 9999 1 0 Output 9999 Submitted Solution: ``` import bisect n, k = list(map(int, input().split())) d = list(map(int, input().split())) can_use = list(set([i for i in range(10)]) - set(d)) can_use.sort() s = str(n) ans = "" up = 0 for ind, i in enumerate(s[::-1]): num = int(i) + up if num in can_use: ans += str(num) up = 0 else: if can_use[-1] > num: ans += str(can_use[bisect.bisect_left(can_use, num)]) up = 0 else: ans += str(can_use[0]) up = 1 if up: ans += str(max(1, int(can_use[0]))) print(int(ans[::-1])) ``` No
9,784
Provide a correct Python 3 solution for this coding contest problem. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA "Correct Solution: ``` # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0120 """ import sys from sys import stdin input = stdin.readline def calc_width(cakes): # ??±????????????????????????(?????????)????????????????????????????????????????¨?????????? if len(cakes) == 1: return cakes[0]*2 prev_r = cakes[0] width = prev_r for r in cakes[1:]: h_diff = abs(prev_r - r) w = ((prev_r + r)**2 - h_diff**2)**0.5 width += w prev_r = r width += cakes[-1] return width def main(args): for line in sys.stdin: data = [int(x) for x in line.strip().split()] box_size = data[0] temp = data[1:] temp.sort() # ??±?????????????????????????????????????????????????????????????????????????????? min_width = float('inf') cakes = [temp[0]] temp = temp[1:] pick_large = True while temp: if pick_large: pick = temp[-1] temp = temp[:-1] pick_large = False diff_front = abs(pick - cakes[0]) diff_rear = abs(pick - cakes[-1]) if diff_front > diff_rear: cakes.insert(0, pick) else: cakes.append(pick) else: pick = temp[0] temp = temp[1:] pick_large = True diff_front = abs(pick - cakes[0]) diff_rear = abs(pick - cakes[-1]) if diff_front > diff_rear: cakes.insert(0, pick) else: cakes.append(pick) result = calc_width(cakes) min_width = min(result, min_width) if min_width <= box_size: print('OK') else: print('NA') if __name__ == '__main__': main(sys.argv[1:]) ```
9,785
Provide a correct Python 3 solution for this coding contest problem. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA "Correct Solution: ``` # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0120 """ import sys from sys import stdin input = stdin.readline def calc_width(cakes): # ??±????????????????????????(?????????)????????????????????????????????????????¨?????????? if len(cakes) == 1: return cakes[0]*2 prev_r = cakes[0] width = prev_r for r in cakes[1:]: h_diff = abs(prev_r - r) if h_diff == 0: width += prev_r width += r else: w = ((prev_r + r)**2 - h_diff**2)**0.5 width += w prev_r = r width += cakes[-1] return width def main(args): for line in sys.stdin: data = [int(x) for x in line.strip().split()] box_size = data[0] temp = data[1:] temp.sort() min_width = float('inf') cake = [] if len(temp) < 3: cakes = temp[:] elif len(temp) == 3: cakes = [temp[1], temp[2], temp[0]] else: cakes = [temp[1] ,temp[-1], temp[0]] temp = temp[2:-1] tail = True small = False while temp: if tail: if small: cakes.append(temp[0]) temp = temp[1:] tail = False else: cakes.append(temp[-1]) temp = temp[:-1] tail = False else: if small: cakes.insert(0, temp[0]) temp = temp[1:] small = False tail = True else: cakes.insert(0, temp[-1]) temp = temp[:-1] small = True tail = True result = calc_width(cakes) min_width = min(result, min_width) temp = data[1:] temp.sort() cake = [] if len(temp) < 3: cakes = temp[:] elif len(temp) == 3: cakes = [temp[1], temp[0], temp[2]] else: cakes = [temp[-2] ,temp[0], temp[-1]] temp = temp[1:-2] tail = True small = True while temp: if tail: if small: cakes.append(temp[0]) temp = temp[1:] tail = False else: cakes.append(temp[-1]) temp = temp[:-1] tail = False else: if small: cakes.insert(0, temp[0]) temp = temp[1:] small = False tail = True else: cakes.insert(0, temp[-1]) temp = temp[:-1] small = True tail = True result = calc_width(cakes) min_width = min(result, min_width) if min_width <= box_size: print('OK') else: print('NA') from itertools import permutations def main2(args): data = [3, 3, 3, 10, 10] p = permutations(data, len(data)) best_fit = float('inf') for cakes in p: result = calc_width(cakes) if result < best_fit: best_fit = result print(cakes) print(result) if __name__ == '__main__': main(sys.argv[1:]) ```
9,786
Provide a correct Python 3 solution for this coding contest problem. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA "Correct Solution: ``` INF = 10 ** 20 def get_dist(r1, r2): return ((r1 + r2) ** 2 - (r1 - r2) ** 2) ** (1 / 2) def minimum_width(rest, r, dic): if (rest, r) in dic: return dic[(rest, r)] if rest == (): return r ret = INF lenr = len(rest) for c in rest: next_rest = list(rest) next_rest.remove(c) ret = min(ret, minimum_width(tuple(next_rest), c, dic) + get_dist(r, c)) dic[(rest, r)] = ret return ret while True: try: lst = list(map(int, input().split())) w = lst[0] cakes = lst[1:] cakes.sort() lenc = len(cakes) dic = {} ans = INF for i in range(lenc): ans = min(ans, minimum_width(tuple(cakes[j] for j in range(lenc) if i != j), cakes[i], dic) + cakes[i]) if w >= ans: print("OK") else: print("NA") except EOFError: break ```
9,787
Provide a correct Python 3 solution for this coding contest problem. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA "Correct Solution: ``` ####################################################################################### import sys from math import sqrt def rec(state, v): if state == (1 << N) - 1: return cakes[v] if dp[state][v] != -1: return dp[state][v] ret = INF for u in range(N): if state == 0: ret = min(ret, rec(1 << u, u) + cakes[u]) elif not (state >> u & 1): ret = min(ret, rec(state | 1 << u, u) + sqrt(pow(cakes[u] + cakes[v], 2) - pow(cakes[u] - cakes[v], 2))) dp[state][v] = ret return ret testcases = [[int(x) for x in line.split()] for line in sys.stdin.readlines()] for testcase in testcases: box, *cakes = testcase N = len(cakes) INF = box + 1 dp = [[-1] * N for _ in range(1 << N)] print('OK' if rec(0, 0) <= box else 'NA') ```
9,788
Provide a correct Python 3 solution for this coding contest problem. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA "Correct Solution: ``` import sys from math import sqrt def rec(state, v): if state == (1 << N) - 1: return cakes[v] if dp[state][v] != -1: return dp[state][v] ret = INF for i in range(N): if state == 0: ret = min(ret, rec(1 << i, i) + cakes[i]) elif not (state >> i & 1): ret = min(ret, rec(state | 1 << i, i) + sqrt(pow(cakes[i] + cakes[v], 2) - pow(cakes[i] - cakes[v], 2))) dp[state][v] = ret return ret testcases = [[int(x) for x in line.split()] for line in sys.stdin.readlines()] for testcase in testcases: box, *cakes = testcase N = len(cakes) INF = box + 1 dp = [[-1] * N for _ in range(1 << N)] print('OK' if rec(0, 0) <= box else 'NA') ```
9,789
Provide a correct Python 3 solution for this coding contest problem. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA "Correct Solution: ``` from collections import deque def calcwidth(cks): if len(cks) == 1: return cks[0]*2 width = cks[0] + cks[-1] for ck1,ck2 in zip(cks[:-1],cks[1:]): width += ((ck1+ck2)**2-(ck1-ck2)**2)**0.5 return width while True: try: W, *rs = list(map(float,input().split())) except: break rs = deque(sorted(rs)) dp = [float('inf')]*len(rs) cs = deque([rs.popleft()]) last_pick_small = -1 # if -1: last pick up is smallest, if 0: last pick up is biggest while rs: if last_pick_small: nxt = rs.pop() else: nxt = rs.popleft() if abs(nxt-cs[0]) > abs(nxt-cs[-1]): cs.appendleft(nxt) else: cs.append(nxt) last_pick_small = -1-last_pick_small ret = calcwidth(list(cs)) if ret <= W: print('OK') else: print('NA') ```
9,790
Provide a correct Python 3 solution for this coding contest problem. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA "Correct Solution: ``` # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0120 """ import sys from sys import stdin input = stdin.readline def calc_width(cakes): # ??±????????????????????????(?????????)????????????????????????????????????????¨?????????? if len(cakes) == 1: return cakes[0]*2 prev_r = cakes[0] width = prev_r # ??±?????????(???????????±???????????????) for r in cakes[1:]: # ???????????±?????????????????????????°´????????¢ h_diff = abs(prev_r - r) w = ((prev_r + r)**2 - h_diff**2)**0.5 width += w prev_r = r width += cakes[-1] # ??±?????????(???????????±???????????????) return width def main(args): for line in sys.stdin: data = [int(x) for x in line.strip().split()] box_size = data[0] temp = data[1:] temp.sort() # ??±?????????????????????????????????????????????????????????????????????????????? # ????°??????±??????????????????????????§????????´??¨?°?????????´??????????????????????????¢??????????????£????????±????????¨???????????§???????????????????????? cakes = [temp[0]] temp = temp[1:] pick_large = True pick = 0 while temp: if pick_large: pick = temp[-1] temp = temp[:-1] pick_large = False else: pick = temp[0] temp = temp[1:] pick_large = True diff_front = abs(pick - cakes[0]) diff_rear = abs(pick - cakes[-1]) if diff_front > diff_rear: cakes.insert(0, pick) else: cakes.append(pick) # ??±????????¨???????¨????????¨????????????±?????\???????¢?????????? result = calc_width(cakes) if result <= box_size: print('OK') else: print('NA') if __name__ == '__main__': main(sys.argv[1:]) ```
9,791
Provide a correct Python 3 solution for this coding contest problem. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA "Correct Solution: ``` import sys from math import sqrt def rec(state, v): if state == (1 << N) - 1: return cakes[v] if dp[state][v] != -1: return dp[state][v] ret = INF for u in range(N): if state == 0: ret = min(ret, rec(1 << u, u) + cakes[u]) elif not (state >> u & 1): ret = min(ret, rec(state | 1 << u, u) + sqrt(pow(cakes[u] + cakes[v], 2) - pow(cakes[u] - cakes[v], 2))) dp[state][v] = ret return ret testcases = [[int(x) for x in line.split()] for line in sys.stdin.readlines()] for testcase in testcases: box, *cakes = testcase N = len(cakes) INF = box + 1 dp = [[-1] * N for _ in range(1 << N)] print('OK' if rec(0, 0) <= box else 'NA') ```
9,792
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA Submitted Solution: ``` INF = 10 ** 20 def get_dist(r1, r2): return ((r1 + r2) ** 2 - (r1 - r2) ** 2) ** (1 / 2) def minimum_width(rest, r, dic): if (rest, r) in dic: return dic[(rest, r)] if rest == (): return r ret = INF lenr = len(rest) for c in rest: next_rest = list(rest) next_rest.remove(c) ret = min(ret, minimum_width(tuple(next_rest), c, dic) + get_dist(r, c)) dic[(rest, r)] = ret return ret while True: try: lst = list(map(int, input().split())) w = lst[0] cakes = lst[1:] cakes.sort() lenc = len(cakes) dic = {} ans = INF for c in cakes: tmp = cakes[:] tmp.remove(c) ans = min(ans, minimum_width(tuple(tmp), c, dic) + c) if w >= ans: print("OK") else: print("NA") except EOFError: break ``` Yes
9,793
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA Submitted Solution: ``` # AOJ 0120 Patisserie # Python3 2018.6.23 bal4u INF = 0x7fffffff R = 100000 d = [[0 for j in range(13)] for i in range(13)] # ロールケーキ円心間の水平距離 for i in range(3, 11): ii = i*i for j in range(i, 11): d[i][j] = d[j][i] = int(2*R * ii**0.5) ii += i while 1: try: r = list(map(int, input().split())) except: break W = r.pop(0) if 2*sum(r) <= W: print("OK") continue n = len(r) W *= R dp = [[INF for j in range(1<<n)] for i in range(n)] for i in range(n): dp[i][1<<i] = r[i]*R lim = 1<<n for k in range(lim): for i in range(n): if k & (1<<i): continue for j in range(n): dp[i][k|(1<<i)] = min(dp[i][k|(1<<i)], dp[j][k] + d[r[i]][r[j]]) w = 240*R for i in range(n): dp[i][lim-1] += r[i]*R if dp[i][lim-1] < w: w = dp[i][lim-1]; print("OK" if w <= W else "NA") ``` Yes
9,794
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA Submitted Solution: ``` INF = 10 ** 20 def get_dist(r1, r2): c = r1 + r2 b = abs(r1 - r2) return (c ** 2 - b ** 2) ** (1 / 2) def minimum_width(rest, r, dic): if (rest, r) in dic: return dic[(rest, r)] if rest == (): return r ret = INF lenr = len(rest) for i, c in enumerate(rest): ret = min(ret, minimum_width(tuple(rest[j] for j in range(lenr) if i != j), rest[i], dic) + get_dist(r, rest[i])) dic[(rest, r)] = ret return ret while True: try: lst = list(map(int, input().split())) w = lst[0] cakes = lst[1:] cakes.sort() lenc = len(cakes) dic = {} ans = INF for i in range(lenc): ans = min(ans, minimum_width(tuple(cakes[j] for j in range(lenc) if i != j), cakes[i], dic) + cakes[i]) if w >= ans: print("OK") else: print("NA") except EOFError: break ``` Yes
9,795
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA Submitted Solution: ``` # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0120 """ import sys from sys import stdin input = stdin.readline def calc_width(cakes): # ??±????????????????????????(?????????????????????????????????????????????????¨??????????) if len(cakes) == 1: return cakes[0]*2 prev_r = cakes[0] width = prev_r for r in cakes[1:]: h_diff = abs(prev_r - r) if h_diff == 0: width += prev_r width += r else: w = ((prev_r + r)**2 - h_diff**2)**0.5 width += w prev_r = r width += cakes[-1] return width def main(args): for line in sys.stdin: data = [int(x) for x in line.split()] box_size = data[0] temp = data[1:] temp.sort() cakes = [] head = True while temp: if head: cakes.append(temp[0]) temp = temp[1:] head = False else: cakes.append(temp[-1]) temp = temp[:-1] head = True result = calc_width(cakes) if result <= box_size: print('OK') else: print('NA') if __name__ == '__main__': main(sys.argv[1:]) ``` No
9,796
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA Submitted Solution: ``` # -*- coding: utf-8 -*- import sys import os import math def pythagoras(a, b): return 2 * math.sqrt(a * b) for s in sys.stdin: lst = list(map(int, s.split())) W = lst[0] R = lst[1:] R.sort() n = len(R) if n == 0: print('OK') exit() if n == 1: if W >= R[0]: print('OK') exit() else: print('NA') exit() left = [] right = [] left.append(R.pop(0)) right.append(R.pop(0)) l = left[0] + right[0] while R: min_R = R[0] max_R = R[-1] left_R = left[-1] right_R = right[-1] if left_R <= right_R: if right_R - min_R >= max_R - left_R: right.append(R.pop(0)) l += pythagoras(right_R, min_R) else: left.append(R.pop(-1)) l += pythagoras(max_R, left_R) else: if left_R - min_R >= max_R - right_R: left.append(R.pop(0)) l += pythagoras(left_R, min_R) else: right.append(R.pop(-1)) l += pythagoras(max_R, right_R) l += pythagoras(left[-1], right[-1]) if l <= W: print('OK') else: print('NA') ``` No
9,797
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA Submitted Solution: ``` import sys from math import sqrt testcases = [[int(x) for x in line.split()] for line in sys.stdin.readlines()] for testcase in testcases: box, *cakes = testcase N = len(cakes) INF = box + 1 dp = [[INF] * N for _ in range(1 << N)] dp[(1 << N) - 1][0] = 0 for state in reversed(range(1 << N)): for v in range(N): for u in range(N): if not (state >> u & 1): dp[state][v] = min(dp[state][v], dp[state | 1 << u][u] + sqrt(pow(cakes[u] + cakes[v], 2) - pow(cakes[u] - cakes[v], 2))) print(*dp[0]) print('OK' if min(dp[0]) <= box else 'NA') ``` No
9,798
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes the required width. <image> --- Figure (a) <image> Figure (b) Read the radii r1, r2, ..., rn of n roll cakes and the length of the box, judge whether they fit well in the box, and devise the order of arrangement. ", Create a program that outputs" NA "if it does not fit in any order. It is assumed that the cross section of the roll cake is a circle and the height of the wall of the box is high enough. However, the radius of the roll cake should be an integer between 3 and 10. In other words, there is no extreme difference in cake radii, and small cakes do not get stuck between large cakes as shown in Figure (b). Input The input consists of multiple datasets. Each dataset is given in the following format: W r1 r2 ... rn First, the integer W (1 ≤ W ≤ 1,000) representing the length of the box is given. It is then given the integer ri (3 ≤ ri ≤ 10), which represents the radius of each roll cake, separated by blanks. The number of cakes n is 12 or less. The number of datasets does not exceed 50. Output Print OK or NA on one line for each dataset. Example Input 30 4 5 6 30 5 5 5 50 3 3 3 10 10 49 3 3 3 10 10 Output OK OK OK NA Submitted Solution: ``` # -*- coding: utf-8 -*- import sys import os import math for s in sys.stdin: lst = list(map(int, s.split())) W = lst[0] R = lst[1:] R.sort() # zigzag Z = [] while R: r = R.pop(0) Z.append(r) if R: r = R.pop(-1) Z.append(r) #print('Z', Z) l = 0 n = len(Z) for i in range(0, n-1): r0 = Z[i] r1 = Z[i+1] x_length = math.sqrt((r0+r1)**2 - (r0-r1) ** 2) l += x_length l += Z[0] l += Z[-1] #print(l) if l <= W: print('OK') else: print('NA') ``` No
9,799