text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob "Correct Solution: ``` import sys import itertools # import numpy as np import time import math import heapq from collections import defaultdict sys.setrecursionlimit(10 ** 7) INF = 10 ** 18 MOD = 10 ** 9 + 7 read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines # map(int, input().split()) N = int(input()) adj = [[] for _ in range(N)] for i in range(N - 1): x, y = map(int, input().split()) x -= 1 y -= 1 adj[x].append(y) adj[y].append(x) def dfs(v, p): nim = 0 for u in adj[v]: if u == p: continue nim ^= dfs(u, v) if p == -1: return nim nim += 1 return nim res = dfs(0, -1) if res: print("Alice") else: print("Bob") ```
84,900
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob "Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10**7) N = int(input()) graph = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) checked = [False]*N def dfs(p): checked[p] = True g = 0 for np in graph[p]: if not checked[np]: g ^= dfs(np)+1 return g if dfs(0) == 0: print("Bob") else: print("Alice") ```
84,901
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` class Tree(): def __init__(self, n, edge, indexed=1): self.n = n self.tree = [[] for _ in range(n)] for e in edge: self.tree[e[0] - indexed].append(e[1] - indexed) self.tree[e[1] - indexed].append(e[0] - indexed) def setroot(self, root): self.root = root self.parent = [None for _ in range(self.n)] self.parent[root] = -1 self.order = [] self.order.append(root) stack = [root] while stack: node = stack.pop() for adj in self.tree[node]: if self.parent[adj] is None: self.parent[adj] = node self.order.append(adj) stack.append(adj) N = int(input()) edge = [tuple(map(int, input().split())) for _ in range(N - 1)] tree = Tree(N, edge) tree.setroot(0) grundy = [0 for _ in range(N)] for node in tree.order[::-1]: for adj in tree.tree[node]: if tree.parent[node] == adj: continue grundy[node] ^= grundy[adj] + 1 print('Alice' if grundy[0] != 0 else 'Bob') ``` Yes
84,902
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 6) N=int(input()) g = [[] for i in range(N)] for i in range(N-1): a,b=map(int,input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) nim = [-1 for i in range(N)] def dfs(cur,par): val = 0 for dst in g[cur]: if dst == par: continue val ^= dfs(dst,cur) + 1 nim[cur] = val return val dfs(0 , -1) #print(nim) if nim[0] == 0: print('Bob') else: print('Alice') ``` Yes
84,903
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` from collections import deque import heapq N = int(input()) gr = [None] * N child = [0] * N dic = {} q = [] for i in range(N-1): x,y = map(int,input().split()) x -= 1 y -= 1 if x not in dic: dic[x] = [] if y not in dic: dic[y] = [] dic[x].append(y) dic[y].append(x) child[x] += 1 child[y] += 1 dep = [float("inf")] * N dep[0] = 0 dq = deque([0]) while len(dq) > 0: n = dq.popleft() for i in dic[n]: if dep[i] > dep[n] + 1: dep[i] = dep[n] + 1 for i in range(N): if child[i] == 1: child[i] = 0 gr[i] = 0 heapq.heappush(q,[-1 * dep[i] , i]) while len(q) > 0: ngr = 0 no = heapq.heappop(q) now = no[1] for i in dic[now]: if gr[i] != None: ngr ^= (gr[i] + 1) else: child[i] -= 1 if child[i] <= 1 and gr[i] == None: heapq.heappush(q,[-1 * dep[i] , i]) gr[now] = ngr #print (gr) if gr[0] == 0: print ("Bob") else: print ("Alice") ``` Yes
84,904
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import sys input = sys.stdin.readline n = int(input()) ab = [list(map(int,input().split())) for i in range(n-1)] graph = [[] for i in range(n+1)] deg = [0]*(n+1) for a,b in ab: graph[a].append(b) graph[b].append(a) deg[a] += 1 deg[b] += 1 deg[1] += 1 dp = [[] for i in range(n+1)] mark = [0]*(n+1) stack = [] for i in range(1,n+1): if deg[i] == 1: stack.append(i) mark[i] = 1 while stack: x = stack.pop() if dp[x]: t = 0 for z in dp[x]: t ^= z mark[x] = t+1 if x == 1: break for y in graph[x]: if deg[y] > 1: dp[y].append(mark[x]) deg[y] -= 1 if deg[y] == 1: stack.append(y) if mark[1] == 1: print("Bob") else: print("Alice") ``` Yes
84,905
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def main(): n = I() e = collections.defaultdict(set) for _ in range(n-1): x,y = LI() e[x].add(y) e[y].add(x) def search(s): d = collections.defaultdict(lambda: inf) d[s] = 0 q = [] heapq.heappush(q, (0, s)) v = collections.defaultdict(bool) while len(q): k, u = heapq.heappop(q) if v[u]: continue v[u] = True for uv in e[u]: ud = 1 if v[uv]: continue vd = k + ud if d[uv] > vd: d[uv] = vd heapq.heappush(q, (vd, uv)) return d d = search(1) dd = collections.defaultdict(int) for i in range(2,n+1): dd[d[i]] += 1 if dd[1] == 1: return 'Alice' k = 0 for i,c in dd.items(): if c % 2 == 1: return 'Alice' if k % 2 == 1: return 'Alice' return 'Bob' print(main()) ``` No
84,906
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 6) N=int(input()) g = [[] for i in range(N)] for i in range(N-1): a,b=map(int,input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) nim = [-1 for i in range(N)] def dfs(cur,par): val = 0 for dst in g[cur]: if dst == par: continue val ^= dfs(dst,cur) + 1 nim[cur] = val return val dfs(0 , -1) #print(nim) if nim[0] == 0: print('Bob') else: print('Alice') ``` No
84,907
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` N=int(input()) g = [[] for i in range(N)] for i in range(N-1): a,b=map(int,input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) nim = [-1 for i in range(N)] def dfs(cur,par): val = 0 for dst in g[cur]: if dst == par: continue val ^= dfs(dst,cur) + 1 nim[cur] = val return val dfs(0 , -1) #print(nim) if nim[0] == 0: print('Bob') else: print('Alice') ``` No
84,908
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import sys input=sys.stdin.readline sys.setrecursionlimit(1000000) N=int(input()) edge=[[] for i in range(N)] for i in range(N-1): x,y=map(int,input().split()) edge[x-1].append(y-1) edge[y-1].append(x-1) def dfs(v,pv): if v==0: if len(edge[v])%2==1: return True else: ans=0 for nv in edge[v]: ans+=int(dfs(nv,v)) return ans%2==1 else: if len(edge[v])%2==0: return True else: ans=0 for nv in edge[v]: if nv!=pv: ans+=int(dfs(nv,v)) else: continue return ans%2==1 answer=dfs(0,-1) if answer: print("Alice") else: print("Bob") ``` No
84,909
Provide a correct Python 3 solution for this coding contest problem. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 "Correct Solution: ``` import sys from bisect import bisect class BinaryIndexedTree: def __init__(self, n, MOD): self.size = n + 1 self.tree = [0] * (n + 2) self.MOD = MOD def sum(self, i): i += 1 s = 0 while i > 0: s = (s + self.tree[i]) % self.MOD i -= i & -i return s def add(self, i, x): i += 1 while i <= self.size: self.tree[i] = (self.tree[i] + x) % self.MOD i += i & -i def debug_print(self, limit=None): if limit is None: limit = self.size acc = [0] + [self.sum(i) for i in range(limit)] aaa = [a1 - a0 for a0, a1 in zip(acc, acc[1:])] print(aaa) def solve(n, a, b, sss): if a > b: a, b = b, a for s0, s2 in zip(sss, sss[2:]): if s2 - s0 < a: return 0 MOD = 10 ** 9 + 7 bit = BinaryIndexedTree(n, MOD) bit.add(0, 1) bit.add(1, 1) sss.insert(0, -10 ** 18 - 1) pos = 0 for i in range(1, n): s0 = sss[i] s1 = sss[i + 1] lim = bisect(sss, s1 - b) - 1 if lim >= pos: bit.add(i + 1, bit.sum(lim)) if s1 - s0 < a: bit.add(i - 1, -bit.sum(i - 1)) pos = i - 1 return bit.sum(n) n, a, b, *sss = map(int, sys.stdin.read().split()) print(solve(n, a, b, sss)) ```
84,910
Provide a correct Python 3 solution for this coding contest problem. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 "Correct Solution: ``` import sys input = sys.stdin.readline from bisect import bisect_left, bisect_right INF = 10**18 + 100 N,A,B = map(int,input().split()) S = [-INF] + [int(x) for x in sys.stdin.read().split()] MOD = 10**9 + 7 dpX = [0] * (N+1) # 最後にYを選んだとして、直前に選んだXがどこにあるか dpY = [0] * (N+1) # 最後にXを選んだとして、直前に選んだYがどこにあるか dpX[0] = 1 dpY[0] = 1 dpX_cum = [1] * (N+1) + [0] # -1 dpY_cum = [1] * (N+1) + [0] # -1 dpX_left = 0 dpY_left = 0 for n,x in enumerate(S[2:],2): iA = bisect_right(S,x-A) iB = bisect_right(S,x-B) # ....XY xy = dpY_cum[iB-1] - dpY_cum[dpY_left-1] if iB >= dpY_left else 0 # ....YX yx = dpX_cum[iA-1] - dpX_cum[dpX_left-1] if iA >= dpX_left else 0 # ....XX が不可能なら捨てる。明示的に捨てるのではなく、生きている番号だけ持つ if iA != n: dpY_left = n-1 if iB != n: dpX_left = n-1 dpX[n-1] = xy dpX_cum[n-1] = (dpX_cum[n-2] + xy) % MOD dpX_cum[n] = dpX_cum[n-1] dpY[n-1] = yx dpY_cum[n-1] = (dpY_cum[n-2] + yx) % MOD dpY_cum[n] = dpY_cum[n-1] answer = dpX_cum[N-1] - dpX_cum[dpX_left-1] answer += dpY_cum[N-1] - dpY_cum[dpY_left-1] answer %= MOD print(answer) ```
84,911
Provide a correct Python 3 solution for this coding contest problem. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 "Correct Solution: ``` mod=10**9+7 import bisect,sys input=sys.stdin.readline N,A,B=map(int,input().split()) S=[int(input()) for i in range(N)] datax=[i for i in range(N+1)] datay=[i for i in range(N+1)] for i in range(2,N+1): if S[i-1]-S[i-2]>=A: datax[i]=datax[i-1] if S[i-1]-S[i-2]>=B: datay[i]=datay[i-1] #print(datax) #print(datay) dpx=[0]*(N+1) imosx=[0]*(N+1) dpy=[0]*(N+1) imosy=[0]*(N+1) dpx[0]=1 dpy[0]=1 imosx[0]=1 imosy[0]=1 for i in range(1,N): id=bisect.bisect_right(S,S[i]-B) R=min(id+1,i) L=datax[i] if R>=L: dpx[i]=(imosy[R-1]-imosy[L-2]*(L>=2))%mod imosx[i]=(imosx[i-1]+dpx[i])%mod else: imosx[i]=imosx[i-1] id=bisect.bisect_right(S,S[i]-A) R=min(id+1,i) L=datay[i] if R>=L: dpy[i]=(imosx[R-1]-imosx[L-2]*(L>=2))%mod imosy[i]=(imosy[i-1]+dpy[i])%mod else: imosy[i]=imosy[i-1] i=N R=i L=datax[i] if R>=L: dpx[i]=(imosy[R-1]-imosy[L-2]*(L>=2))%mod imosx[i]=(imosx[i-1]+dpx[i])%mod else: imosx[i]=imosx[i-1] R=i L=datay[i] if R>=L: dpy[i]=(imosx[R-1]-imosx[L-2]*(L>=2))%mod imosy[i]=(imosy[i-1]+dpy[i])%mod else: imosy[i]=imosy[i-1] #print(dpx) #print(dpy) print((dpx[-1]+dpy[-1])%mod) ```
84,912
Provide a correct Python 3 solution for this coding contest problem. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 "Correct Solution: ``` """ https://atcoder.jp/contests/agc009/tasks/agc009_c A <= B としてよい dpだろうなぁ dpA[i][X] = 1つ前を置いたのがBで、Aに置かれた最大がindexXの時の置き方 dpB[i][X] = 同様 if S[i]-S[i-1] >= B: dpA[i][X] = dpA[i-1][X] if X == i-1: dpA[i][X] = /// 推移は、BITですればおk もし差がB以下ならば→直前にBを置いていた場所に重ねおきはできない →直前にAに置いていて、なおかつ最後にBに置いたのとの差がB以下の場合だけBにおける →dpA[i][i-1]以外は0になる #直前とB以上の差があるとき if X != i-1: dpBに置く[i][最後にAに置いたのがX] = dpB[i-1][X] else: dpB[i][i-1] = ΣdpA[i-1][y] (y<=S-B) #差がないとき if X == i-1: dpB[i][i-1] = ΣdpA[i-1][y] (y<=S-B) else: dpB[i][X] = 0 """ import sys from sys import stdin from collections import deque def bitadd(a,w,bit): #aにwを加える(1-origin) x = a while x <= (len(bit)-1): bit[x] += w x += x & (-1 * x) def bitsum(a,bit): #ind 1~aまでの和を求める ret = 0 x = a while x > 0: ret += bit[x] x -= x & (-1 * x) return ret N,A,B = map(int,stdin.readline().split()) mod = 10**9+7 BITA = [0] * (N+3) BITB = [0] * (N+3) bitadd(1,1,BITA) #bitadd(0,1,BITB) aq = deque([]) bq = deque([]) Slis = [float("-inf")] for loop in range(N): S = int(stdin.readline()) aq.append( (S,loop+2) ) bq.append( (S,loop+2) ) while aq[0][0] <= S-A: aq.popleft() while bq[0][0] <= S-B: bq.popleft() #dpAへの推移(Bに置く) #Bに置けるのは、1つ前との差がB以上の場合全部おk #そうでない場合、前にAにおいていて、かつ差がB以上の場合 """ #全てokの場合 if S - Slis[-1] >= B: Aans = bitsum(bq[0][1]-1,BITB) Aans %= mod else: #そうでない場合→直前にAに置いていた場合のみ可能→bitをリセットする必要あり Aans = bitsum(bq[0][1]-1,BITB) Aans %= mod if S - Slis[-1] >= A: Bans = bitsum(aq[0][1]-1,BITA) Bans %= mod else: Bans = bitsum(aq[0][1]-1,BITA) Bans %= mod """ Aans = bitsum(bq[0][1]-1,BITB) Bans = bitsum(aq[0][1]-1,BITA) if Aans < 0: Aans = 0 if Bans < 0: Bans = 0 Aans %= mod Bans %= mod #print (Aans,Bans) #更新 if S - Slis[-1] >= B: bitadd(loop+1,Aans,BITA) else: nowsum = bitsum(N+2,BITA) bitadd(1,-1*nowsum,BITA) bitadd(loop+1,Aans,BITA) if S - Slis[-1] >= A: bitadd(loop+1,Bans,BITB) else: nowsum = bitsum(N+2,BITB) bitadd(1,-1*nowsum,BITB) bitadd(loop+1,Bans,BITB) Slis.append(S) if len(Slis) >= 3 and Slis[-1] - Slis[-3] < min(A,B): print (0) sys.exit() print ((bitsum(N+2,BITA) + bitsum(N+2,BITB))% mod) ```
84,913
Provide a correct Python 3 solution for this coding contest problem. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 "Correct Solution: ``` import sys readline = sys.stdin.readline class Lazysegtree: #RUQ def __init__(self, A, intv, initialize = True, segf = min): #区間は 1-indexed で管理 self.N = len(A) self.N0 = 2**(self.N-1).bit_length() self.intv = intv self.segf = segf self.lazy = [None]*(2*self.N0) if initialize: self.data = [intv]*self.N0 + A + [intv]*(self.N0 - self.N) for i in range(self.N0-1, -1, -1): self.data[i] = self.segf(self.data[2*i], self.data[2*i+1]) else: self.data = [intv]*(2*self.N0) def _ascend(self, k): k = k >> 1 c = k.bit_length() for j in range(c): idx = k >> j self.data[idx] = self.segf(self.data[2*idx], self.data[2*idx+1]) def _descend(self, k): k = k >> 1 idx = 1 c = k.bit_length() for j in range(1, c+1): idx = k >> (c - j) if self.lazy[idx] is None: continue self.data[2*idx] = self.data[2*idx+1] = self.lazy[2*idx] \ = self.lazy[2*idx+1] = self.lazy[idx] self.lazy[idx] = None def query(self, l, r): L = l+self.N0 R = r+self.N0 self._descend(L//(L & -L)) self._descend(R//(R & -R)-1) s = self.intv while L < R: if R & 1: R -= 1 s = self.segf(s, self.data[R]) if L & 1: s = self.segf(s, self.data[L]) L += 1 L >>= 1 R >>= 1 return s def update(self, l, r, x): L = l+self.N0 R = r+self.N0 Li = L//(L & -L) Ri = R//(R & -R) self._descend(Li) self._descend(Ri-1) while L < R : if R & 1: R -= 1 self.data[R] = x self.lazy[R] = x if L & 1: self.data[L] = x self.lazy[L] = x L += 1 L >>= 1 R >>= 1 self._ascend(Li) self._ascend(Ri-1) inf = 10**19 N, A, B = map(int, readline().split()) S = [-inf] + [int(readline()) for _ in range(N)] MOD = 10**9+7 dpa = Lazysegtree([1] + [0]*N, 0, initialize = True, segf = lambda x, y: (x+y)%MOD) dpb = Lazysegtree([1] + [0]*N, 0, initialize = True, segf = lambda x, y: (x+y)%MOD) for i in range(1, N+1): oka = 0 ng = i while abs(oka-ng) > 1: med = (oka+ng)//2 if S[i] - S[med] >= A: oka = med else: ng = med okb = 0 ng = i while abs(okb-ng) > 1: med = (okb+ng)//2 if S[i] - S[med] >= B: okb = med else: ng = med tb = dpa.query(0, okb+1) dpa.update(i-1, i, dpb.query(0, oka+1)) dpb.update(i-1, i, tb) if S[i] - S[i-1] < A: dpa.update(0, i-1, 0) if S[i] - S[i-1] < B: dpb.update(0, i-1, 0) print((dpa.query(0, N+1) + dpb.query(0, N+1)) % MOD) ```
84,914
Provide a correct Python 3 solution for this coding contest problem. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 "Correct Solution: ``` from bisect import bisect_left N,A,B=map(int,input().split()) inf,mod=float("inf"),10**9+7 S=[int(input()) for i in range(N)] St_A=[0]*N St_B=[0]*N J_A,J_B=[0],[0] for i in range(N): St_A[i]=bisect_left(S,S[i]+A)-1 St_B[i]=bisect_left(S,S[i]+B)-1 J_A.append(J_A[-1]+int(St_A[i]!=i)) J_B.append(J_B[-1]+int(St_B[i]!=i)) #print(St_A,St_B) #print(J_A,J_B) dp_A=[0]*N dp_B=[0]*N dp_A[-1],dp_B[-1]=1,1 for i in range(N-1)[::-1]: if St_A[i]==i: dp_A[i]=(dp_A[i+1]+dp_B[i+1])%mod else: if J_B[St_A[i]]-J_B[i+1]==0: dp_A[i]=dp_B[St_A[i]] else: dp_A[i]=0 if St_B[i]==i: dp_B[i]=(dp_A[i+1]+dp_B[i+1])%mod else: if J_A[St_B[i]]-J_A[i+1]==0: dp_B[i]=dp_A[St_B[i]] else: dp_B[i]=0 #print(dp_A) #print(dp_B) print((dp_A[0]+dp_B[0])%mod) ```
84,915
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 Submitted Solution: ``` import sys import numpy as np read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines MOD = 10**9 + 7 def main(N, A, B, S): if A > B: A, B = B, A if np.max(S[2:] - S[:-2]) < A: return 0 INF = 1 << 62 S = np.append(S, INF) # A 未満でたどって、Xがどこまで置けるか X = np.zeros_like(S) for i in range(1, N + 1): if S[i] - S[i - 1] >= A: X[i] = X[i - 1] else: X[i] = i # 直前の Y としてありうる最も右 Y = np.searchsorted(S, S - B, side='right') - 1 dp = np.zeros_like(S) dp_cum = np.zeros_like(S) dp[0] = 1 dp_cum[0] = 1 for n in range(1, N + 1): if X[n - 1] == 0: # 初出の Y dp[n] = 1 # 直前の Y の範囲 l, r = max(0, X[n - 1] - 1), min(n - 1, Y[n]) if l <= r: dp[n] += dp_cum[r] - dp_cum[l] + dp[l] dp[n] %= MOD dp_cum[n] = (dp_cum[n - 1] + dp[n]) % MOD return dp[-1] signature = '(i8,i8,i8,i8[:],)' if sys.argv[-1] == 'ONLINE_JUDGE': from numba.pycc import CC cc = CC('my_module') cc.export('main', signature)(main) cc.compile() from my_module import main N, A, B = map(int, readline().split()) S = np.array(read().split(), np.int64) print(main(N, A, B, S)) ``` No
84,916
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 Submitted Solution: ``` import sys input = sys.stdin.readline from bisect import bisect_left, bisect_right INF = 10**18 + 100 N,A,B = map(int,input().split()) S = [-INF] + [int(x) for x in sys.stdin.read().split()] MOD = 10**9 + 7 dpX = [0] * (N+1) # 最後にYを選んだとして、直前に選んだXがどこにあるか dpY = [0] * (N+1) # 最後にXを選んだとして、直前に選んだYがどこにあるか dpX[0] = 1 dpY[0] = 1 dpX_cum = [1] * (N+1) + [0] dpY_cum = [1] * (N+1) + [0] dpX_left = 0 dpY_left = 0 for n,x in enumerate(S[2:],2): iA = bisect_right(S,x-A) iB = bisect_right(S,x-B) # ....XY xy = dpY_cum[iB-1] - dpY_cum[dpY_left-1] # ....YX yx = dpX_cum[iA-1] - dpX_cum[dpX_left-1] # ....XX が不可能なら捨てる。明示的に捨てるのではなく、生きている番号だけ持つ if iA != n: dpY_left = n-1 if iB != n: dpX_left = n-1 dpX[n-1] = xy dpX_cum[n-1] = (dpX_cum[n-2] + xy) % MOD dpX_cum[n] = dpX_cum[n-1] dpY[n-1] = yx dpY_cum[n-1] = (dpY_cum[n-2] + yx) % MOD dpY_cum[n] = dpY_cum[n-1] answer = dpX_cum[N-1] - dpX_cum[dpX_left-1] answer += dpY_cum[N-1] - dpY_cum[dpY_left-1] answer %= MOD print(answer) ``` No
84,917
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 Submitted Solution: ``` import sys import bisect input = sys.stdin.readline class Bit: def __init__(self,n): self.size = n self.tree = [0]*(n+1) def sum(self,i): s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def add(self,i,x): while i <= self.size: self.tree[i] += x i += i & -i n,x,y = map(int,input().split()) a = [int(input()) for i in range(n)] mod = 10**9+7 bsx = [0]*n bsy = [0]*n rowx = [0]*n rowy = [0]*n for i in range(n): bsx[i] = bisect.bisect_right(a,a[i]-x) bsy[i] = bisect.bisect_right(a,a[i]-y) j = n-i-1 if j == 0: continue if a[j-1]+x <= a[j]: rowx[j-1] += rowx[j]+1 else: rowx[j-1] = 0 if a[j-1]+y <= a[j]: rowy[j-1] += rowy[j]+1 else: rowy[j-1] = 0 sm1 = [0 for i in range(n)] sm2 = [0 for i in range(n)] #sm1[i]: dp[i+1][i] #sm2[i]: dp[i][i+1] bit1 = Bit(n+2) bit2 = Bit(n+2) for i in range(n): if i == 0: sm1[i] = 1 sm2[i] = 1 else: sm1[i] = bit2.sum(min(i,bsx[i]+1))%mod sm2[i] = bit1.sum(min(i,bsy[i]+1))%mod bit1.add(i+1,sm1[i]) bit1.add(i+rowx[i]+2,-sm1[i]) bit2.add(i+1,sm2[i]) bit2.add(i+rowy[i]+2,-sm2[i]) print(sm1[-1]+sm2[-1]) ``` No
84,918
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How many ways are there to perform such division, modulo 10^9 + 7? Note that one of X and Y may be empty. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 1 ≦ A , B ≦ 10^{18} * 0 ≦ S_i ≦ 10^{18}(1 ≦ i ≦ N) * S_i < S_{i+1}(1 ≦ i ≦ N - 1) Input The input is given from Standard Input in the following format: N A B S_1 : S_N Output Print the number of the different divisions under the conditions, modulo 10^9 + 7. Examples Input 5 3 7 1 3 6 9 12 Output 5 Input 7 5 3 0 2 4 7 8 11 15 Output 4 Input 8 2 9 3 4 5 13 15 22 26 32 Output 13 Input 3 3 4 5 6 7 Output 0 Submitted Solution: ``` """ https://atcoder.jp/contests/agc009/tasks/agc009_c A <= B としてよい dpだろうなぁ dpA[i][X] = 1つ前を置いたのがBで、Aに置かれた最大がindexXの時の置き方 dpB[i][X] = 同様 if S[i]-S[i-1] >= B: dpA[i][X] = dpA[i-1][X] if X == i-1: dpA[i][X] = /// 推移は、BITですればおk もし差がB以下ならば→直前にBを置いていた場所に重ねおきはできない →直前にAに置いていて、なおかつ最後にBに置いたのとの差がB以下の場合だけBにおける →dpA[i][i-1]以外は0になる """ import sys from sys import stdin from collections import deque def bitadd(a,w,bit): #aにwを加える(1-origin) x = a while x <= (len(bit)-1): bit[x] += w x += x & (-1 * x) def bitsum(a,bit): #ind 1~aまでの和を求める ret = 0 x = a while x > 0: ret += bit[x] x -= x & (-1 * x) return ret N,A,B = map(int,stdin.readline().split()) mod = 10**9+7 BITA = [0] * (N+20) BITB = [0] * (N+20) bitadd(1,1,BITA) #bitadd(0,1,BITB) aq = deque([]) bq = deque([]) Slis = [float("-inf")] for loop in range(N): S = int(stdin.readline()) aq.append( (S,loop+2) ) bq.append( (S,loop+2) ) while aq[0][0] <= S-A: aq.popleft() while bq[0][0] <= S-B: bq.popleft() #dpAへの推移(Bに置く) #Bに置けるのは、1つ前との差がB以上の場合全部おk #そうでない場合、前にAにおいていて、かつ差がB以上の場合 #全てokの場合 if S - Slis[-1] >= B: Aans = bitsum(N+2,BITB) Aans %= mod else: #そうでない場合→直前にAに置いていた場合のみ可能→bitをリセットする必要あり Aans = bitsum(bq[0][1]-1,BITB) Aans %= mod if S - Slis[-1] >= A: Bans = bitsum(N+2,BITA) Bans %= mod else: Bans = bitsum(aq[0][1]-1,BITA) Bans %= mod if Aans < 0: Aans = 0 if Bans < 0: Bans = 0 #print (Aans,Bans) #更新 if S - Slis[-1] >= B: bitadd(loop+1,Aans,BITA) else: nowsum = bitsum(N+2,BITA) bitadd(1,-1*nowsum,BITA) bitadd(loop+1,Aans,BITA) if S - Slis[-1] >= A: bitadd(loop+1,Bans,BITB) else: nowsum = bitsum(N+2,BITB) bitadd(1,-1*nowsum,BITB) bitadd(loop+1,Bans,BITB) Slis.append(S) print ((bitsum(N+2,BITA) + bitsum(N+2,BITB))% mod) ``` No
84,919
Provide a correct Python 3 solution for this coding contest problem. Sigma and Sugim are playing a game. The game is played on a graph with N vertices numbered 1 through N. The graph has N-1 red edges and N-1 blue edges, and the N-1 edges in each color forms a tree. The red edges are represented by pairs of integers (a_i, b_i), and the blue edges are represented by pairs of integers (c_i, d_i). Each player has his own piece. Initially, Sigma's piece is at vertex X, and Sugim's piece is at vertex Y. The game is played in turns, where turns are numbered starting from turn 1. Sigma takes turns 1, 3, 5, ..., and Sugim takes turns 2, 4, 6, .... In each turn, the current player either moves his piece, or does nothing. Here, Sigma can only move his piece to a vertex that is directly connected to the current vertex by a red edge. Similarly, Sugim can only move his piece to a vertex that is directly connected to the current vertex by a blue edge. When the two pieces come to the same vertex, the game ends immediately. If the game ends just after the operation in turn i, let i be the total number of turns in the game. Sigma's objective is to make the total number of turns as large as possible, while Sugim's objective is to make it as small as possible. Determine whether the game will end in a finite number of turns, assuming both players plays optimally to achieve their respective objectives. If the answer is positive, find the number of turns in the game. Constraints * 2 ≦ N ≦ 200,000 * 1 ≦ X, Y ≦ N * X \neq Y * 1 ≦ a_i, b_i, c_i, d_i ≦ N * The N-1 edges in each color (red and blue) forms a tree. Input The input is given from Standard Input in the following format: N X Y a_1 b_1 a_2 b_2 : a_{N-1} b_{N-1} c_1 d_1 c_2 d_2 : c_{N-1} d_{N-1} Output If the game will end in a finite number of turns, print the number of turns. Otherwise, print `-1`. Examples Input 4 1 2 1 2 1 3 1 4 2 1 2 3 1 4 Output 4 Input 3 3 1 1 2 2 3 1 2 2 3 Output 4 Input 4 1 2 1 2 3 4 2 4 1 2 3 4 1 3 Output 2 Input 4 2 1 1 2 3 4 2 4 1 2 3 4 1 3 Output -1 Input 5 1 2 1 2 1 3 1 4 4 5 2 1 1 3 1 5 5 4 Output 6 "Correct Solution: ``` import sys sys.setrecursionlimit(2147483647) INF=float("inf") MOD=10**9+7 # 998244353 input=lambda:sys.stdin.readline().rstrip() def resolve(): n,x,y=map(int,input().split()) x-=1; y-=1 E1=[[] for _ in range(n)] E2=[[] for _ in range(n)] for _ in range(n-1): u,v=map(int,input().split()) u-=1; v-=1 E1[u].append(v) E1[v].append(u) for _ in range(n-1): u,v=map(int,input().split()) u-=1; v-=1 E2[u].append(v) E2[v].append(u) # E2 において、y-rooted tree とみて、depth,par を計算 par=[None]*n # x の必勝頂点を判定するのに必要 par[y]=y depth2=[None]*n depth2[y]=0 Q=[y] while(Q): v=Q.pop() for nv in E2[v]: if(depth2[nv] is not None): continue depth2[nv]=depth2[v]+1 par[nv]=v Q.append(nv) # E1の辺で、E2での距離が 3 以上のものは必勝 win=[0]*n for v in range(n): for nv in E1[v]: if(par[v]==nv or par[nv]==v or par[v]==par[nv] or par[par[v]]==nv or par[par[nv]]==v): continue win[nv]=win[v]=1 # E1 において、x-rooted tree とみて探索 # depth1 < depth2 -> 以降も探索できる # depth1 = depth2 -> そこで捕まる ans=depth2[x] depth1=[None]*n depth1[x]=0 Q=[x] while(Q): v=Q.pop() if(win[v]): # 探索できる状態 & 必勝頂点にいれば勝ち print(-1) return for nv in E1[v]: if(depth1[nv] is not None): continue depth1[nv]=depth1[v]+1 ans=max(ans,depth2[nv]) if(depth1[nv]<depth2[nv]): Q.append(nv) print(2*ans) resolve() ```
84,920
Provide a correct Python 3 solution for this coding contest problem. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 "Correct Solution: ``` def check_range(xy, n): for i in range(2): if xy[i] == -1: xy[i] = n - 1 elif xy[i] == n: xy[i] = 0 return xy while True: n = int(input()) if n == 0: break ms = [[0 for i in range(n)] for j in range(n)] xy = [n//2, n//2 - 1] i = 1 while i <= n*n: if ms[xy[1]][xy[0]] != 0: xy[0] -= 1 xy[1] -= 1 xy = check_range(xy, n) continue ms[xy[1]][xy[0]] = i xy[0] += 1 xy[1] -= 1 xy = check_range(xy, n) i += 1 for i in range(n): s = "" for j in range(n): s += "{0:>4}".format(str(ms[n - i - 1][j])) print(s) ```
84,921
Provide a correct Python 3 solution for this coding contest problem. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 "Correct Solution: ``` from sys import stdin def sqmatrix(n): return [[0] * n for i in range(n)] def magicsq(m): n = len(m) j = int(n/2) i = j + 1 for num in range(1, n**2 + 1): m[i][j] = num i += 1 j += 1 i = i%n j = j % n if m[i][j] != 0: i += 1 j -= 1 if j < 0: j = n -1 i = i % n return m for line in stdin: n = int(line) if n == 0: break sm = sqmatrix(n) for row in magicsq(sm): print (''.join(map(lambda x: str(x).rjust(4, ' '),row))) ```
84,922
Provide a correct Python 3 solution for this coding contest problem. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 "Correct Solution: ``` def square(n): mp = [[0 for _ in range(n)] for _ in range(n)] x, y = n // 2 , n // 2 + 1 mp[y][x] = 1 for i in range(2, n ** 2 + 1): x = (x + 1) % n y = (y + 1) % n while mp[y][x]: y = (y + 1) % n x = (x - 1) % n mp[y][x] = i for line in mp: s = "" for i in line: si = str(i) s += si.rjust(4) print(s) while True: n = int(input()) if not n: break square(n) ```
84,923
Provide a correct Python 3 solution for this coding contest problem. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 "Correct Solution: ``` # AOJ 0078 Magic Square # Python3 2018.6.17 bal4u MAX = 15 tbl = [0]*MAX while True: n = int(input()) if n == 0: break tbl = [[0 for r in range(n)] for c in range(n)] r, c = n//2+1, n//2 tbl[r][c] = i = 1 while i < n*n: r += 1 c += 1 while True: if c >= n: c = 0; elif c < 0: c = n - 1; if r >= n: r = 0; if tbl[r][c] == 0: i += 1 tbl[r][c] = i break r += 1 c -= 1 for r in range(n): for c in range(n): print(format(tbl[r][c], '4d'), end='') print() ```
84,924
Provide a correct Python 3 solution for this coding contest problem. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 "Correct Solution: ``` import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) if N == 0: return False x = N//2; y = x+1 P = [[-1]*N for i in range(N)] c = 0 N2 = N*N while c < N2: if P[y][x] == -1: c += 1 P[y][x] = c x = (x + 1) % N; y = (y + 1) % N else: x = (x - 1) % N; y = (y + 1) % N for line in P: write("".join(map("{:4d}".format, line))) write("\n") return True while solve(): ... ```
84,925
Provide a correct Python 3 solution for this coding contest problem. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 "Correct Solution: ``` import sys for n in map(int, sys.stdin): if not n: break a = [[-1]*(n+2)]+[[-1]+[0]*n+[-1] for _ in [0]*n]+[[-1]*(n+2)] x, y = (n+1)//2, (n+1)//2+1 for i in range(1, n**2+1): while a[y][x]: if a[y][x] == -1: if x in {0, n+1}: x = (1, n)[x==0] if y in {0, n+1}: y = (1, n)[y==0] else: x, y = x-1, y+1 a[y][x] = i x, y = x+1, y+1 for l in a[1:-1]: print("".join(map(lambda x: "{:>4d}".format(x), l[1:-1]))) ```
84,926
Provide a correct Python 3 solution for this coding contest problem. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 "Correct Solution: ``` def print_board(A,n): for i in range(n): s = "" for j in range(n): st = str(A[i][j]) if len(st) == 1: s += " " elif len(st) == 2: s += " " elif len(st) == 3: s += " " s += str(st) print(s) def check_leftdown(A,h,w,n): if h + 1 > n - 1: #下に抜けるならば,左に-1してその列に値が入っていない箇所を探す w -= 1 for x in range(n): if A[x][w] == 0: h = x break else: #左に抜けるならば if w - 1 < 0: w = n h += 1 else: h += 1 w -= 1 return h,w def check_rightdown(A,h,w,n): if h + 1 > n - 1: #下にも右にも抜ける場合 if w + 1 > n - 1: None else: #下に抜けるならば,右に+1してその列に値が入っていない箇所を探す w += 1 for x in range(n): if A[x][w] == 0: h = x break else: if w + 1 > n - 1: #右に抜けるならば w = 0 h += 1 else: #通常パターン h += 1 w += 1 if A[h][w] != 0: #値が既に埋まっている #左下をチェック h,w = check_leftdown(A,h,w,n) return h,w if __name__ == '__main__': while True: try: n = int(input()) if n == 0: break A = [[0 for i in range(n)] for j in range(n)] cnt = n * n for x in range(cnt): if x == 0: mid = n // 2 h = mid + 1 w = mid A[h][w] = x + 1 else: h,w = check_rightdown(A,h,w,n) A[h][w] = x+1 print_board(A,n) except EOFError: break ```
84,927
Provide a correct Python 3 solution for this coding contest problem. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 "Correct Solution: ``` while 1: n = int(input()) if n == 0: break l = [[ 0 for i in range(n)] for j in range(n)] i = n//2 + 1 j = n//2 l[i][j] = ' 1' c = 2 d = '{: >4}'.format(c) for x in range(n**2 - 1): i = (i + 1) % n j = (j + 1) % n while l[i][j] != 0: i = (i + 1) % n j = (j - 1) % n l[i][j] = d c += 1 d = '{: >4}'.format(c) for s in range(n): print(*l[s],sep="") ```
84,928
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` while True: n = int(input()) if n==0: break else: l = [[0 for i in range(n)] for j in range(n)] x = n//2 y = n//2+1 c = 0 while c < n**2: c += 1 while l[y][x] != 0: y += 1 if y >= n: y = 0 x -= 1 if x <= -1: x = n-1 l[y][x] = c x += 1 if x >= n: x = 0 y += 1 if y >= n: y = 0 for i in l: a = '' for j in i: if 0 <= j < 10**1: a = a + ' ' + str(j) elif 10**1<=j<10**2: a = a + ' ' + str(j) elif 10**2<=j<10**3: a = a + ' ' + str(j) print(a) ``` Yes
84,929
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` while True : n = int(input()) if n == 0 : break magic = list([0] * n for i in range(n)) x = (n+1)//2 - 1 y = (n+1)//2 - 2 for i in range(1, n**2+1) : x += 1 y += 1 while True : if x >= n : x = 0 if y >= n : y = 0 if magic[x][y] != 0 : x += 1 y -= 1 if y == -1 : y = n - 1 if x < n and y < n and magic[x][y] == 0 : break magic[x][y] = i for i in range(n) : for j in range(n) : print('{:4}'.format(magic[i][j]), end="") print() ``` Yes
84,930
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` while 1: n=int(input()) if n==0:break ans=[[0 for i in range(n)] for j in range(n)] y=n//2 x=n//2-1 for i in range(1,n**2+1): y=[y+1,y+1-n][y+1==n] x=[x+1,x+1-n][x+1==n] if ans[y][x]==0:ans[y][x]=str(i).rjust(4) else: y=[y+1,y+1-n][y+1==n] x=[x-1,x-1+n][x==0] ans[y][x]=str(i).rjust(4) for i in ans:print(''.join(map(str,i))) ``` Yes
84,931
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` for e in iter(input,'0'): n=int(e);m,f=[[0]*n for _ in[0]*n],'{:4}'*n s=lambda x:-~x%n j=n//2;i=j+1 m[i][j]=1 for k in range(2,n*n+1): i,j,t=s(i),s(j),j if m[i][j]:i,j=s(i),t m[i][j]=k for r in m:print(f.format(*r)) ``` Yes
84,932
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` # -*- coding: utf-8 -*- import sys import os import math for s in sys.stdin: n = int(s) if n == 0: break M = [[None for i in range(n)] for j in range(n)] # 1 x = n // 2 y = n // 2 + 1 M[y][x] = 1 x = x + 1 y = y + 1 counter = 2 while counter < n * n + 1: if x >= n: x = 0 elif x < 0: x = n - 1 if y >= n: y = 0 elif y < 0: y = n - 1 if M[y][x] is not None: x -= 1 y += 1 else: M[y][x] = counter counter += 1 x += 1 y += 1 for row in M: print(*row) ``` No
84,933
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0078 """ import sys class MagicSquare(): def __init__(self, size): self.size = size self.data = [['@']*self.size for _ in range(self.size)] self.fill_data() def fill_data(self): num = 1 x = self.size // 2 y = x + 1 self.data[y][x] = num while num < self.size**2: x += 1 if x >= self.size: x = 0 y += 1 if y >= self.size: y = 0 if self.data[y][x] == '@': num += 1 self.data[y][x] = num else: while self.data[y][x] != '@': x -= 1 if x < 0: x = self.size - 1 y += 1 if y >= self.size: y = 0 num += 1 self.data[y][x] = num def print_data(self): digits = len(str(self.size**2)) for row in self.data: print(*row) def main(args): while True: size = int(input()) if size < 3 or size%2 == 0: break ms = MagicSquare(size) ms.print_data() if __name__ == '__main__': main(sys.argv[1:]) ``` No
84,934
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` import sys f = sys.stdin def set1(sq): x = len(sq) // 2 y = len(sq) // 2 + 1 square[y][x] = 1 return x, y, 1 def mv_r(sq, x, y): x = (x + 1) % len(sq) y = (y + 1) % len(sq) return x, y def mv_l(sq, x, y): x -= 1 if x < 0: x += len(sq) y = (y + 1) % len(sq) return x, y def setnext(sq, x, y, i): x, y = mv_r(sq, x,y) i += 1 while sq[y][x]: x, y = mv_l(sq, x, y) sq[y][x] = i return x, y, i while True: n = int(f.readline()) if n == 0: break square = [[None for j in range(n)] for i in range(n)] arg = set1(square) for i in range(n * n - 1): arg = setnext(square,*arg) for line in square: print(*line) ``` No
84,935
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` from sys import stdin def sqmatrix(n): return [[0] * n for i in range(n)] def magicsq(m): n = len(m) j = int(n/2) i = j + 1 for num in range(1, n**2 + 1): m[i][j] = num i += 1 j += 1 i = i%n j = j % n if m[i][j] != 0: i += 1 j -= 1 if j < 0: j = n -1 i = i % n return m for line in stdin: n = int(line) if n == 0: break sm = sqmatrix(n) for row in magicsq(sm): print (' '.join(map(str,row))) ``` No
84,936
Provide a correct Python 3 solution for this coding contest problem. The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications. As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north. <image> Figure 1 People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below. 1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change. 2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south. Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze. Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows. : Wall .: Floor X: Emergency exit E: People facing east N: People facing north W: People facing west S: People facing south The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: W H str1 str2 :: strH The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze. The number of datasets does not exceed 50. Output For each input dataset, the time when all people finish evacuating is output on one line. Examples Input 10 3 ########## #E.......X ########## 4 4 #### #N.# #..X #### 5 5 ##### #N..# ###.X #S..# ##### 6 6 ###### #..#X# #.EE.# ####N# #....# ###### 8 8 ##X##### #....E.# #####.## #.#...## #.W.#..# #.#.N#.X #X##.#.# ######## 0 0 Output 8 NA 9 16 10 Input 10 3 E.......X 4 4 N.# ..X 5 5 N..# .X S..# 6 6 ..#X# .EE.# N# ....# 8 8 X##### ....E.# .## .#...## .W.#..# .#.N#.X X##.#.# 0 0 Output 8 NA 9 16 10 "Correct Solution: ``` from sys import stdin # from line_profiler import LineProfiler def main(): head = [[8,1,2,4],[1,2,4,8],[2,4,8,1],[4,8,1,2]] while(True): W,H = map(int, stdin.readline().split()) m = [[0]*W for _ in range(H)] ps = [] if not (W or H): break for h in range(H): s = stdin.readline() for w in range(W): if s[w] in [".", "X", "E", "N", "W", "S"]: m[h][max(0,w-1)] |= 1 m[min(H-1,h+1)][w] |= 2 m[h][min(W-1,w+1)] |= 4 m[max(0,h-1)][w] |= 8 if s[w] in ["E", "N", "W", "S"]: ps.append([h,w,["E", "N", "W", "S"].index(s[w])]) if s[w] == "X": m[h][w] |= 16 if W <= 2 or H <= 2: print(1) continue ttt = 0 while(True): ttt += 1 if ttt > 180: print("NA"); break dest = [] positions = [a[:2] for a in ps] for pi,p in enumerate(ps): for i in range(4): if head[p[2]][i] & m[p[0]][p[1]]: d = head[p[2]][i] if d == 1 and not [p[0],p[1]+1] in positions: p[2] = 0; dest.append([pi,2,p[0],p[1]+1]); break elif d == 2 and not [p[0]-1,p[1]] in positions: p[2] = 1; dest.append([pi,3,p[0]-1,p[1]]); break elif d == 4 and not [p[0],p[1]-1] in positions: p[2] = 2; dest.append([pi,0,p[0],p[1]-1]); break elif d == 8 and not [p[0]+1,p[1]] in positions: p[2] = 3; dest.append([pi,1,p[0]+1,p[1]]); break else: dest.append([pi,(p[2]+2)&3,p[0],p[1]]) dest = sorted(dest,key=lambda x: (x[2:],x[1])) dellist = [] for pi,d,dy,dx in dest: if not [dy,dx] in positions: positions.append([dy,dx]); ps[pi][:2] = [dy,dx] if m[ps[pi][0]][ps[pi][1]] & 16: dellist.append(pi) for idx in sorted(dellist)[::-1]: del ps[idx] if not len(ps): print(ttt); break if __name__ == "__main__": # prf = LineProfiler() # prf.add_function(main) # prf.runcall(main) # prf.print_stats() main() ```
84,937
Provide a correct Python 3 solution for this coding contest problem. The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications. As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north. <image> Figure 1 People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below. 1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change. 2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south. Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze. Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows. : Wall .: Floor X: Emergency exit E: People facing east N: People facing north W: People facing west S: People facing south The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: W H str1 str2 :: strH The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze. The number of datasets does not exceed 50. Output For each input dataset, the time when all people finish evacuating is output on one line. Examples Input 10 3 ########## #E.......X ########## 4 4 #### #N.# #..X #### 5 5 ##### #N..# ###.X #S..# ##### 6 6 ###### #..#X# #.EE.# ####N# #....# ###### 8 8 ##X##### #....E.# #####.## #.#...## #.W.#..# #.#.N#.X #X##.#.# ######## 0 0 Output 8 NA 9 16 10 Input 10 3 E.......X 4 4 N.# ..X 5 5 N..# .X S..# 6 6 ..#X# .EE.# N# ....# 8 8 X##### ....E.# .## .#...## .W.#..# .#.N#.X X##.#.# 0 0 Output 8 NA 9 16 10 "Correct Solution: ``` from sys import stdin from itertools import chain head = [[8,1,2,4],[1,2,4,8],[2,4,8,1],[4,8,1,2]] while(True): W,H = map(int, stdin.readline().split()) m = [[0]*W for _ in range(H)] ps = [] if not (W or H): break flag = True for h in range(H): s = stdin.readline() if "X" in s: flag = False for w in range(W): if s[w] in [".", "X", "E", "N", "W", "S"]: m[h][max(0,w-1)] |= 1 m[min(H-1,h+1)][w] |= 2 m[h][min(W-1,w+1)] |= 4 m[max(0,h-1)][w] |= 8 if s[w] in ["E", "N", "W", "S"]: ps.append([h,w,["E", "N", "W", "S"].index(s[w])]) if s[w] == "X": m[h][w] |= 16 # if flag: # print("NA") # continue if W <= 2 or H <= 2: print(1) continue # print(ps) # for n in m: # print(n) ttt = 0 while(True): ttt += 1 if ttt > 180: print("NA"); break # import time # time.sleep(1) mt = [[0]*W for _ in range(H)] for p in ps: mt[p[0]][p[1]] |= 1 dest = [] # for mmm in mt: # print(mmm) # print() # print([a[:2] for a in ps]) for pi,p in enumerate(ps): for i in range(4): if head[p[2]][i] & m[p[0]][p[1]]: d = head[p[2]][i] if d == 1 and not [p[0],p[1]+1] in [a[:2] for a in ps]: p[2] = 0; dest.append([pi,2,p[0],p[1]+1]); break elif d == 2 and not [p[0]-1,p[1]] in [a[:2] for a in ps]: p[2] = 1; dest.append([pi,3,p[0]-1,p[1]]); break elif d == 4 and not [p[0],p[1]-1] in [a[:2] for a in ps]: p[2] = 2; dest.append([pi,0,p[0],p[1]-1]); break elif d == 8 and not [p[0]+1,p[1]] in [a[:2] for a in ps]: p[2] = 3; dest.append([pi,1,p[0]+1,p[1]]); break else: dest.append([pi,(p[2]+2)&3,p[0],p[1]]) dest = sorted(dest,key=lambda x: (x[2:],x[1])) # print(dest) # for mmm in mt: # print(mmm) # print("ps = ",ps,dest) dellist = [] for pi,d,dy,dx in dest: # print(W,H,dy,dx,mt) if not mt[dy][dx]: # print("move",W,H,ps[pi][:2],dy,dx) mt[dy][dx] |= 1 ps[pi][:2] = [dy,dx] if m[ps[pi][0]][ps[pi][1]] & 16: # print("OUT") # print(ttt) # time.sleep(3) dellist.append(pi) # print(dellist) for idx in sorted(dellist)[::-1]: del ps[idx] if not len(ps): print(ttt) break # ms = [stdin.readline() for _ in range(H)] # print(m) # from pprint import pprint # print(ps) # for n in m: # print(n) # print() ```
84,938
Provide a correct Python 3 solution for this coding contest problem. The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications. As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north. <image> Figure 1 People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below. 1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change. 2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south. Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze. Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows. : Wall .: Floor X: Emergency exit E: People facing east N: People facing north W: People facing west S: People facing south The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: W H str1 str2 :: strH The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze. The number of datasets does not exceed 50. Output For each input dataset, the time when all people finish evacuating is output on one line. Examples Input 10 3 ########## #E.......X ########## 4 4 #### #N.# #..X #### 5 5 ##### #N..# ###.X #S..# ##### 6 6 ###### #..#X# #.EE.# ####N# #....# ###### 8 8 ##X##### #....E.# #####.## #.#...## #.W.#..# #.#.N#.X #X##.#.# ######## 0 0 Output 8 NA 9 16 10 Input 10 3 E.......X 4 4 N.# ..X 5 5 N..# .X S..# 6 6 ..#X# .EE.# N# ....# 8 8 X##### ....E.# .## .#...## .W.#..# .#.N#.X X##.#.# 0 0 Output 8 NA 9 16 10 "Correct Solution: ``` while True: dic = {"#":-3, ".":-1, "X":-2, "E":0, "N":1, "W":2, "S":3} def fix(c): return dic[c] w, h = map(int, input().split()) if w == 0: break mp = [list(map(fix, list(input()))) for _ in range(h)] persons = [] for y in range(h): for x in range(w): if mp[y][x] in (0, 1, 2, 3): persons.append([x, y, mp[y][x]]) vx = (1, 0, -1, 0) vy = (0, -1, 0, 1) time = 0 while time < 180: if not persons: print(time) break reserve = {} for index, state in enumerate(persons): x, y, d = state for i in range(d - 1, d + 3): dx, dy = vx[i % 4], vy[i % 4] if mp[y + dy][x + dx] in (-1, -2): persons[index][2] = i % 4 if (x + dx, y + dy) in reserve: if reserve[(x + dx, y + dy)][1] > (i + 2) % 4: reserve[(x + dx, y + dy)] = (index, (i + 2) % 4, mp[y + dy][x + dx]) else: reserve[(x + dx, y + dy)] = (index, (i + 2) % 4, mp[y + dy][x + dx]) break reserve = sorted(reserve.items(), key=lambda a:-a[1][0]) for k, v in reserve: nx, ny = k index, nd, panel = v px, py, _ = persons[index] mp[py][px] = -1 if panel == -1: persons[index] = [nx, ny, (nd + 2) % 4] mp[ny][nx] = (nd + 2) % 4 else: persons.pop(index) time += 1 else: print("NA") ```
84,939
Provide a correct Python 3 solution for this coding contest problem. The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications. As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north. <image> Figure 1 People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below. 1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change. 2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south. Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze. Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows. : Wall .: Floor X: Emergency exit E: People facing east N: People facing north W: People facing west S: People facing south The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: W H str1 str2 :: strH The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze. The number of datasets does not exceed 50. Output For each input dataset, the time when all people finish evacuating is output on one line. Examples Input 10 3 ########## #E.......X ########## 4 4 #### #N.# #..X #### 5 5 ##### #N..# ###.X #S..# ##### 6 6 ###### #..#X# #.EE.# ####N# #....# ###### 8 8 ##X##### #....E.# #####.## #.#...## #.W.#..# #.#.N#.X #X##.#.# ######## 0 0 Output 8 NA 9 16 10 Input 10 3 E.......X 4 4 N.# ..X 5 5 N..# .X S..# 6 6 ..#X# .EE.# N# ....# 8 8 X##### ....E.# .## .#...## .W.#..# .#.N#.X X##.#.# 0 0 Output 8 NA 9 16 10 "Correct Solution: ``` dd = ((1, 0), (0, -1), (-1, 0), (0, 1)) ENWS = "ENWS" ds = [-1, 0, 1, 2] ss = [2, 3, 0, 1] while 1: W, H = map(int, input().split()) if W == H == 0: break S = [input() for i in range(H)] ps = []; U = [[-1]*W for i in range(H)] for i in range(H): for j, c in enumerate(S[i]): if c in ENWS: ps.append([i, j, ENWS.index(c)]) U[i][j] = 1 elif c == '#': U[i][j] = W*H rest = len(ps) t = 0 while rest > 0 and t <= 180: for p in ps: y, x, c = p if c == -1: continue for d in ds: dx, dy = dd[(c+d) % 4] nx = x + dx; ny = y + dy if U[ny][nx] == -1: p[2] = (c+d) % 4 break ps.sort(key = lambda x: ss[x[2]]) qs = [] for p in ps: y, x, c = p if c == -1: continue dx, dy = dd[c] nx = x + dx; ny = y + dy if U[ny][nx] == -1: U[ny][nx] = 1 if S[ny][nx] == 'X': rest -= 1 p[2] = -1 qs.append((ny, nx)) else: p[0] = ny; p[1] = nx qs.append((y, x)) for y, x in qs: U[y][x] = -1 t += 1 if t <= 180: print(t) else: print("NA") ```
84,940
Provide a correct Python 3 solution for this coding contest problem. The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications. As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north. <image> Figure 1 People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below. 1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change. 2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south. Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze. Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows. : Wall .: Floor X: Emergency exit E: People facing east N: People facing north W: People facing west S: People facing south The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: W H str1 str2 :: strH The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze. The number of datasets does not exceed 50. Output For each input dataset, the time when all people finish evacuating is output on one line. Examples Input 10 3 ########## #E.......X ########## 4 4 #### #N.# #..X #### 5 5 ##### #N..# ###.X #S..# ##### 6 6 ###### #..#X# #.EE.# ####N# #....# ###### 8 8 ##X##### #....E.# #####.## #.#...## #.W.#..# #.#.N#.X #X##.#.# ######## 0 0 Output 8 NA 9 16 10 Input 10 3 E.......X 4 4 N.# ..X 5 5 N..# .X S..# 6 6 ..#X# .EE.# N# ....# 8 8 X##### ....E.# .## .#...## .W.#..# .#.N#.X X##.#.# 0 0 Output 8 NA 9 16 10 "Correct Solution: ``` from collections import defaultdict from typing import Dict class Players(object): def __init__(self): self.players: Dict[int, "Player"] = {} self.reservation = defaultdict(list) self.square = None self.goal = [] def set_goal(self, x, y): self.goal.append((x, y)) def add(self, player: "Player"): self.players[len(self.players)] = player def search_all(self): for i, player in self.players.items(): x, y, d = player.search(self.square) self.reservation[(x, y)].append(((d-2)%4, i)) for k, v in self.reservation.items(): if len(v) == 1: continue self.reservation[k] = [min(v)] def move_all(self): for (x, y), l in self.reservation.items(): _id = l[0][1] _x, _y = self.players[_id].pos self.players[_id].move(x, y) self.square[_y][_x], self.square[y][x] = ".", "o" self.reservation.clear() for i, player in self.players.copy().items(): x, y = player.pos if (x, y) in self.goal: del self.players[i] self.square[y][x] = "." @property def is_finished(self): return len(self.players) == 0 class Player(object): dir_dict = {"E": 0, "N": 1, "W": 2, "S": 3} dir_diff = ((1, 0), (0, -1), (-1, 0), (0, 1)) def __init__(self, x, y, direction): self.x = x self.y = y self.dir = self.dir_dict[direction] def search(self, square): for i in range(self.dir-1, self.dir+3): dx, dy = self.dir_diff[i % 4] if square[self.y+dy][self.x+dx] in (".", "X"): self.dir = i % 4 return self.x+dx, self.y+dy, self.dir else: return self.x, self.y, self.dir def move(self, x, y): self.x, self.y = x, y @property def pos(self): return self.x, self.y while True: W, H = map(int, input().split()) if W == 0: break square = [] players = Players() for y in range(H): square.append(list(input())) for x, c in enumerate(square[-1]): if c in "ENWS": players.add(Player(x, y, c)) elif c == "X": players.set_goal(x, y) players.square = square for i in range(1, 121): players.search_all() players.move_all() if players.is_finished: print(i) break else: print("NA") ```
84,941
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications. As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north. <image> Figure 1 People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below. 1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change. 2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south. Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze. Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows. : Wall .: Floor X: Emergency exit E: People facing east N: People facing north W: People facing west S: People facing south The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: W H str1 str2 :: strH The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze. The number of datasets does not exceed 50. Output For each input dataset, the time when all people finish evacuating is output on one line. Examples Input 10 3 ########## #E.......X ########## 4 4 #### #N.# #..X #### 5 5 ##### #N..# ###.X #S..# ##### 6 6 ###### #..#X# #.EE.# ####N# #....# ###### 8 8 ##X##### #....E.# #####.## #.#...## #.W.#..# #.#.N#.X #X##.#.# ######## 0 0 Output 8 NA 9 16 10 Input 10 3 E.......X 4 4 N.# ..X 5 5 N..# .X S..# 6 6 ..#X# .EE.# N# ....# 8 8 X##### ....E.# .## .#...## .W.#..# .#.N#.X X##.#.# 0 0 Output 8 NA 9 16 10 Submitted Solution: ``` from sys import stdin head = [[8,1,2,4],[1,2,4,8],[2,4,8,1],[4,8,1,2]] while(True): W,H = map(int, stdin.readline().split()) m = [[0]*W for _ in range(H)] ps = [] if not (W or H): break for h in range(H): s = stdin.readline() for w in range(W): if s[w] in [".", "X", "E", "N", "W", "S"]: m[h][max(0,w-1)] |= 1 m[min(H-1,h+1)][w] |= 2 m[h][min(W-1,w+1)] |= 4 m[max(0,h-1)][w] |= 8 if s[w] in ["E", "N", "W", "S"]: ps.append([h,w,["E", "N", "W", "S"].index(s[w])]) if s[w] == "X": m[h][w] |= 16 if W <= 2 or H <= 2: print(1) continue # print(ps) # for n in m: # print(n) ttt = 0 while(True): ttt += 1 if ttt > 180: print("NA"); break # import time # time.sleep(1) mt = [[0]*W for _ in range(H)] for p in ps: mt[p[0]][p[1]] |= 1 dest = [] # for mmm in mt: # print(mmm) # print() # print([a[:2] for a in ps]) for pi,p in enumerate(ps): for i in range(4): if head[p[2]][i] & m[p[0]][p[1]]: d = head[p[2]][i] if d == 1 and not [p[0],p[1]+1] in [a[:2] for a in ps]: p[2] = 0; dest.append([pi,2,p[0],p[1]+1]); break elif d == 2 and not [p[0]-1,p[1]] in [a[:2] for a in ps]: p[2] = 1; dest.append([pi,3,p[0]-1,p[1]]); break elif d == 4 and not [p[0],p[1]-1] in [a[:2] for a in ps]: p[2] = 2; dest.append([pi,0,p[0],p[1]-1]); break elif d == 8 and not [p[0]+1,p[1]] in [a[:2] for a in ps]: p[2] = 3; dest.append([pi,1,p[0]+1,p[1]]); break else: dest.append([pi,(p[2]+2)&3,p[0],p[1]]) # print(dest) dest = sorted(dest,key=lambda x: (x[2:],x[1])) # for mmm in mt: # print(mmm) # print("ps = ",ps,dest) dellist = [] for pi,d,dy,dx in dest: # print(W,H,dy,dx,mt) if not mt[dy][dx]: mt[dy][dx] |= 1 ps[pi][:2] = [dy,dx] if m[dy][dx] & 16: # print("OUT") # print(ttt) # time.sleep(3) dellist.append(pi) for idx in sorted(dellist)[::-1]: del ps[idx] if not len(ps): print(ttt) break # ms = [stdin.readline() for _ in range(H)] # print(m) # from pprint import pprint # print(ps) # for n in m: # print(n) # print() ``` No
84,942
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications. As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north. <image> Figure 1 People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below. 1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change. 2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south. Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze. Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows. : Wall .: Floor X: Emergency exit E: People facing east N: People facing north W: People facing west S: People facing south The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: W H str1 str2 :: strH The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze. The number of datasets does not exceed 50. Output For each input dataset, the time when all people finish evacuating is output on one line. Examples Input 10 3 ########## #E.......X ########## 4 4 #### #N.# #..X #### 5 5 ##### #N..# ###.X #S..# ##### 6 6 ###### #..#X# #.EE.# ####N# #....# ###### 8 8 ##X##### #....E.# #####.## #.#...## #.W.#..# #.#.N#.X #X##.#.# ######## 0 0 Output 8 NA 9 16 10 Input 10 3 E.......X 4 4 N.# ..X 5 5 N..# .X S..# 6 6 ..#X# .EE.# N# ....# 8 8 X##### ....E.# .## .#...## .W.#..# .#.N#.X X##.#.# 0 0 Output 8 NA 9 16 10 Submitted Solution: ``` from sys import stdin readline = stdin.readline from itertools import product N, W, S, E = (0, -1), (-1, 0), (0, 1), (1, 0) BLANK = ('.', 'X') DIRECTION = { 'N': N, 'W': W, 'S': S, 'E': E, } check_priority = { N: (E, N, W, S), W: (N, W, S, E), S: (W, S, E, N), E: (S, E, N, W), } step_priority = (E, N, W, S) def search_people(sq): people = [] for y, x in product(range(h), range(w)): if sq[y][x] in DIRECTION: sq[y][x] = person = Person(x, y, DIRECTION[sq[y][x]], sq) people.append(person) return people class Person: def __init__(self, x, y, direction, sq): self.x, self.y = x, y self.direction = direction self.sq = sq self.evacuating = True def check_direction(self): for direction in check_priority[self.direction]: dx, dy = direction if self.sq[self.y + dy][self.x + dx] in BLANK: self.direction = direction break def check_stepable(self): dx, dy = self.direction x, y = self.x + dx, self.y + dy if self.sq[y][x] == 'X': self.stepable = True return for dx, dy in step_priority: tmp = self.sq[y + dy][x + dx] if not isinstance(tmp, Person): continue if tmp == self: self.stepable = True break dx, dy = tmp.direction if tmp.x + dx == x and tmp.y + dy == y: self.stepable = False break def __repr__(self): return "'P'" def step(self): if self.stepable: dx, dy = self.direction self.sq[self.y][self.x] = '.' self.x += dx self.y += dy if self.sq[self.y][self.x] == '.': self.sq[self.y][self.x] = self else: self.evacuating = False while True: w, h = map(int, readline().split()) if w == 0: break squares = [list(readline().strip()) for _ in range(h)] people = search_people(squares) for i in range(180): for pi in people: pi.check_direction() for pi in people: pi.check_stepable() for pi in people: pi.step() people = [pi for pi in people if pi.evacuating] if len(people) == 0: print(i + 1) break else: print('NA') ``` No
84,943
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications. As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north. <image> Figure 1 People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below. 1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change. 2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south. Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze. Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows. : Wall .: Floor X: Emergency exit E: People facing east N: People facing north W: People facing west S: People facing south The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: W H str1 str2 :: strH The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze. The number of datasets does not exceed 50. Output For each input dataset, the time when all people finish evacuating is output on one line. Examples Input 10 3 ########## #E.......X ########## 4 4 #### #N.# #..X #### 5 5 ##### #N..# ###.X #S..# ##### 6 6 ###### #..#X# #.EE.# ####N# #....# ###### 8 8 ##X##### #....E.# #####.## #.#...## #.W.#..# #.#.N#.X #X##.#.# ######## 0 0 Output 8 NA 9 16 10 Input 10 3 E.......X 4 4 N.# ..X 5 5 N..# .X S..# 6 6 ..#X# .EE.# N# ....# 8 8 X##### ....E.# .## .#...## .W.#..# .#.N#.X X##.#.# 0 0 Output 8 NA 9 16 10 Submitted Solution: ``` from sys import stdin readline = stdin.readline from itertools import product N, W, S, E = (0, -1), (-1, 0), (0, 1), (1, 0) BLANK = ('.', 'X') DIRECTION = { 'N': N, 'W': W, 'S': S, 'E': E, } check_priority = { N: (E, N, W, S), W: (N, W, S, E), S: (W, S, E, N), E: (S, E, N, W), } step_priority = (E, N, W, S) def search_people(sq): people = [] for y, x in product(range(h), range(w)): if sq[y][x] in DIRECTION: sq[y][x] = person = Person(x, y, DIRECTION[sq[y][x]], sq) people.append(person) return people class Person: def __init__(self, x, y, direction, sq): self.x, self.y = x, y self.direction = direction self.sq = sq self.evacuating = True def check_direction(self): for direction in check_priority[self.direction]: dx, dy = direction if self.sq[self.y + dy][self.x + dx] in BLANK: self.direction = direction break def check_stepable(self): dx, dy = self.direction x, y = self.x + dx, self.y + dy if self.sq[y][x] == 'X': return True for dx, dy in step_priority: tmp = self.sq[y + dy][x + dx] if not isinstance(tmp, Person): continue if tmp == self: self.stepable = True break dx, dy = tmp.direction if tmp.x + dx == x and tmp.y + dy == y: self.stepable = False break def __repr__(self): return "'P'" def step(self): if self.stepable: dx, dy = self.direction self.sq[self.y][self.x] = '.' self.x += dx self.y += dy if self.sq[self.y][self.x] == '.': self.sq[self.y][self.x] = self else: self.evacuating = False while True: w, h = map(int, readline().split()) if w == 0: break squares = [list(readline().strip()) for _ in range(h)] people = search_people(squares) for i in range(180): for pi in people: pi.check_direction() for pi in people: pi.check_stepable() for pi in people: pi.step() people = [pi for pi in people if pi.evacuating] if len(people) == 0: print(i + 1) break else: print('NA') ``` No
84,944
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the following specifications. As shown in Fig. 1, the giant maze is represented by W × H squares of horizontal W and vertical H. Each square is either a passage (white square), a wall (brown square), or an emergency exit (green square). The circles in the figure represent people, and the lowercase letters (E, W, S, N) in them represent the direction in which the person is facing (north, south, east, and west). The figure is drawn with the upward direction facing north. <image> Figure 1 People in the giant maze initially stand facing either north, south, east, or west. Each person attempts to move in 1-second increments at the same time, following the steps below. 1. Look at the right, front, left, and back squares in the direction you are currently facing, and turn to the first vacant aisle or emergency exit you find. If there is no such square, the direction will not change. 2. If the square in front of you is open and not in front of another person, move it. If there are multiple people with the same square in front of you, the selected one will move in the order of the people in that square, east, north, west, and south. Those who arrive at the emergency exit after moving will evacuate safely and disappear from the maze. Create a program that inputs the given huge maze and the location information of people and outputs the time when all people finish evacuating. If it takes more than 180 seconds to escape, output NA. Maze and person location information is given by the characters in rows H and columns W. The meaning of each character is as follows. : Wall .: Floor X: Emergency exit E: People facing east N: People facing north W: People facing west S: People facing south The boundary between the maze and the outside is either the wall # or the emergency exit X. In addition, there is always one or more people in the huge maze. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: W H str1 str2 :: strH The first line gives the horizontal size W of the maze and the vertical size H (1 ≤ W, H ≤ 30). The following H line is given the string stri (length W) that represents the i-th line of the maze. The number of datasets does not exceed 50. Output For each input dataset, the time when all people finish evacuating is output on one line. Examples Input 10 3 ########## #E.......X ########## 4 4 #### #N.# #..X #### 5 5 ##### #N..# ###.X #S..# ##### 6 6 ###### #..#X# #.EE.# ####N# #....# ###### 8 8 ##X##### #....E.# #####.## #.#...## #.W.#..# #.#.N#.X #X##.#.# ######## 0 0 Output 8 NA 9 16 10 Input 10 3 E.......X 4 4 N.# ..X 5 5 N..# .X S..# 6 6 ..#X# .EE.# N# ....# 8 8 X##### ....E.# .## .#...## .W.#..# .#.N#.X X##.#.# 0 0 Output 8 NA 9 16 10 Submitted Solution: ``` from sys import stdin head = [[8,1,2,4],[1,2,4,8],[2,4,8,1],[4,8,1,2]] while(True): W,H = map(int, stdin.readline().split()) m = [[0]*W for _ in range(H)] ps = [] if not (W or H): break for h in range(H): s = stdin.readline() for w in range(W): if s[w] in [".", "X", "E", "N", "W", "S"]: m[h][max(0,w-1)] |= 1 m[min(H-1,h+1)][w] |= 2 m[h][min(W-1,w+1)] |= 4 m[max(0,h-1)][w] |= 8 if s[w] in ["E", "N", "W", "S"]: ps.append([h,w,["E", "N", "W", "S"].index(s[w])]) if s[w] == "X": m[h][w] |= 16 # print(ps) # for n in m: # print(n) ttt = 0 while(True): ttt += 1 if ttt > 180: print("NA"); break # import time # time.sleep(1) mt = [[0]*W for _ in range(H)] for p in ps: mt[p[0]][p[1]] |= 1 dest = [] # for mmm in mt: # print(mmm) # print() # print([a[:2] for a in ps]) for pi,p in enumerate(ps): for i in range(4): if head[p[2]][i] & m[p[0]][p[1]]: d = head[p[2]][i] if d == 1 and not [p[0],p[1]+1] in [a[:2] for a in ps]: p[2] = 0; dest.append([pi,2,p[0],p[1]+1]); break elif d == 2 and not [p[0]-1,p[1]] in [a[:2] for a in ps]: p[2] = 1; dest.append([pi,3,p[0]-1,p[1]]); break elif d == 4 and not [p[0],p[1]-1] in [a[:2] for a in ps]: p[2] = 2; dest.append([pi,0,p[0],p[1]-1]); break elif d == 8 and not [p[0]+1,p[1]] in [a[:2] for a in ps]: p[2] = 3; dest.append([pi,1,p[0]+1,p[1]]); break else: dest.append([pi,(p[2]+2)&3,p[0],p[1]]) # print(dest) dest = sorted(dest,key=lambda x: (x[2:],x[1])) # for mmm in mt: # print(mmm) # print("ps = ",ps,dest) dellist = [] for pi,d,dy,dx in dest: if not mt[dy][dx]: mt[dy][dx] |= 1 ps[pi][:2] = [dy,dx] if m[dy][dx] & 16: # print("OUT") # print(ttt) # time.sleep(3) dellist.append(pi) for idx in sorted(dellist)[::-1]: del ps[idx] if not len(ps): print(ttt) break # ms = [stdin.readline() for _ in range(H)] # print(m) # from pprint import pprint # print(ps) # for n in m: # print(n) # print() ``` No
84,945
Provide a correct Python 3 solution for this coding contest problem. Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same depth) with sufficiently large depth. Then, starting from its root, write on it a number, say, 1 for each position of first tree, and draw different number, say, 2 for second tree. The “intersection” of two trees is a tree with nodes numbered both 1 and 2, and the “union” is a tree with nodes numbered either 1 or 2, or both. For example, the intersection of trees in Figures 1 and 2 is a tree in Figure 3, and the union of them is a tree in Figure 4. <image> A node of a tree is expressed by a sequence of characters, “(,)“. If a node has a left child, the expression of the child is inserted between ’(’ and ’,’. The expression of a right child is inserted between ’,’ and ’)’. For exam- ple, the expression of trees in Figures 1 and 2 are “((,),(,))“ and “((,(,)),)“, respectively. Input Each line of the input contains an operation. An operation starts with a character which specifies the type of operation, either ’i’ or ’u’: ’i’ means intersection, and ’u’ means union. Following the character and a space, two tree expressions are given, separated by a space. It is assumed that 1 <= #nodes in a tree <= 100, and no tree expression contains spaces and syntax errors. Input is terminated by EOF. Output For each line of the input, output a tree expression, without any space, for the result of the operation. Example Input i ((,),(,)) ((,(,)),) u ((,),(,)) ((,(,)),) Output ((,),) ((,(,)),(,)) "Correct Solution: ``` # AOJ 1001: Binary Tree Intersection And Union # Python3 2018.7.5 bal4u def parse(p, i): global sz node[i][2] += 1 del p[0] if p[0] != ',': if node[i][0] == 0: node[i][0] = sz sz += 1 parse(p, node[i][0]) del p[0] if p[0] != ')': if node[i][1] == 0: node[i][1] = sz sz += 1 parse(p, node[i][1]) del p[0] def act(i, k): global ans if node[i][2] < k: return ans += '(' if node[i][0] > 0: act(node[i][0], k) ans += ',' if node[i][1] > 0: act(node[i][1], k) ans += ')' while True: try: op, a, b = input().split() except: break sz = 1 node = [[0 for j in range(3)] for i in range(210)] parse(list(a), 0) parse(list(b), 0) ans = '' act(0, 2 if op== 'i' else 1) print(ans) ```
84,946
Provide a correct Python 3 solution for this coding contest problem. Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same depth) with sufficiently large depth. Then, starting from its root, write on it a number, say, 1 for each position of first tree, and draw different number, say, 2 for second tree. The “intersection” of two trees is a tree with nodes numbered both 1 and 2, and the “union” is a tree with nodes numbered either 1 or 2, or both. For example, the intersection of trees in Figures 1 and 2 is a tree in Figure 3, and the union of them is a tree in Figure 4. <image> A node of a tree is expressed by a sequence of characters, “(,)“. If a node has a left child, the expression of the child is inserted between ’(’ and ’,’. The expression of a right child is inserted between ’,’ and ’)’. For exam- ple, the expression of trees in Figures 1 and 2 are “((,),(,))“ and “((,(,)),)“, respectively. Input Each line of the input contains an operation. An operation starts with a character which specifies the type of operation, either ’i’ or ’u’: ’i’ means intersection, and ’u’ means union. Following the character and a space, two tree expressions are given, separated by a space. It is assumed that 1 <= #nodes in a tree <= 100, and no tree expression contains spaces and syntax errors. Input is terminated by EOF. Output For each line of the input, output a tree expression, without any space, for the result of the operation. Example Input i ((,),(,)) ((,(,)),) u ((,),(,)) ((,(,)),) Output ((,),) ((,(,)),(,)) "Correct Solution: ``` class Node: def __init__(self, left, right): self.left = left self.right = right self.val = '' @classmethod def fromString(cls, s): pos = 1 if s[pos] == '(': e = getEnd(s, 1) left = cls.fromString(s[1:e+1]) pos = e + 2 else: left = None pos += 1 if s[pos] == '(': e = getEnd(s, pos) right = Node.fromString(s[pos:e+1]) else: right = None return cls(left, right) def __str__(self): lstr = "" if self.left == None else str(self.left) rstr = "" if self.right == None else str(self.right) return "({},{})".format(lstr, rstr) def getEnd(s, pos): count = 0 while True: if s[pos] == '(': count += 1 elif s[pos] == ')': count -= 1 if count == 0: break pos += 1 return pos def intersection(root1, root2): if root1.left == None or root2.left == None: root1.left = None else: intersection(root1.left, root2.left) if root1.right == None or root2.right == None: root1.right = None else: intersection(root1.right, root2.right) def union(root1, root2): if root1.left == None and root2.left == None: pass elif root1.left != None and root2.left == None: pass elif root1.left == None and root2.left != None: root1.left = root2.left else: union(root1.left, root2.left) if root1.right == None and root2.right == None: pass elif root1.right != None and root2.right == None: pass elif root1.right == None and root2.right != None: root1.right = root2.right else: union(root1.right, root2.right) if __name__ == '__main__': try: while True: line = input().strip().split() c = line[0] a = Node.fromString(line[1]) b = Node.fromString(line[2]) if c == 'i': intersection(a, b) else: union(a, b) print(a) except EOFError: pass ```
84,947
Provide a correct Python 3 solution for this coding contest problem. Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same depth) with sufficiently large depth. Then, starting from its root, write on it a number, say, 1 for each position of first tree, and draw different number, say, 2 for second tree. The “intersection” of two trees is a tree with nodes numbered both 1 and 2, and the “union” is a tree with nodes numbered either 1 or 2, or both. For example, the intersection of trees in Figures 1 and 2 is a tree in Figure 3, and the union of them is a tree in Figure 4. <image> A node of a tree is expressed by a sequence of characters, “(,)“. If a node has a left child, the expression of the child is inserted between ’(’ and ’,’. The expression of a right child is inserted between ’,’ and ’)’. For exam- ple, the expression of trees in Figures 1 and 2 are “((,),(,))“ and “((,(,)),)“, respectively. Input Each line of the input contains an operation. An operation starts with a character which specifies the type of operation, either ’i’ or ’u’: ’i’ means intersection, and ’u’ means union. Following the character and a space, two tree expressions are given, separated by a space. It is assumed that 1 <= #nodes in a tree <= 100, and no tree expression contains spaces and syntax errors. Input is terminated by EOF. Output For each line of the input, output a tree expression, without any space, for the result of the operation. Example Input i ((,),(,)) ((,(,)),) u ((,),(,)) ((,(,)),) Output ((,),) ((,(,)),(,)) "Correct Solution: ``` import re class bintree(): def __init__(self, str1): self.str1 = str1 if self.str1[1] != ",": c = 0 counter = 0 for s in str1[1:]: counter += 1 if s == "(": c += 1 elif s == ")": c -= 1 if c == 0: break self.left = bintree(str1[1:counter+1]) #match1 = re.search("\((\(.*\)),.*\)",str1) #if match1 != None: # self.left = bintree(str(match1.group(1))) else: self.left = "" if self.str1[-2] != ",": str1 = str1[0]+str1[1+len(str(self.left)):] match2 = re.search("\(,(\(.*\))\)",str1) if match2 != None: self.right = bintree(str(str1[2:-1])) else: self.right = "" def __str__(self): return self.str1 def inter(bin1, bin2): if bin1.left != "" and bin2.left != "": strleft = inter(bin1.left, bin2.left) else: strleft = "" if bin1.right != "" and bin2.right != "": strright = inter(bin1.right, bin2.right) else: strright = "" return "(" + strleft + "," + strright + ")" def union(bin1, bin2): if bin1.left != "" or bin2.left != "": if bin1.left == "": strleft = str(bin2.left) elif bin2.left == "": strleft = str(bin1.left) else: strleft = union(bin1.left, bin2.left) else: strleft = "" if bin1.right != "" or bin2.right != "": if bin1.right == "": strright = str(bin2.right) elif bin2.right == "": strright = str(bin1.right) else: strright = union(bin1.right, bin2.right) else: strright = "" #print("(" + strleft + "," + strright + ")") return "(" + strleft + "," + strright + ")" while True: try: inputs = map(str,input().split()) order = next(inputs) if order == "i": t1 = bintree(next(inputs)) t2 = bintree(next(inputs)) #print(t1.left,t1.right) print(inter(t1, t2))# == "((((((,),),),),),)") elif order == "u": t1 = bintree(next(inputs)) t2 = bintree(next(inputs)) #print(t1.left,t1.right) #print(t1.left,t1.right) print(union(t1,t2))# == "((((,),(,)),((,),(,))),(((,),(,)),((,),(,))))") except EOFError as exception: break ```
84,948
Provide a correct Python 3 solution for this coding contest problem. Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same depth) with sufficiently large depth. Then, starting from its root, write on it a number, say, 1 for each position of first tree, and draw different number, say, 2 for second tree. The “intersection” of two trees is a tree with nodes numbered both 1 and 2, and the “union” is a tree with nodes numbered either 1 or 2, or both. For example, the intersection of trees in Figures 1 and 2 is a tree in Figure 3, and the union of them is a tree in Figure 4. <image> A node of a tree is expressed by a sequence of characters, “(,)“. If a node has a left child, the expression of the child is inserted between ’(’ and ’,’. The expression of a right child is inserted between ’,’ and ’)’. For exam- ple, the expression of trees in Figures 1 and 2 are “((,),(,))“ and “((,(,)),)“, respectively. Input Each line of the input contains an operation. An operation starts with a character which specifies the type of operation, either ’i’ or ’u’: ’i’ means intersection, and ’u’ means union. Following the character and a space, two tree expressions are given, separated by a space. It is assumed that 1 <= #nodes in a tree <= 100, and no tree expression contains spaces and syntax errors. Input is terminated by EOF. Output For each line of the input, output a tree expression, without any space, for the result of the operation. Example Input i ((,),(,)) ((,(,)),) u ((,),(,)) ((,(,)),) Output ((,),) ((,(,)),(,)) "Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def tree_left(node, it): c = next(it) if c == "(": node[0] = [None, None] tree_left(node[0], it) c = next(it) if c == ",": tree_right(node, it) else: assert False def tree_right(node, it): c = next(it) if c == "(": node[1] = [None, None] tree_left(node[1], it) c = next(it) if c == ")": pass else: assert False def tree_parse(s): root = [None, None] s = s[1:] it = iter(s) tree_left(root, it) return root def tree_dump(node): s = "" s += "(" if node[0]: s += tree_dump(node[0]) s += "," if node[1]: s += tree_dump(node[1]) s += ")" return s def intersection(t1, t2): if t1 is None or t2 is None: return None node = [None, None] node[0] = intersection(t1[0], t2[0]) node[1] = intersection(t1[1], t2[1]) return node def union(t1, t2): if t1 is None and t2 is None: return None elif t1 is None: return t2 elif t2 is None: return t1 node = [None, None] node[0] = union(t1[0], t2[0]) node[1] = union(t1[1], t2[1]) return node def main(): for line in sys.stdin: op, s1, s2 = line.split() tree1 = tree_parse(s1) tree2 = tree_parse(s2) #print(tree_dump(tree1)) #print(tree_dump(tree2)) if op == "i": ans = intersection(tree1, tree2) print(tree_dump(ans)) elif op == "u": ans = union(tree1, tree2) print(tree_dump(ans)) if __name__ == "__main__": main() ```
84,949
Provide a correct Python 3 solution for this coding contest problem. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 "Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): rr = [] while True: n,w = LI() if n == 0: break a = [I() for _ in range(n)] ma = max(a) l = (ma // w + 1) b = [0] * l for c in a: b[c//w] += 1 h = max(b) r = 0.01 for i in range(l): bi = b[i] d = (l-i-1) / (l-1) r += d * bi / h rr.append(r) return '\n'.join(map(str, rr)) print(main()) ```
84,950
Provide a correct Python 3 solution for this coding contest problem. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 "Correct Solution: ``` while True: n, w = map(int, input().split()) if n is 0 and w is 0: break l = [int(input()) for i in range(n)] max_num = 0 for i in range(n): max_num = max(max_num, l[i]) hist_size = int((max_num/w) + 1) hist = [0.0] * int(hist_size) for i in range(n): hist[int(l[i]/w)] += 1 max_height= 0 for i in range(hist_size): max_height = max(max_height,hist[i]) ans = 0.0 for i in range(hist_size-1): ans += hist[i]/max_height*(hist_size - 1 - i)/(hist_size-1) ans += 0.01 print(ans) ```
84,951
Provide a correct Python 3 solution for this coding contest problem. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 "Correct Solution: ``` # coding: utf-8 while 1: n,w=map(int,input().split()) if n==0: break dic={} mx=-1 max_section=-1 for i in range(1+100//w): dic[i]=0 for i in range(n): x=int(input()) dic[x//w]+=1 mx=max(mx,dic[x//w]) max_section=max(max_section,x//w) ans=0 for i in range(1+100//w): ans+=(dic[i]/mx)*(1-i*(1/(max_section))) print(ans+0.01) ```
84,952
Provide a correct Python 3 solution for this coding contest problem. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 "Correct Solution: ``` while True: n, w = list(map(int, input().split())) if n==0: break v = [int(input()) for i in range(n)] h = [0 for i in range(100)] ma = 0 mi = 1e9 for i in range(n): h[v[i]//w] += 1 ma = max(ma, v[i]//w) mi = min(mi, v[i]//w) sm = ma-mi h = [h[i]/max(h) for i in range(100)] ans = 0.01 for i in range(mi, ma): ans += (sm-i+mi)/(sm+mi)*h[i] print(ans) ```
84,953
Provide a correct Python 3 solution for this coding contest problem. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 "Correct Solution: ``` while True: N,W = map(int,input().split()) if N == 0: break src = [int(input()) for i in range(N)] highest = max(src) bands = highest//W + 1 hist = [0 for i in range(bands)] for i in range(N): hist[src[i] // W] += 1 ans = maxn = 0 for i,n in enumerate(hist): ans += n * (bands-1-i) maxn = max(n, maxn) print(ans / maxn / (bands-1) + 0.01) ```
84,954
Provide a correct Python 3 solution for this coding contest problem. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 "Correct Solution: ``` while True: N, W = map(int, input().split()) if not N: break s = list(sorted([int(input()) for i in range(N)])) m = s[-1] // W + 1 ss = [0] * m for c in s: ss[c // W] += 1 unit = max(ss) a = 0 for i, c in enumerate(ss): a += (1 - i / (m - 1)) * (c / unit) print(a + 0.01) ```
84,955
Provide a correct Python 3 solution for this coding contest problem. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 "Correct Solution: ``` while 1: n,w=map(int,input().split()) if n==w==0:break a=[0]*100 s=h=int(0) while n: b=int(input()) a[b//w]+=1 s=max(s,b//w) h=max(h,a[b//w]) n-=1 ans=0.01 for i in range(int(s)+1): ans+=a[i]/h*(s-i)/s print(ans) ```
84,956
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 Submitted Solution: ``` from heapq import * def calcInk(wdt,val): maxval=val[-1] histnum=maxval//wdt hist=[] for i in range(histnum+1): hist.append([]) vl=len(val) for i in range(vl): v=heappop(val) hist[v//wdt].append(v) highest=0 for i in range(len(hist)): highest=max(highest,len(hist[i])) ink=0 for i in range(len(hist)): ink+=(1-i/histnum)*(len(hist[i])/highest) return ink+0.01 if __name__=='__main__': while True: n,w=map(int,input().split()) if n==w==0: break V=[] for _ in range(n): heappush(V,int(input())) ``` No
84,957
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 Submitted Solution: ``` from heapq import * ``` No
84,958
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 Submitted Solution: ``` from heapq import * def calcInk(wdt,val): maxval=val[-1] histnum=maxval//wdt hist=[] for i in range(histnum+1): hist.append([]) vl=len(val) for i in range(vl): v=heappop(val) hist[v//wdt].append(v) highest=0 for i in range(len(hist)): highest=max(highest,len(hist[i])) ink=0 for i in range(len(hist)): ink+=(1-i/histnum)*(len(hist[i])/highest) return ink+0.01 ``` No
84,959
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0-9 occur five times, those in the interval 10-19 occur three times, and 20-29 and 30-39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format. n w v1 v2 . . vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v < w, the second one if w ≤ v < 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset. You may assume the following. 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: <image> Each output value should be in a decimal fraction and may have an error less than 10-5 . Example Input 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output 0.51 0.26 1.4766666666666667 Submitted Solution: ``` if __name__=='__main__': while True: n,w=map(int,input().split()) if n==w==0: break V=[] for _ in range(n): heappush(V,int(input())) maxV=V[-1] histnum=maxV//w hist=[] for i in range(histnum+1): hist.append([]) vl=len(V) for i in range(vl): v=heappop(V) hist[v//w].append(v) highest=0 for i in range(len(hist)): highest=max(highest,len(hist[i])) ink=0 for i in range(len(hist)): ink+=(1-i/histnum)*(len(hist[i])/highest) print(ink) ``` No
84,960
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS "Correct Solution: ``` #!/usr/bin/env python3 #aoj b import re from collections import defaultdict def check(i):#メモ化再帰 if d[i] > 0: return d[i] d[i] = 1#チェック状態 for y in range(p[i][0],p[i][1]+1): for x in range(p[i][2],p[i][3]+1): if s[y][x] == ".":#長方形内部に空の部分が存在 d[i] = 3 #SUSPICIOUS return d[i] elif s[y][x] != i:#長方形内部に他の物質が存在 if d[s[y][x]] == 1:#その物質がチェック状態 d[i] = 3 #SUSPICIOUS(循環参照 テストケース4) return d[i] c = check(s[y][x])#そいつの状態確認の再帰 if c == 3: d[i] == 3 return d[i] d[i] = 2#SAFE return 2 N = int(input()) for _ in range(N): h,w = map(int,input().split()) s = [list(input()) for _ in range(h)] p = defaultdict(list) #p[0]:上端,p[1]:下端,p[2]:左端,p[3]:右端 #y座標の追加は横方向で見る(上端は上から、下端は下から) for y in range(h):#上端 for x in range(w): if s[y][x] != '.' and len(p[s[y][x]]) < 1: p[s[y][x]].append(y) for y in range(h)[::-1]:#下端 for x in range(w): if s[y][x] != '.' and len(p[s[y][x]]) < 2: p[s[y][x]].append(y) #x座標の追加は縦方向で見る(左端は左から、右端は右から) for x in range(w):#左端 for y in range(h): if s[y][x] != '.' and len(p[s[y][x]]) < 3: p[s[y][x]].append(x) for x in range(w)[::-1]:#右端 for y in range(h): if s[y][x] != '.' and len(p[s[y][x]]) < 4: p[s[y][x]].append(x) d = defaultdict(lambda : 0)#メモ化再帰用dict for i in p.keys(): if check(i) == 3: print('SUSPICIOUS') break else: print('SAFE') ```
84,961
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS "Correct Solution: ``` def can_fill(image, k, v): for y in range(v[1], v[3] + 1): for x in range(v[0], v[2] + 1): m = image[y][x] if m != k and m != '*': return False return True def is_safe(image, p): keys = list(p.keys()) i = 0 while i < len(keys): k = keys[i] v = p[k] if can_fill(image, k, v): for y in range(v[1], v[3] + 1): for x in range(v[0], v[2] + 1): image[y][x] = '*' keys.remove(k) i = 0 else: i += 1 return len(keys) == 0 n = int(input()) for i in range(n): h, w = map(int, input().split(' ')) image = [list(input()) for y in range(h)] p = {} for y in range(h): for x in range(w): m = image[y][x] if m != '.': if m not in p: p[m] = [x, y, x, y] else: p[m][0] = min(p[m][0], x) p[m][1] = min(p[m][1], y) p[m][2] = max(p[m][2], x) p[m][3] = max(p[m][3], y) print('SAFE' if is_safe(image, p) else 'SUSPICIOUS') ```
84,962
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS "Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): rr = [] n = I() ni = 0 while ni < n: ni += 1 h,w = LI() s = [[c for c in S()] for _ in range(h)] d = collections.defaultdict(lambda: [inf,-inf,inf,-inf]) for i in range(h): for j in range(w): if s[i][j] == '.': continue t = d[s[i][j]] if t[0] > i: t[0] = i if t[1] < i: t[1] = i if t[2] > j: t[2] = j if t[3] < j: t[3] = j f = True k = set(d.keys()) while f: f = False for t in list(k): hi,ha,wi,wa = d[t] ff = True for i in range(hi,ha+1): for j in range(wi,wa+1): if s[i][j] != t and s[i][j] != '?': ff = False break if not ff: break if ff: k.remove(t) f = True for i in range(hi,ha+1): for j in range(wi,wa+1): s[i][j] = '?' if not k: rr.append('SAFE') else: rr.append('SUSPICIOUS') return '\n'.join(map(str,rr)) print(main()) ```
84,963
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS "Correct Solution: ``` import sys from collections import defaultdict def check(i): #メモ化再帰でやります if d[i] > 0: return d[i] d[i] = 1 #チェック状態 """長方形と仮定し、矛盾があればSUSPICUOUS""" for y in range(p[i][0],p[i][1]+1): for x in range(p[i][2],p[i][3]+1): if s[y][x] == ".": #長方形内部に空の部分が存在 d[i] = 3 #SUSPICUOUS return d[i] elif s[y][x] != i: #長方形内部に他の物質が存在 if d[s[y][x]] == 1: #その物質が現在チェック状態 d[i] = 3 #SUSPICUOUS(循環参照であるため。例:テストケース4) return d[i] c = check(s[y][x]) #再帰でそいつの状態をみる if c == 3: #SUSPICUOUS d[i] = 3 #SUSPICUOUS return d[i] d[i] = 2 #SAFE return 2 n = int(sys.stdin.readline()) for _ in range(n): h,w = map(int, sys.stdin.readline().split()) s = [sys.stdin.readline() for i in range(h)] p = defaultdict(list) """p[0]:上端,p[1]:下端,p[2]:左端,p[3]:右端""" for y in range(h): for x in range(w): if s[y][x] != "." and len(p[s[y][x]]) < 1: p[s[y][x]].append(y) for y in range(h)[::-1]: for x in range(w): if s[y][x] != "." and len(p[s[y][x]]) < 2: p[s[y][x]].append(y) for x in range(w): for y in range(h): if s[y][x] != "." and len(p[s[y][x]]) < 3: p[s[y][x]].append(x) for x in range(w)[::-1]: for y in range(h): if s[y][x] != "." and len(p[s[y][x]]) < 4: p[s[y][x]].append(x) d = defaultdict(lambda : 0) #メモ化再帰用のdict for i in p.keys(): if check(i) == 3: print("SUSPICIOUS") break else: print("SAFE") ```
84,964
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS "Correct Solution: ``` n = int(input()) for _ in range(n): h, w = map(int, input().split()) mp = [list(input()) for _ in range(h)] range_dic = {} keys = [] for y in range(h): for x in range(w): c = mp[y][x] if c in range_dic: x1, x2, y1, y2 = range_dic[c] range_dic[c] = (min(x, x1), max(x, x2), min(y, y1), max(y, y2)) else: range_dic[c] = (x, x, y, y) keys.append(c) while keys: tmp = keys[:] for key in keys: break_flag = False x1, x2, y1, y2 = range_dic[key] for x in range(x1, x2 + 1): for y in range(y1, y2 + 1): if not mp[y][x] in (key, "#"): break_flag = True break if break_flag: break else: for y in range(y1, y2 + 1): mp[y][x1:x2 + 1] = ["#"] * (x2 - x1 + 1) keys.remove(key) if tmp == keys: print("SUSPICIOUS") break else: print("SAFE") ```
84,965
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS "Correct Solution: ``` n = int(input()) for _ in range(n): h, w = map(int, input().split()) mp = [list(input()) for _ in range(h)] range_dic = {} keys = [] for y in range(h): for x in range(w): c = mp[y][x] if c in range_dic: x1, x2, y1, y2 = range_dic[c] range_dic[c] = (min(x, x1), max(x, x2), min(y, y1), max(y, y2)) else: range_dic[c] = (x, x, y, y) keys.append(c) while keys: tmp = keys[:] for key in keys: break_flag = False x1, x2, y1, y2 = range_dic[key] for x in range(x1, x2 + 1): for y in range(y1, y2 + 1): if not mp[y][x] in (key, "#"): break_flag = True break if break_flag: break else: for x in range(x1, x2 + 1): for y in range(y1, y2 + 1): mp[y][x] = "#" keys.remove(key) if tmp == keys: print("SUSPICIOUS") break else: print("SAFE") ```
84,966
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS "Correct Solution: ``` from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,copy,time sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inp(): return int(input()) def inpl(): return list(map(int, input().split())) def inpl_str(): return list(input().split()) def dfs(s,cnt): global ans if cnt > 10: ans = False return for t in lines[s]: dfs(t,cnt+1) N = inp() for _ in range(N): H,W = inpl() MAP = [['.']*(W+2)] + [['.']+list(input())+['.'] for y in range(H)] + [['.']*(W+2)] als = set([]) almm = [[INF,0,INF,0] for _ in range(30)] for y in range(1,H+1): for x in range(1,W+1): tmp = MAP[y][x] if tmp != '.': tmp = ord(tmp) - ord('A') als.add(tmp) almm[tmp][0] = min(almm[tmp][0],x) almm[tmp][1] = max(almm[tmp][1],x) almm[tmp][2] = min(almm[tmp][2],y) almm[tmp][3] = max(almm[tmp][3],y) ans = True lines = defaultdict(set) for a in als: xl,xr,yl,yr = almm[a] alpha = chr(a+ord('A')) for x in range(xl,xr+1): for y in range(yl,yr+1): if MAP[y][x] == '.': ans = False break elif MAP[y][x] != alpha: lines[a].add(ord(MAP[y][x])-ord('A')) for a in als: dfs(a,0) if not ans: print('SUSPICIOUS') else: print('SAFE') ```
84,967
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Submitted Solution: ``` from itertools import permutations from collections import defaultdict def judge(field, c): for y in xrange(corner[c][2], corner[c][3] + 1): for x in xrange(corner[c][0], corner[c][1] + 1): if field[y][x] != c and field[y][x] != "*": return False field[y][x] = "*" return True N = int(raw_input()) for loop in xrange(N): h, w = map(int, raw_input().split()) field = [raw_input() for i in xrange(h)] chars = set([]) corner = defaultdict(lambda :[49,0,49,0]) for y in xrange(h): for x in xrange(w): c = field[y][x] if c == ".": continue chars.add(c) corner[c][0] = min(corner[c][0], x) corner[c][1] = max(corner[c][1], x) corner[c][2] = min(corner[c][2], y) corner[c][3] = max(corner[c][3], y) for order in permutations(chars): cp = map(list, field) for c in order: if not judge(cp, c): break else: print("SAFE") break else: print("SUSPICIOUS") ``` No
84,968
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Submitted Solution: ``` class Baggage: height = 0 width = 0 contentsdata = [[]] def __init__(self, H, W): self.height = H self.width = W self.contentsdata = [["." for i in range(0, H)] for j in range(0, W)] def setContents(self, x, y, cnt): self.contentsdata[x][y] = cnt def contentscheck(baggage, checkwords): # ????????? => True???????????¢???=> False left = 10000 right = 10000 up = 1000 bottom = 1000 for x in range(0, baggage.width): # ???????????????????????¨????????????????????????????????? if(baggage.contentsdata[x].count(checkwords) > 0): left = x break for x in sorted([int(i) for i in range(0, baggage.width)], reverse=True): # ???????????????????????¨????????????????????????????????? if(baggage.contentsdata[x].count(checkwords) > 0): right = x break for y in range(0, baggage.height): # ???????????????????????¨????????????????????????????????? for x in range(0, baggage.width): if(baggage.contentsdata[x][y] == checkwords): up = y break else: continue break for y in sorted([int(i) for i in range(0, baggage.height)], reverse=True): # ???????????????????????¨????????????????????????????????? for x in range(0, baggage.width): if(baggage.contentsdata[x][y] == checkwords): bottom = y break else: continue break # print(checkwords + ": (left, right, up, bottom) = (" + str(left) + ", " + str(right) + ", " + str(up) + ", " + str(bottom) + ")") for x in range(left, right + 1): for y in range(up, bottom + 1): if(baggage.contentsdata[x][y] == "."): return True break else: continue break return False n = int(input()) usedwordslist = [] for k in range(0, n): try: size = [int(i) for i in input().split(" ")] # size = [H, W] checkingbaggage = Baggage(size[0], size[1]) for i in range(0, size[0]): data = list(input()) for j in range(0, size[1]): checkingbaggage.contentsdata[j][i] = data[j] if(data[j] != "." and usedwordslist.count(data[j]) == 0): usedwordslist.append(data[j]) usedwordslist.sort() for i in usedwordslist: if(contentscheck(checkingbaggage, i)): print("SUSPICIOUS") break else: print("SAFE") except: raise exit() '''???????????\????¢??????¨ for i in range(0, size[0]): for j in range(0, size[1]): print(checkingbaggage.contentsdata[j][i]) print(usedwordslist)''' usedwordslist.clear() ``` No
84,969
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Submitted Solution: ``` class Baggage: height = 0 width = 0 contentsdata = [[]] def __init__(self, H, W): self.height = H self.width = W self.contentsdata = [["." for i in range(0, H)] for j in range(0, W)] def setContents(self, x, y, cnt): self.contentsdata[x][y] = cnt def contentscheck(baggage, checkwords): # ????????? => 0???????????¢???????????§???=> 1 ?????¨???????????¢???=> 2 left = 0 right = 0 up = 0 bottom = 0 for x in range(0, baggage.width): # ???????????????????????¨????????????????????????????????? if(baggage.contentsdata[x].count(checkwords) > 0): left = x break for x in sorted([int(i) for i in range(0, baggage.width)], reverse=True): # ???????????????????????¨????????????????????????????????? if(baggage.contentsdata[x].count(checkwords) > 0): right = x break for y in range(0, baggage.height): # ???????????????????????¨????????????????????????????????? for x in range(0, baggage.width): if(baggage.contentsdata[x][y] == checkwords): up = y break else: continue break for y in sorted([int(i) for i in range(0, baggage.height)], reverse=True): # ???????????????????????¨????????????????????????????????? for x in range(0, baggage.width): if(baggage.contentsdata[x][y] == checkwords): bottom = y break else: continue break # print(checkwords + ": (left, right, up, bottom) = (" + str(left) + ", " + str(right) + ", " + str(up) + ", " + str(bottom) + ")") complite = 1 for x in range(left, right + 1): for y in range(up, bottom + 1): # print(checkwords + ":" + baggage.contentsdata[x][y]) if(baggage.contentsdata[x][y] != checkwords): complite = 0 if(baggage.contentsdata[x][y] == "."): return 0 break else: continue break if(complite == 0): return 1 else: return 2 n = int(input()) usedwordslist = [] for k in range(0, n): cmp = False try: size = [int(i) for i in input().split(" ")] # size = [H, W] checkingbaggage = Baggage(size[0], size[1]) for i in range(0, size[0]): data = list(input()) for j in range(0, size[1]): checkingbaggage.contentsdata[j][i] = data[j] if(data[j] != "." and usedwordslist.count(data[j]) == 0): usedwordslist.append(data[j]) usedwordslist.sort() for i in usedwordslist: jdg = int(contentscheck(checkingbaggage, i)) if(jdg == 0): print("SUSPICIOUS") break if(jdg == 2): cmp = True else: print("cmp " + str(cmp)) if(cmp): print("SAFE") elif(len(usedwordslist) == 0): print("SAFE") else: print("SUSPICIOUS") except: raise exit() '''???????????\????¢??????¨ for i in range(0, size[0]): for j in range(0, size[1]): print(checkingbaggage.contentsdata[j][i]) print(usedwordslist)''' usedwordslist.clear() ``` No
84,970
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Submitted Solution: ``` class Baggage: height = 0 width = 0 contentsdata = [[]] def __init__(self, H, W): self.height = H self.width = W self.contentsdata = [["." for i in range(0, H)] for j in range(0, W)] def setContents(self, x, y, cnt): self.contentsdata[x][y] = cnt def contentscheck(baggage, checkwords): # ????????? => 0???????????¢???????????§???=> 1 ?????¨???????????¢???=> 2 left = 0 right = 0 up = 0 bottom = 0 for x in range(0, baggage.width): # ???????????????????????¨????????????????????????????????? if(baggage.contentsdata[x].count(checkwords) > 0): left = x break for x in sorted([int(i) for i in range(0, baggage.width)], reverse=True): # ???????????????????????¨????????????????????????????????? if(baggage.contentsdata[x].count(checkwords) > 0): right = x break for y in range(0, baggage.height): # ???????????????????????¨????????????????????????????????? for x in range(0, baggage.width): if(baggage.contentsdata[x][y] == checkwords): up = y break else: continue break for y in sorted([int(i) for i in range(0, baggage.height)], reverse=True): # ???????????????????????¨????????????????????????????????? for x in range(0, baggage.width): if(baggage.contentsdata[x][y] == checkwords): bottom = y break else: continue break # print(checkwords + ": (left, right, up, bottom) = (" + str(left) + ", " + str(right) + ", " + str(up) + ", " + str(bottom) + ")") complite = 1 for x in range(left, right + 1): for y in range(up, bottom + 1): # print(checkwords + ":" + baggage.contentsdata[x][y]) if(baggage.contentsdata[x][y] != checkwords): complite = 0 if(baggage.contentsdata[x][y] == "."): return 0 break else: continue break if(complite == 0): return 1 else: return 2 n = int(input()) usedwordslist = [] for k in range(0, n): cmp = False try: size = [int(i) for i in input().split(" ")] # size = [H, W] checkingbaggage = Baggage(size[0], size[1]) for i in range(0, size[0]): data = list(input()) for j in range(0, size[1]): checkingbaggage.contentsdata[j][i] = data[j] if(data[j] != "." and usedwordslist.count(data[j]) == 0): usedwordslist.append(data[j]) usedwordslist.sort() for i in usedwordslist: jdg = int(contentscheck(checkingbaggage, i)) if(jdg == 0): print("SUSPICIOUS") break if(jdg == 2): cmp = True else: if(cmp): print("SAFE") elif(len(usedwordslist) == 0): print("SAFE") else: print("SUSPICIOUS") except: raise exit() '''???????????\????¢??????¨ for i in range(0, size[0]): for j in range(0, size[1]): print(checkingbaggage.contentsdata[j][i]) print(usedwordslist)''' usedwordslist.clear() ``` No
84,971
Provide a correct Python 3 solution for this coding contest problem. You are recording a result of a secret experiment, which consists of a large set of N-dimensional vectors. Since the result may become very large, you are thinking of compressing it. Fortunately you already have a good compression method for vectors with small absolute values, all you have to do is to preprocess the vectors and make them small. You can record the set of vectors in any order you like. Let's assume you process them in the order v_1, v_2,..., v_M. Each vector v_i is recorded either as is, or as a difference vector. When it is recorded as a difference, you can arbitrarily pick up an already chosen vector v_j (j<i) and a real value r. Then the actual vector value recorded is (v_i - r v_j). The values of r and j do not affect the compression ratio so much, so you don't have to care about them. Given a set of vectors, your task is to write a program that calculates the minimum sum of the squared length of the recorded vectors. Input The input is like the following style. N M v_{1,1} v_{1,2} ... v_{1,N} ... v_{M,1} v_{M,2} ... v_{M,N} The first line contains two integers N and M (1 \leq N, M \leq 100), where N is the dimension of each vector, and M is the number of the vectors. Each of the following M lines contains N floating point values v_{i,j} (-1.0 \leq v_{i,j} \leq 1.0) which represents the j-th element value of the i-th vector. Output Output the minimum sum of the squared length of the recorded vectors. The output should not contain an absolute error greater than 10^{-6}. Examples Input 2 3 1.0 1.0 -1.0 0.0 0.5 0.5 Output 1.0 Input 1 1 1.0 Output 1.0 Input 4 3 1.0 1.0 0.0 0.0 -1.0 0.0 -1.0 0.0 0.5 0.5 0.5 0.5 Output 3.0 "Correct Solution: ``` import sys readline = sys.stdin.readline write = sys.stdout.write def calc(V, es, r): mins = [(10**18, -1)]*V for s, t, w in es: mins[t] = min(mins[t], (w, s)) mins[r] = (-1, -1) group = [0]*V comp = [0]*V cnt = 0 used = [0]*V for v in range(V): if not used[v]: chain = [] cur = v while cur!=-1 and not used[cur]: chain.append(cur) used[cur] = 1 cur = mins[cur][1] if cur!=-1: cycle = 0 for e in chain: group[e] = cnt if e==cur: cycle = 1 comp[cnt] = 1 if not cycle: cnt += 1 if cycle: cnt += 1 else: for e in chain: group[e] = cnt cnt += 1 if cnt == V: return sum(map(lambda x:x[0], mins)) + 1 res = sum(mins[v][0] for v in range(V) if v!=r and comp[group[v]]) n_es = [] for s, t, w in es: gs = group[s]; gt = group[t] if gs == gt: continue if comp[gt]: n_es.append((gs, gt, w - mins[t][0])) else: n_es.append((gs, gt, w)) return res + calc(cnt, n_es, group[r]) def solve(): N, M = map(int, readline().split()) V = [] D = [] for i in range(M): *Vi, = map(float, readline().split()) d = sum(e**2 for e in Vi) if d <= 1e-9: continue V.append(Vi) D.append(d) M = len(V) E = [] for i in range(M): Vi = V[i] for j in range(M): if i == j: continue Vj = V[j] t = 0 for k in range(N): t += Vi[k] * Vj[k] r = t / (D[j]) c = 0 for k in range(N): c += (Vi[k] - r*Vj[k])**2 E.append((j+1, i+1, c)) E.append((0, i+1, D[i])) write("%.16f\n" % calc(M+1, E, 0)) solve() ```
84,972
Provide a correct Python 3 solution for this coding contest problem. Sunuke-kun's dictionary contains the words s1, ..., sn, which consist of n lowercase letters. This satisfies s1 <... <sn when compared in lexicographical order. Unfortunately, some characters are faint and unreadable. Unreadable characters are represented by?. Find out how many ways to restore the dictionary by replacing? With lowercase letters, even with mod 1,000,000,007. Constraints * 1 ≤ n ≤ 50 * 1 ≤ | si | ≤ 20 * The characters that appear in si are lowercase letters or? Input n s1 .. .. sn Output Print the answer on one line. Examples Input 2 ?sum??mer c??a??mp Output 703286064 Input 3 snuje ????e snule Output 1 "Correct Solution: ``` # seishin.py import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): MOD = 10**9 + 7 N = int(readline()) M = 20 L = 26 ca = ord('a') cq = ord('?') S = [[ca-1]*M for i in range(N)] for i in range(N): s = readline().strip() S[i][:len(s)] = map(ord, s) memo = [[[[-1]*(L+2) for i in range(M+1)] for j in range(N+1)] for k in range(N+1)] for i in range(N+1): for p in range(M+1): for c in range(L+2): memo[i][i][p][c] = 1 for i in range(N+1): for j in range(i+1, N+1): for p in range(M+1): memo[i][j][p][L+1] = 0 for c in range(L+2): memo[i][j][M][c] = (i+1 == j) def dfs(l, r, p, c): if memo[l][r][p][c] != -1: return memo[l][r][p][c] res = dfs(l, r, p, c+1) for i in range(l+1, r+1): if (S[i-1][p] != ca + c - 1) if S[i-1][p] != cq else (c == 0): break res += dfs(l, i, p+1, 0) * dfs(i, r, p, c+1) % MOD memo[l][r][p][c] = res = res % MOD return res write("%d\n" % dfs(0, N, 0, 0)) solve() ```
84,973
Provide a correct Python 3 solution for this coding contest problem. Example Input 4 Durett 7 Gayles 3 Facenda 6 Daughtery 0 1 + Mccourtney 2 Output Mccourtney is not working now. Durett is working hard now. "Correct Solution: ``` from heapq import heappush, heappop, heapify import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) P = []; Q = [] E = []; R = {} L = N + 20000 for i in range(N): s, a = readline().split(); a = int(a) * L + i E.append(s) Q.append((-a, i)) R[s] = (i, a) heapify(Q) for i in range(N // 5): b, i = heappop(Q) P.append((-b, i)) heapify(P) pn = len(P); qn = len(Q) ln = N cur = N M = int(readline()) for i in range(M): p, *g = readline().split() db = dk = -1 if p == "+": t, b = g; b = int(b) * L + cur E.append(t) R[t] = (cur, b) ln += 1 if ln >= 5 and -Q[0][0] < b: da = 1 pn += 1 heappush(P, (b, cur)) if pn > ln // 5: while 1: c, k = heappop(P) if E[k] is not None: if c == b: da = 0 else: db = 0 dk = k heappush(Q, (-c, k)) break pn -= 1; qn += 1 else: da = 0 qn += 1 heappush(Q, (-b, cur)) if pn < ln // 5: while 1: c, k = heappop(Q) if E[k] is not None: if -b == c: da = 1 else: db = 1 dk = k heappush(P, (-c, k)) break pn += 1; qn -= 1 if da: write("%s is working hard now.\n" % t) else: write("%s is not working now.\n" % t) cur += 1 else: t, = g j, b = R[t] E[j] = None ln -= 1 if P and P[0][0] <= b: pn -= 1 if pn < ln // 5: while 1: c, k = heappop(Q) if E[k] is not None: heappush(P, (-c, k)) db = 1; dk = k break pn += 1; qn -= 1 else: qn -= 1 if pn > ln // 5: while 1: c, k = heappop(P) if E[k] is not None: heappush(Q, (-c, k)) db = 0; dk = k break qn += 1; pn -= 1 if db != -1: if db: write("%s is working hard now.\n" % E[dk]) else: write("%s is not working now.\n" % E[dk]) solve() ```
84,974
Provide a correct Python 3 solution for this coding contest problem. E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to look up the number of "numbers that are neither multiples of 2 nor multiples of 3". However, Nene was tired, so she decided to cheat only for the answer. Based only on the values ​​of $ N, A, B, and C $, you can find the number of "numbers that are neither multiples of 2 nor multiples of 3". Create a program that asks for this. input $ N, A, B, C $ are given separated by blanks. output Output the number of "numbers that are neither multiples of 2 nor multiples of 3" in the data. However, insert a line break at the end. Constraint * $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $ * $ A, B, C $ are integers greater than or equal to $ 0 $ and less than or equal to $ N $ * No inconsistent data is given, such as $ A $ being greater than $ N $ Input example 1 6 3 2 1 Output example 1 2 For example, if your data is $ 2, 3, 4, 5, 6, 7 $, then $ 5 $ and $ 7 $ are "numbers that are neither multiples of 2 nor multiples of 3". Input example 2 10 9 9 9 Output example 2 1 Example Input 6 3 2 1 Output 2 "Correct Solution: ``` N, A, B, C = [int(x) for x in input().split()] ans = N - (A + B) + C print(ans) ```
84,975
Provide a correct Python 3 solution for this coding contest problem. E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to look up the number of "numbers that are neither multiples of 2 nor multiples of 3". However, Nene was tired, so she decided to cheat only for the answer. Based only on the values ​​of $ N, A, B, and C $, you can find the number of "numbers that are neither multiples of 2 nor multiples of 3". Create a program that asks for this. input $ N, A, B, C $ are given separated by blanks. output Output the number of "numbers that are neither multiples of 2 nor multiples of 3" in the data. However, insert a line break at the end. Constraint * $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $ * $ A, B, C $ are integers greater than or equal to $ 0 $ and less than or equal to $ N $ * No inconsistent data is given, such as $ A $ being greater than $ N $ Input example 1 6 3 2 1 Output example 1 2 For example, if your data is $ 2, 3, 4, 5, 6, 7 $, then $ 5 $ and $ 7 $ are "numbers that are neither multiples of 2 nor multiples of 3". Input example 2 10 9 9 9 Output example 2 1 Example Input 6 3 2 1 Output 2 "Correct Solution: ``` N,A,B,C=map(int,input().split()) print(N-A-B+C) ```
84,976
Provide a correct Python 3 solution for this coding contest problem. E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to look up the number of "numbers that are neither multiples of 2 nor multiples of 3". However, Nene was tired, so she decided to cheat only for the answer. Based only on the values ​​of $ N, A, B, and C $, you can find the number of "numbers that are neither multiples of 2 nor multiples of 3". Create a program that asks for this. input $ N, A, B, C $ are given separated by blanks. output Output the number of "numbers that are neither multiples of 2 nor multiples of 3" in the data. However, insert a line break at the end. Constraint * $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $ * $ A, B, C $ are integers greater than or equal to $ 0 $ and less than or equal to $ N $ * No inconsistent data is given, such as $ A $ being greater than $ N $ Input example 1 6 3 2 1 Output example 1 2 For example, if your data is $ 2, 3, 4, 5, 6, 7 $, then $ 5 $ and $ 7 $ are "numbers that are neither multiples of 2 nor multiples of 3". Input example 2 10 9 9 9 Output example 2 1 Example Input 6 3 2 1 Output 2 "Correct Solution: ``` n,a,b,c = map(int,input().split()) print(n - (a+b-c)) ```
84,977
Provide a correct Python 3 solution for this coding contest problem. E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to look up the number of "numbers that are neither multiples of 2 nor multiples of 3". However, Nene was tired, so she decided to cheat only for the answer. Based only on the values ​​of $ N, A, B, and C $, you can find the number of "numbers that are neither multiples of 2 nor multiples of 3". Create a program that asks for this. input $ N, A, B, C $ are given separated by blanks. output Output the number of "numbers that are neither multiples of 2 nor multiples of 3" in the data. However, insert a line break at the end. Constraint * $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $ * $ A, B, C $ are integers greater than or equal to $ 0 $ and less than or equal to $ N $ * No inconsistent data is given, such as $ A $ being greater than $ N $ Input example 1 6 3 2 1 Output example 1 2 For example, if your data is $ 2, 3, 4, 5, 6, 7 $, then $ 5 $ and $ 7 $ are "numbers that are neither multiples of 2 nor multiples of 3". Input example 2 10 9 9 9 Output example 2 1 Example Input 6 3 2 1 Output 2 "Correct Solution: ``` n, a, b, c = map(int, input().split()) print(n-(c+a-c+b-c)) ```
84,978
Provide a correct Python 3 solution for this coding contest problem. E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to look up the number of "numbers that are neither multiples of 2 nor multiples of 3". However, Nene was tired, so she decided to cheat only for the answer. Based only on the values ​​of $ N, A, B, and C $, you can find the number of "numbers that are neither multiples of 2 nor multiples of 3". Create a program that asks for this. input $ N, A, B, C $ are given separated by blanks. output Output the number of "numbers that are neither multiples of 2 nor multiples of 3" in the data. However, insert a line break at the end. Constraint * $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $ * $ A, B, C $ are integers greater than or equal to $ 0 $ and less than or equal to $ N $ * No inconsistent data is given, such as $ A $ being greater than $ N $ Input example 1 6 3 2 1 Output example 1 2 For example, if your data is $ 2, 3, 4, 5, 6, 7 $, then $ 5 $ and $ 7 $ are "numbers that are neither multiples of 2 nor multiples of 3". Input example 2 10 9 9 9 Output example 2 1 Example Input 6 3 2 1 Output 2 "Correct Solution: ``` n,a,b,c=map(int,input().split()) print((n+c)-(a+b)) ```
84,979
Provide a correct Python 3 solution for this coding contest problem. E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to look up the number of "numbers that are neither multiples of 2 nor multiples of 3". However, Nene was tired, so she decided to cheat only for the answer. Based only on the values ​​of $ N, A, B, and C $, you can find the number of "numbers that are neither multiples of 2 nor multiples of 3". Create a program that asks for this. input $ N, A, B, C $ are given separated by blanks. output Output the number of "numbers that are neither multiples of 2 nor multiples of 3" in the data. However, insert a line break at the end. Constraint * $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $ * $ A, B, C $ are integers greater than or equal to $ 0 $ and less than or equal to $ N $ * No inconsistent data is given, such as $ A $ being greater than $ N $ Input example 1 6 3 2 1 Output example 1 2 For example, if your data is $ 2, 3, 4, 5, 6, 7 $, then $ 5 $ and $ 7 $ are "numbers that are neither multiples of 2 nor multiples of 3". Input example 2 10 9 9 9 Output example 2 1 Example Input 6 3 2 1 Output 2 "Correct Solution: ``` n, a, b, c = map(int, input().split()) print(n-a-b+c) ```
84,980
Provide a correct Python 3 solution for this coding contest problem. E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to look up the number of "numbers that are neither multiples of 2 nor multiples of 3". However, Nene was tired, so she decided to cheat only for the answer. Based only on the values ​​of $ N, A, B, and C $, you can find the number of "numbers that are neither multiples of 2 nor multiples of 3". Create a program that asks for this. input $ N, A, B, C $ are given separated by blanks. output Output the number of "numbers that are neither multiples of 2 nor multiples of 3" in the data. However, insert a line break at the end. Constraint * $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $ * $ A, B, C $ are integers greater than or equal to $ 0 $ and less than or equal to $ N $ * No inconsistent data is given, such as $ A $ being greater than $ N $ Input example 1 6 3 2 1 Output example 1 2 For example, if your data is $ 2, 3, 4, 5, 6, 7 $, then $ 5 $ and $ 7 $ are "numbers that are neither multiples of 2 nor multiples of 3". Input example 2 10 9 9 9 Output example 2 1 Example Input 6 3 2 1 Output 2 "Correct Solution: ``` n,a,b,c=map(int,input().split());print(n-a-b+c) ```
84,981
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 "Correct Solution: ``` def cross(a: complex, b: complex) -> float: return a.real * b.imag - a.imag * b.real def cross_point(c: complex, d: complex) -> complex: global lt, lv vec = d - c v1 = cross(lv, vec) v2 = cross(lv, lt - c) return c + v2 / v1 * vec if __name__ == "__main__": n = int(input()) points = [complex(*map(int, input().split())) for _ in range(n)] point0 = points.pop(0) points.append(point0) q = int(input()) while q: x1, y1, x2, y2 = map(int, input().split()) ls, lt = (x1 + 1j * y1, x2 + 1j * y2) lv = lt - ls area = 0.0 prev = point0 prev_flag = 0 <= cross(lv, prev - ls) cp1, cp2 = None, None for p in points: curr_flag = 0 <= cross(lv, p - ls) if prev_flag and curr_flag: area += cross(prev, p) elif prev_flag != curr_flag: cp = cross_point(prev, p) if prev_flag: area += cross(prev, cp) cp1 = cp else: area += cross(cp, p) cp2 = cp prev, prev_flag = p, curr_flag if cp1 is not None and cp2 is not None: area += cross(cp1, cp2) print(area / 2) q -= 1 ```
84,982
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 "Correct Solution: ``` import sys readline = sys.stdin.readline write = sys.stdout.write def cross3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (by - oy) - (bx - ox) * (ay - oy) def cross_point(p0, p1, q0, q1): x0, y0 = p0; x1, y1 = p1 x2, y2 = q0; x3, y3 = q1 dx0 = x1 - x0; dy0 = y1 - y0 dx1 = x3 - x2; dy1 = y3 - y2 s = (y0-y2)*dx1 - (x0-x2)*dy1 sm = dx0*dy1 - dy0*dx1 if -EPS < sm < EPS: return None return x0 + s*dx0/sm, y0 + s*dy0/sm EPS = 1e-9 def convex_cut(P, line): q0, q1 = line N = len(P) Q = [] for i in range(N): p0 = P[i-1]; p1 = P[i] cv0 = cross3(q0, q1, p0) cv1 = cross3(q0, q1, p1) if cv0 * cv1 < EPS: v = cross_point(q0, q1, p0, p1) if v is not None: Q.append(v) if cv1 > -EPS: Q.append(p1) return Q def polygon_area(P): s = 0 N = len(P) for i in range(N): p0 = P[i-1]; p1 = P[i] s += p0[0]*p1[1] - p0[1]*p1[0] return abs(s) / 2 def solve(): N = int(readline()) P = [list(map(int, readline().split())) for i in range(N)] Q = int(readline()) for i in range(Q): x0, y0, x1, y1 = map(int, readline().split()) P0 = convex_cut(P, ((x0, y0), (x1, y1))) write("%.16f\n" % polygon_area(P0)) solve() ```
84,983
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 "Correct Solution: ``` import cmath EPS = 1e-6 #外積 def OuterProduct(one, two): tmp = one.conjugate() * two return tmp.imag #点が直線上にあるか def IsOnLine(point, begin, end): return abs(OuterProduct(begin-point, end-point)) <= EPS #3点が反時計回りか #一直線上のときの例外処理できていない→F def CCW(p, q, r): one, two = q-p, r-q if OuterProduct(one, two) > EPS: return True else: return False def Crosspoint(a, b, c, d): if abs(OuterProduct(b-a, d-c)) <= EPS: return False else: u = OuterProduct(c-a, d-a) / OuterProduct(b-a, d-c) return (1-u)*a + u*b #凹多角形の面積(多角形は反時計回りに与えられる) def Area(dots): res = 0 for i in range(len(dots)-1): res += OuterProduct(dots[i], dots[i+1]) res += OuterProduct(dots[-1], dots[0]) return res/2 n = int(input()) dots = [] for _ in range(n): x, y = map(float, input().split()) dots.append(complex(x, y)) q = int(input()) for _ in range(q): x, y, z, w = map(int, input().split()) p1, p2 = complex(x, y), complex(z, w) res = [] for i in range(-1, n-1): if IsOnLine(dots[i], p1, p2) or CCW(p1, p2, dots[i]): res.append(dots[i]) if not IsOnLine(dots[i], p1, p2) and not IsOnLine(dots[i+1], p1, p2) and (CCW(p1, p2, dots[i]) != CCW(p1, p2, dots[i+1])): res.append(Crosspoint(dots[i], dots[i+1], p1, p2)) if not res: print(0) else: print(Area(res)) ```
84,984
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 "Correct Solution: ``` #!/usr/bin/env python3 # CGL_4_C: Convex Polygon Convex Cut def cut(ps, p0, p1): polygon = [] for p2, p3 in zip(ps, ps[1:] + [ps[0]]): if cross(p0, p1, p0, p2) >= 0: polygon.append(p2) if intersect(p0, p1, p2, p3): p = intersect_point(p0, p1, p2, p3) if not same(p, p2): polygon.append(p) return polygon def intersect(p0, p1, p2, p3): if cross(p0, p1, p0, p2) >= 0 and cross(p0, p1, p0, p3) < 0: return True elif cross(p0, p1, p0, p2) <= 0 and cross(p0, p1, p0, p3) > 0: return True return False def same(p0, p1): x0, y0 = p0 x1, y1 = p1 return abs(x0 - x1) < 1e-10 and abs(y0 - y1) < 1e-10 def intersect_point(p0, p1, p2, p3): d1 = abs(cross(p0, p1, p0, p2)) d2 = abs(cross(p0, p1, p0, p3)) t = d1 / (d1 + d2) x2, y2 = p2 x3, y3 = p3 return x2 + (x3 - x2) * t, y2 + (y3 - y2) * t def area(ps): """Calculate area of a polygon. >>> area([(0, 0), (2, 2), (-1, 1)]) 2.0 >>> area([]) 0.0 >>> area([(0, 0)]) 0.0 >>> area([(0, 0), (1, 0)]) 0.0 """ area = 0.0 if ps: for p0, p1 in zip(ps, ps[1:]+[ps[0]]): area += cross((0, 0), p0, p0, p1) return area / 2 def cross(p0, p1, p2, p3): x0, y0 = p0 x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 return (x1-x0)*(y3-y2) - (x3-x2)*(y1-y0) def run(): n = int(input()) ps = [] for _ in range(n): x, y = [int(i) for i in input().split()] ps.append((x, y)) q = int(input()) for _ in range(q): x1, y1, x2, y2 = [int(i) for i in input().split()] print("{:.10f}".format(area(cut(ps, (x1, y1), (x2, y2))))) if __name__ == '__main__': run() ```
84,985
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 "Correct Solution: ``` from sys import stdin readline = stdin.readline class vector: def cross(a, b): return a.real * b.imag - a.imag * b.real def dot(a, b): return a.real * b.real + a.imag * b.imag def ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return 1 if vector.cross(b, c) < 0: return 2 if vector.dot(b, c) < 0: return 3 if abs(b) < abs(c): return 4 return 5 def polygon(p): if len(p) < 3: return 0 return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 if s1 + s2 == 0: return 0 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(float, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(float, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (1, 2) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != 2: left.append(p[i]) pre_tmp = tmp print('{:.6f}'.format(vector.polygon(left))) main() ```
84,986
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 "Correct Solution: ``` def cross(a, b): return a.real * b.imag - a.imag * b.real def cross_point(c, d): l = d - c v1 = cross(lv, l) v2 = cross(lv, lt - c) return c + v2 / v1 * l n = int(input()) points = [complex(*map(int, input().split())) for _ in range(n)] point0 = points.pop(0) points.append(point0) q = int(input()) while q: x1, y1, x2, y2 = map(int, input().split()) ls, lt = (x1 + 1j * y1, x2 + 1j * y2) lv = lt - ls area = 0 prev = point0 prev_flag = cross(lv, prev - ls) >= 0 cp1, cp2 = None, None for p in points: curr_flag = cross(lv, p - ls) >= 0 if prev_flag and curr_flag: area += cross(prev, p) elif prev_flag != curr_flag: cp = cross_point(prev, p) if prev_flag: area += cross(prev, cp) cp1 = cp else: area += cross(cp, p) cp2 = cp prev, prev_flag = p, curr_flag if cp1 is not None and cp2 is not None: area += cross(cp1, cp2) print(area / 2) q -= 1 ```
84,987
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 "Correct Solution: ``` # cross point def cross(c1, c2): return c1.real * c2.imag - c1.imag * c2.real def cross_point(p1, p2, p3, p4): # p1 and p2 are points on a segment. # p3 and p4 are points on the other segment. base = p4 - p3 hypo1 = p1 - p3 hypo2 = p2 - p3 d1 = cross(base, hypo1) / abs(base) d2 = cross(base, hypo2) / abs(base) cp = p1 + d1 / (d1 - d2) * (p2 - p1) return cp # area of a triangle def _area_of_triangle(c1, c2, c3): v1 = c2 - c1 v2 = c3 - c1 return abs(v1.real * v2.imag - v1.imag * v2.real) / 2 # convex cut def convex_cut(points, c1, c2): points.append(points[0]) ref_vec = c2 - c1 cross_point1 = None flag = 0 # Detection of one intersection point for i, segment in enumerate(zip(points, points[1:])): p1, p2 = segment cross1 = cross(ref_vec, p1 - c1) cross2 = cross(ref_vec, p2 - c1) flag += cross1 if cross1 <= 0 and cross2 > 0: cross_point1 = cross_point(c1, c2, p1, p2) points = points[i+1:] break elif cross1 > 0 and cross2 <= 0: cross_point1 = cross_point(c1, c2, p1, p2) points = points[i::-1] + points[:i:-1] break # Processing when there is no intersection point if cross_point1 == None: if flag > 0: cross_point1 = points[0] points = points[1:] else: return 0 # find area cut_area = 0 for p1, p2 in zip(points, points[1:]): if cross(ref_vec, p1 - c1) * cross(ref_vec, p2 - c1) <= 0: cross_point2 = cross_point(c1, c2, p1, p2) cut_area += _area_of_triangle(cross_point1, cross_point2, p1) break else: cut_area += _area_of_triangle(cross_point1, p1, p2) return cut_area # acceptance of input import sys file_input = sys.stdin n = int(file_input.readline()) def string_to_complex(s): x, y = map(float, s.split()) return x + y * 1j G = [string_to_complex(file_input.readline()) for i in range(n)] # output q = int(file_input.readline()) for line in file_input: p1x, p1y, p2x, p2y = map(int, line.split()) p1 = p1x + p1y * 1j p2 = p2x + p2y * 1j ans = convex_cut(G.copy(), p1, p2) print("{:f}".format(ans)) ```
84,988
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 "Correct Solution: ``` from sys import stdin readline = stdin.readline class vector: def cross(a, b): return a.real * b.imag - a.imag * b.real def dot(a, b): return a.real * b.real + a.imag * b.imag def ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return 1 if vector.cross(b, c) < 0: return 2 if vector.dot(b, c) < 0: return 3 if abs(b) < abs(c): return 4 return 5 def polygon(p): if len(p) < 3: return 0 return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 if s1 + s2 == 0: return 0 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(float, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(float, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (1, 2) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != 2: left.append(p[i]) pre_tmp = tmp print('{:.6f}'.format(vector.polygon(left))) import sys if sys.hexversion >= 0x030203F0: main() else: print('Error') ```
84,989
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` #!/usr/bin/python3 import array from fractions import Fraction import functools import itertools import math import os import sys def main(): N = read_int() P = [Vec(*read_ints()) for _ in range(N)] Q = read_int() for _ in range(Q): x1, y1, x2, y2 = read_ints() print(solve(N, P, Vec(x1, y1), Vec(x2, y2))) def solve(N, P, A, B): b = B - A P = [p - A for p in P] ccw = 0 cw = 0 for p in P: c = b.cross(p) if c >= 0: ccw += 1 if c <= 0: cw += 1 if ccw == N: return float(poly_area(P)) if cw == N: return 0 cross_points = [] for i in range(N): j = (i + 1) % N p = P[i] q = P[j] qp = q - p cross_qp_b = qp.cross(b) if cross_qp_b == 0: continue k = Fraction(b.cross(p), cross_qp_b) if 0 < k <= 1: t = Fraction(p.cross(qp), b.cross(qp)) cross_points.append((t, i, k)) cross_points.sort() _, i1, k1 = cross_points[0] _, i2, k2 = cross_points[1] x1 = P[i1] + k1 * (P[(i1 + 1) % N] - P[i1]) x2 = P[i2] + k2 * (P[(i2 + 1) % N] - P[i2]) Q = [x2] j = (i2 + 1) % N while j != i1: Q.append(P[j]) j = (j + 1) % N Q.append(P[i1]) Q.append(x1) return float(poly_area(Q)) def poly_area(P): N = len(P) a = 0 for i in range(1, N - 1): a += Fraction((P[i + 1] - P[i]).cross(P[0] - P[i + 1]), 2) return a ############################################################################### # AUXILIARY FUNCTIONS class Vec(object): def __init__(self, x, y): self.x = x self.y = y super().__init__() def __add__(self, other): return Vec(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vec(self.x - other.x, self.y - other.y) def __mul__(self, scalar): return Vec(self.x * scalar, self.y * scalar) def __rmul__(self, scalar): return Vec(self.x * scalar, self.y * scalar) def __truediv__(self, scalar): return Vec(self.x / scalar, self.y / scalar) def __iadd__(self, other): self.x += other.x self.y += other.y return self def __isub__(self, other): self.x -= other.x self.y -= other.y return self def __imul__(self, scalar): self.x *= scalar self.y *= scalar return self def __idiv__(self, scalar): self.x /= scalar self.y /= scalar return self def __neg__(self): return Vec(-self.x, -self.y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash('Vec', self.x, self.y) def dot(self, other): return self.x * other.x + self.y * other.y def cross(self, other): return self.x * other.y - self.y * other.x def abs2(self): return self.x * self.x + self.y * self.y def __abs__(self): return math.sqrt(float(self.abs2())) def __repr__(self): return '({}, {})'.format(self.x, self.y) DEBUG = 'DEBUG' in os.environ def inp(): return sys.stdin.readline().rstrip() def read_int(): return int(inp()) def read_ints(): return [int(e) for e in inp().split()] def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) if __name__ == '__main__': main() ``` Yes
84,990
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` import cmath import math import os import sys if os.getenv("LOCAL"): sys.stdin = open("_in.txt", "r") sys.setrecursionlimit(10 ** 9) INF = float("inf") IINF = 10 ** 18 MOD = 10 ** 9 + 7 # MOD = 998244353 PI = cmath.pi TAU = cmath.pi * 2 EPS = 1e-10 class Point: """ 2次元空間上の点 """ # 反時計回り側にある CCW_COUNTER_CLOCKWISE = 1 # 時計回り側にある CCW_CLOCKWISE = -1 # 線分の後ろにある CCW_ONLINE_BACK = 2 # 線分の前にある CCW_ONLINE_FRONT = -2 # 線分上にある CCW_ON_SEGMENT = 0 def __init__(self, c: complex): self.c = c @property def x(self): return self.c.real @property def y(self): return self.c.imag @staticmethod def from_rect(x: float, y: float): return Point(complex(x, y)) @staticmethod def from_polar(r: float, phi: float): return Point(cmath.rect(r, phi)) def __add__(self, p): """ :param Point p: """ return Point(self.c + p.c) def __iadd__(self, p): """ :param Point p: """ self.c += p.c return self def __sub__(self, p): """ :param Point p: """ return Point(self.c - p.c) def __isub__(self, p): """ :param Point p: """ self.c -= p.c return self def __mul__(self, f: float): return Point(self.c * f) def __imul__(self, f: float): self.c *= f return self def __truediv__(self, f: float): return Point(self.c / f) def __itruediv__(self, f: float): self.c /= f return self def __repr__(self): return "({}, {})".format(round(self.x, 10), round(self.y, 10)) def __neg__(self): return Point(-self.c) def __eq__(self, p): return abs(self.c - p.c) < EPS def __abs__(self): return abs(self.c) @staticmethod def ccw(a, b, c): """ 線分 ab に対する c の位置 線分上にあるか判定するだけなら on_segment とかのが速い Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja :param Point a: :param Point b: :param Point c: """ b = b - a c = c - a det = b.det(c) if det > EPS: return Point.CCW_COUNTER_CLOCKWISE if det < -EPS: return Point.CCW_CLOCKWISE if b.dot(c) < -EPS: return Point.CCW_ONLINE_BACK if c.norm() - b.norm() > EPS: return Point.CCW_ONLINE_FRONT return Point.CCW_ON_SEGMENT def dot(self, p): """ 内積 :param Point p: :rtype: float """ return self.x * p.x + self.y * p.y def det(self, p): """ 外積 :param Point p: :rtype: float """ return self.x * p.y - self.y * p.x def dist(self, p): """ 距離 :param Point p: :rtype: float """ return abs(self.c - p.c) def norm(self): """ 原点からの距離 :rtype: float """ return abs(self.c) def phase(self): """ 原点からの角度 :rtype: float """ return cmath.phase(self.c) def angle(self, p, q): """ p に向いてる状態から q まで反時計回りに回転するときの角度 -pi <= ret <= pi :param Point p: :param Point q: :rtype: float """ return (cmath.phase(q.c - self.c) - cmath.phase(p.c - self.c) + PI) % TAU - PI def area(self, p, q): """ p, q となす三角形の面積 :param Point p: :param Point q: :rtype: float """ return abs((p - self).det(q - self) / 2) def projection_point(self, p, q, allow_outer=False): """ 線分 pq を通る直線上に垂線をおろしたときの足の座標 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A&lang=ja :param Point p: :param Point q: :param allow_outer: 答えが線分の間になくても OK :rtype: Point|None """ diff_q = q - p # 答えの p からの距離 r = (self - p).dot(diff_q) / abs(diff_q) # 線分の角度 phase = diff_q.phase() ret = Point.from_polar(r, phase) + p if allow_outer or (p - ret).dot(q - ret) < EPS: return ret return None def reflection_point(self, p, q): """ 直線 pq を挟んで反対にある点 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B&lang=ja :param Point p: :param Point q: :rtype: Point """ # 距離 r = abs(self - p) # pq と p-self の角度 angle = p.angle(q, self) # 直線を挟んで角度を反対にする angle = (q - p).phase() - angle return Point.from_polar(r, angle) + p def on_segment(self, p, q, allow_side=True): """ 点が線分 pq の上に乗っているか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja :param Point p: :param Point q: :param allow_side: 端っこでギリギリ触れているのを許容するか :rtype: bool """ if not allow_side and (self == p or self == q): return False # 外積がゼロ: 面積がゼロ == 一直線 # 内積がマイナス: p - self - q の順に並んでる return abs((p - self).det(q - self)) < EPS and (p - self).dot(q - self) < EPS class Line: """ 2次元空間上の直線 """ def __init__(self, a: float, b: float, c: float): """ 直線 ax + by + c = 0 """ self.a = a self.b = b self.c = c @staticmethod def from_gradient(grad: float, intercept: float): """ 直線 y = ax + b :param grad: 傾き :param intercept: 切片 :return: """ return Line(grad, -1, intercept) @staticmethod def from_segment(p1, p2): """ :param Point p1: :param Point p2: """ a = p2.y - p1.y b = p1.x - p2.x c = p2.y * (p2.x - p1.x) - p2.x * (p2.y - p1.y) return Line(a, b, c) @property def gradient(self): """ 傾き """ return INF if self.b == 0 else -self.a / self.b @property def intercept(self): """ 切片 """ return INF if self.b == 0 else -self.c / self.b def is_parallel_to(self, l): """ 平行かどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja :param Line l: """ # 法線ベクトル同士の外積がゼロ return abs(Point.from_rect(self.a, self.b).det(Point.from_rect(l.a, l.b))) < EPS def is_orthogonal_to(self, l): """ 直行しているかどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja :param Line l: """ # 法線ベクトル同士の内積がゼロ return abs(Point.from_rect(self.a, self.b).dot(Point.from_rect(l.a, l.b))) < EPS def intersection_point(self, l): """ 交差する点 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C&lang=ja :param Line l: :rtype: Point|None """ a1, b1, c1 = self.a, self.b, self.c a2, b2, c2 = l.a, l.b, l.c det = a1 * b2 - a2 * b1 if abs(det) < EPS: # 並行 return None x = (b1 * c2 - b2 * c1) / det y = (a2 * c1 - a1 * c2) / det return Point.from_rect(x, y) def dist(self, p): """ 他の点との最短距離 :param Point p: """ raise NotImplementedError() def has_point(self, p): """ p が直線上に乗っているかどうか :param Point p: """ return abs(self.a * p.x + self.b * p.y + self.c) < EPS class Segment: """ 2次元空間上の線分 """ def __init__(self, p1, p2): """ :param Point p1: :param Point p2: """ self.p1 = p1 self.p2 = p2 def norm(self): """ 線分の長さ """ return abs(self.p1 - self.p2) def phase(self): """ p1 を原点としたときの p2 の角度 """ return cmath.phase(self.p2 - self.p1) def is_parallel_to(self, s): """ 平行かどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja :param Segment s: :return: """ # 外積がゼロ return abs((self.p1 - self.p2).det(s.p1 - s.p2)) < EPS def is_orthogonal_to(self, s): """ 直行しているかどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja :param Segment s: :return: """ # 内積がゼロ return abs((self.p1 - self.p2).dot(s.p1 - s.p2)) < EPS def intersects_with(self, s, allow_side=True): """ 交差するかどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B&lang=ja :param Segment s: :param allow_side: 端っこでギリギリ触れているのを許容するか """ if self.is_parallel_to(s): # 並行なら線分の端点がもう片方の線分の上にあるかどうか return (s.p1.on_segment(self.p1, self.p2, allow_side) or s.p2.on_segment(self.p1, self.p2, allow_side) or self.p1.on_segment(s.p1, s.p2, allow_side) or self.p2.on_segment(s.p1, s.p2, allow_side)) else: # allow_side ならゼロを許容する det_lower = EPS if allow_side else -EPS ok = True # self の両側に s.p1 と s.p2 があるか ok &= (self.p2 - self.p1).det(s.p1 - self.p1) * (self.p2 - self.p1).det(s.p2 - self.p1) < det_lower # s の両側に self.p1 と self.p2 があるか ok &= (s.p2 - s.p1).det(self.p1 - s.p1) * (s.p2 - s.p1).det(self.p2 - s.p1) < det_lower return ok def closest_point(self, p): """ 線分上の、p に最も近い点 :param Point p: """ # p からおろした垂線までの距離 d = (p - self.p1).dot(self.p2 - self.p1) / self.norm() # p1 より前 if d < EPS: return self.p1 # p2 より後 if -EPS < d - self.norm(): return self.p2 # 線分上 return Point.from_polar(d, (self.p2 - self.p1).phase()) + self.p1 def dist(self, p): """ 他の点との最短距離 :param Point p: """ return abs(p - self.closest_point(p)) def dist_segment(self, s): """ 他の線分との最短距離 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D&lang=ja :param Segment s: """ if self.intersects_with(s): return 0.0 return min( self.dist(s.p1), self.dist(s.p2), s.dist(self.p1), s.dist(self.p2), ) def has_point(self, p, allow_side=True): """ p が線分上に乗っているかどうか :param Point p: :param allow_side: 端っこでギリギリ触れているのを許容するか """ return p.on_segment(self.p1, self.p2, allow_side=allow_side) class Polygon: """ 2次元空間上の多角形 """ def __init__(self, points): """ :param list of Point points: """ self.points = points def iter2(self): """ 隣り合う2点を順に返すイテレータ :rtype: typing.Iterator[(Point, Point)] """ return zip(self.points, self.points[1:] + self.points[:1]) def iter3(self): """ 隣り合う3点を順に返すイテレータ :rtype: typing.Iterator[(Point, Point, Point)] """ return zip(self.points, self.points[1:] + self.points[:1], self.points[2:] + self.points[:2]) def area(self): """ 面積 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A&lang=ja """ # 外積の和 / 2 dets = [] for p, q in self.iter2(): dets.append(p.det(q)) return abs(math.fsum(dets)) / 2 def is_convex(self, allow_straight=False, allow_collapsed=False): """ 凸多角形かどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B&lang=ja :param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか :param allow_collapsed: 面積がゼロの場合を許容するか """ ccw = [] for a, b, c in self.iter3(): ccw.append(Point.ccw(a, b, c)) ccw = set(ccw) if len(ccw) == 1: if ccw == {Point.CCW_CLOCKWISE}: return True if ccw == {Point.CCW_COUNTER_CLOCKWISE}: return True if allow_straight and len(ccw) == 2: if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_CLOCKWISE}: return True if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_COUNTER_CLOCKWISE}: return True if allow_collapsed and len(ccw) == 3: return ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_ONLINE_BACK, Point.CCW_ON_SEGMENT} return False def has_point_on_edge(self, p): """ 指定した点が辺上にあるか :param Point p: :rtype: bool """ for a, b in self.iter2(): if p.on_segment(a, b): return True return False def contains(self, p, allow_on_edge=True): """ 指定した点を含むか Winding Number Algorithm https://www.nttpc.co.jp/technology/number_algorithm.html Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C&lang=ja :param Point p: :param bool allow_on_edge: 辺上の点を許容するか """ angles = [] for a, b in self.iter2(): if p.on_segment(a, b): return allow_on_edge angles.append(p.angle(a, b)) # 一周以上するなら含む return abs(math.fsum(angles)) > EPS @staticmethod def convex_hull(points, allow_straight=False): """ 凸包。x が最も小さい点のうち y が最も小さい点から反時計回り。 Graham Scan O(N log N) Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A&lang=ja :param list of Point points: :param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか :rtype: list of Point """ points = points[:] points.sort(key=lambda p: (p.x, p.y)) # allow_straight なら 0 を許容する det_lower = -EPS if allow_straight else EPS sz = 0 #: :type: list of (Point|None) ret = [None] * (N * 2) for p in points: while sz > 1 and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower: sz -= 1 ret[sz] = p sz += 1 floor = sz for p in reversed(points[:-1]): while sz > floor and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower: sz -= 1 ret[sz] = p sz += 1 ret = ret[:sz - 1] if allow_straight and len(ret) > len(points): # allow_straight かつ全部一直線のときに二重にカウントしちゃう ret = points return ret @staticmethod def diameter(points): """ 直径 凸包構築 O(N log N) + カリパー法 O(N) Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B&lang=ja :param list of Point points: """ # 反時計回り points = Polygon.convex_hull(points, allow_straight=False) if len(points) == 1: return 0.0 if len(points) == 2: return abs(points[0] - points[1]) # x軸方向に最も遠い点対 si = points.index(min(points, key=lambda p: (p.x, p.y))) sj = points.index(max(points, key=lambda p: (p.x, p.y))) n = len(points) ret = 0.0 # 半周回転 i, j = si, sj while i != sj or j != si: ret = max(ret, abs(points[i] - points[j])) ni = (i + 1) % n nj = (j + 1) % n # 2つの辺が並行になる方向にずらす if (points[ni] - points[i]).det(points[nj] - points[j]) > 0: j = nj else: i = ni return ret def convex_cut_by_line(self, line_p1, line_p2): """ 凸多角形を直線 line_p1-line_p2 でカットする。 凸じゃないといけません Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C&lang=ja :param line_p1: :param line_p2: :return: (line_p1-line_p2 の左側の多角形, line_p1-line_p2 の右側の多角形) :rtype: (Polygon|None, Polygon|None) """ n = len(self.points) line = Line.from_segment(line_p1, line_p2) # 直線と重なる点 on_line_points = [] for i, p in enumerate(self.points): if line.has_point(p): on_line_points.append(i) # 辺が直線上にある has_on_line_edge = False if len(on_line_points) >= 3: has_on_line_edge = True elif len(on_line_points) == 2: # 直線上にある点が隣り合ってる has_on_line_edge = abs(on_line_points[0] - on_line_points[1]) in [1, n - 1] # 辺が直線上にある場合、どっちか片方に全部ある if has_on_line_edge: for p in self.points: ccw = Point.ccw(line_p1, line_p2, p) if ccw == Point.CCW_COUNTER_CLOCKWISE: return Polygon(self.points[:]), None if ccw == Point.CCW_CLOCKWISE: return None, Polygon(self.points[:]) ret_lefts = [] ret_rights = [] d = line_p2 - line_p1 for p, q in self.iter2(): det_p = d.det(p - line_p1) det_q = d.det(q - line_p1) if det_p > -EPS: ret_lefts.append(p) if det_p < EPS: ret_rights.append(p) # 外積の符号が違う == 直線の反対側にある場合は交点を追加 if det_p * det_q < -EPS: intersection = line.intersection_point(Line.from_segment(p, q)) ret_lefts.append(intersection) ret_rights.append(intersection) # 点のみの場合を除いて返す l = Polygon(ret_lefts) if len(ret_lefts) > 1 else None r = Polygon(ret_rights) if len(ret_rights) > 1 else None return l, r N = int(sys.stdin.buffer.readline()) XY = [list(map(float, sys.stdin.buffer.readline().split())) for _ in range(N)] points = [] for x, y in XY: points.append(Point(complex(x, y))) polygon = Polygon(points) Q = int(sys.stdin.buffer.readline()) POINTS = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)] for x1, y1, x2, y2 in POINTS: l, r = polygon.convex_cut_by_line(Point.from_rect(x1, y1), Point.from_rect(x2, y2)) if l: print(l.area()) else: print(0) ``` Yes
84,991
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` from sys import stdin readline = stdin.readline from enum import Enum direction = Enum('direction', 'CCW CW CAB ABC ACB') class vector: def cross(a, b): return a.real * b.imag - a.imag * b.real def dot(a, b): return a.real * b.real + a.imag * b.imag def ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return direction.CCW if vector.cross(b, c) < 0: return direction.CW if vector.dot(b, c) < 0: return direction.CAB if abs(b) < abs(c): return direction.ABC return direction.ACB def polygon(p): if len(p) < 3: return 0 return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 if s1 + s2 == 0: return 0 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(float, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(float, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (direction.CW, direction.CCW) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != direction.CW: left.append(p[i]) pre_tmp = tmp print('{:.6f}'.format(vector.polygon(left))) main() ``` No
84,992
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` # cross point def cross(c1, c2): return c1.real * c2.imag - c1.imag * c2.real def cross_point(p1, p2, p3, p4): # p1 and p2 are points on a segment. # p3 and p4 are points on the other segment. base = p4 - p3 hypo1 = p1 - p3 hypo2 = p2 - p3 d1 = cross(base, hypo1) / abs(base) d2 = cross(base, hypo2) / abs(base) cp = p1 + d1 / (d1 - d2) * (p2 - p1) return cp # area of a triangle def _area_of_triangle(c1, c2, c3): v1 = c2 - c1 v2 = c3 - c1 return abs(v1.real * v2.imag - v1.imag * v2.real) / 2 # convex cut def convex_cut(points, c1, c2): points.append(points[0]) ref_vec = c2 - c1 for i, segment in enumerate(zip(points, points[1:])): p1, p2 = segment cross1 = cross(ref_vec, p1 - c1) cross2 = cross(ref_vec, p2 - c1) if cross1 <= 0 and cross2 > 0: cross_point1 = cross_point(c1, c2, p1, p2) points = points[i+1:] break elif cross1 > 0 and cross2 <= 0: cross_point1 = cross_point(c1, c2, p1, p2) points = points[i::-1] + points[:i:-1] break cut_area = 0 for p1, p2 in zip(points, points[1:]): if cross(ref_vec, p1 - c1) * cross(ref_vec, p2 - c1) <= 0: cross_point2 = cross_point(c1, c2, p1, p2) cut_area += _area_of_triangle(cross_point1, cross_point2, p1) break else: cut_area += _area_of_triangle(cross_point1, p1, p2) return cut_area # acceptance of input import sys file_input = sys.stdin n = int(file_input.readline()) def string_to_complex(s): x, y = map(float, s.split()) return x + y * 1j G = [string_to_complex(file_input.readline()) for i in range(n)] # output q = int(file_input.readline()) for line in file_input: p1x, p1y, p2x, p2y = map(int, line.split()) p1 = p1x + p1y * 1j p2 = p2x + p2y * 1j ans = convex_cut(G.copy(), p1, p2) print("{:f}".format(ans)) ``` No
84,993
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` from sys import stdin readline = stdin.readline from enum import Enum direction = Enum('direction', 'CCW CW CAB ABC ACB') class vector: def cross(a, b): return a.real * b.imag - a.imag * b.real def dot(a, b): return a.real * b.real + a.imag * b.imag def ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return direction.CCW if vector.cross(b, c) < 0: return direction.CW if vector.dot(b, c) < 0: return direction.CAB if vector.abs(b) < abs(c): return direction.ABC return direction.ACB def polygon(p): if len(p) < 3: return 0 return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(float, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(float, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (direction.CW, direction.CCW) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != direction.CW: left.append(p[i]) pre_tmp = tmp print('{:.6f}'.format(vector.polygon(left))) main() ``` No
84,994
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` from sys import stdin readline = stdin.readline from enum import Enum direction = Enum('direction', 'CCW CW CAB ABC ACB') class vector: def cross(a, b): return a.real * b.imag - a.imag * b.real def dot(a, b): return a.real * b.real + a.imag * b.imag def ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return direction.CCW if vector.cross(b, c) < 0: return direction.CW if vector.dot(b, c) < 0: return direction.CAB if vector.abs(b) < abs(c): return direction.ABC return direction.ACB def polygon(p): return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(int, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(int, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (direction.CW, direction.CCW) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != direction.CW: left.append(p[i]) pre_tmp = tmp print(vector.polygon(left)) main() ``` No
84,995
Provide a correct Python 3 solution for this coding contest problem. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 "Correct Solution: ``` from itertools import permutations n = int(input()) arr = tuple(map(int, input().split())) p = list(permutations(sorted(arr))) idx = p.index(arr) for i in range(max(0, idx - 1), min(len(p), idx + 2), 1): print(*p[i]) ```
84,996
Provide a correct Python 3 solution for this coding contest problem. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 "Correct Solution: ``` import heapq from collections import deque from enum import Enum import sys import math from _heapq import heappush, heappop BIG_NUM = 2000000000 MOD = 1000000007 EPS = 0.000000001 N = int(input()) table = [None] * N check = [False] * (N+1) MAP = {} rev_MAP = {} perm_index = 0 def recursive(index): global perm_index if index == N: tmp = 0 for i in range(N): tmp = 10*tmp+table[i] MAP[perm_index] = tmp rev_MAP[tmp] = perm_index perm_index += 1 return for i in range(1,(N+1)): if check[i]: continue check[i] = True table[index] = i recursive(index+1) check[i] = False def outPut(num): S = deque() while True: S.appendleft(num%10) num //= 10 if num == 0: break print("%d"%(S.popleft()),end="") while len(S) > 0: print(" %d"%(S.popleft()),end="") print() recursive(0) tmp = 0 for i in list(map(int,input().split())): tmp = 10*tmp+i index = rev_MAP[tmp] if index > 0: outPut(MAP[index-1]) outPut(tmp) if index+1 in MAP: outPut(MAP[index+1]) ```
84,997
Provide a correct Python 3 solution for this coding contest problem. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 "Correct Solution: ``` import itertools n = int(input()) num = list(map(int, input().split())) per = list(itertools.permutations(num)) per.sort() index = per.index(tuple(num)) if index != 0: print(' '.join(str(n) for n in per[index-1])) print(' '.join(str(n) for n in per[index])) if index != len(per)-1: print(' '.join(str(n) for n in per[index+1])) ```
84,998
Provide a correct Python 3 solution for this coding contest problem. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 "Correct Solution: ``` import itertools if __name__ == '__main__': n = int(input()) now = tuple(map(int,input().split())) seq = [i+1 for i in range(n)] seq2 = list(itertools.permutations(seq)) ind = 0 for j,k in enumerate(seq2): if k == now: ind = j if ind == 0: print(*seq2[ind]) if len(seq2) != 1: print(*seq2[ind+1]) elif ind+1 == len(seq2): print(*seq2[ind-1]) print(*seq2[ind]) else: print(*seq2[ind-1]) print(*seq2[ind]) print(*seq2[ind+1]) ```
84,999