message
stringlengths
2
67k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
463
109k
cluster
float64
19
19
__index_level_0__
int64
926
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m — the number of vertices and the number of edges in the graph (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105). The next n lines contain the information about edges of the graph. i-th line (1 ≤ i ≤ n) contains nonnegative integer ci — number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j — indices of these vertices (1 ≤ ai, j ≤ n, ai, j ≠ i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s — the initial position of the chip (1 ≤ s ≤ n). Output If Petya can win print «Win» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≤ k ≤ 106) — the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print «Draw» in the only line. Otherwise print «Lose». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie. Submitted Solution: ``` import sys from collections import deque g = {} data = sys.stdin.readlines() n, m = map(int, data[0].split()) for i, line in enumerate(data[1:-1], 1): g[i] = list(map(int, line.split()[1:])) cycle = False mk = {} start = int(data[-1]) queue = deque() queue.append((start, 0, 0, -1)) while len(queue) > 0: v, player, dist, prev = queue.popleft() if mk.get((v, player), None): if mk[(v, player)][1] < dist: cycle = True continue mk[(v, player)] = (prev, dist) for w in g[v]: queue.append((w, 1-player, dist+1, v)) sol = 0 for v in range(1, n+1): if len(g[v]) == 0 and mk.get((v, 1), None): sol = v break if sol: path = [sol] cur = (sol, 1) while cur != (start, 0): cur = (mk.get(cur)[0], 1-cur[1]) path.append(cur[0]) print('Win') print(*path[::-1]) elif cycle: print('Draw') else: print('Lose') ```
instruction
0
73,050
19
146,100
No
output
1
73,050
19
146,101
Provide a correct Python 3 solution for this coding contest problem. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996
instruction
0
73,185
19
146,370
"Correct Solution: ``` #####segfunc##### def segfunc(x, y): return min(x,y) ################# #####ide_ele##### ide_ele = float("inf") ################# class SegTree: """ init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN) """ def __init__(self, n, segfunc, ide_ele): """ init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index) """ self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num # 配列の値を葉にセット # 構築していく def update(self, k, x): """ k番目の値をxに更新 k: index(0-index) x: update value """ k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): """ [l, r)のsegfuncしたものを得る l: index(0-index) r: index(0-index) """ res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res import bisect,random N,E,T=map(int,input().split()) x=list(map(int,input().split())) x=[0]+x X=[2*x[i] for i in range(N+1)] dp=[0 for i in range(N+1)] dp[N]=abs(E-x[N]) seg1=SegTree(N+1,segfunc,ide_ele) seg3=SegTree(N+1,segfunc,ide_ele) seg1.update(N,E-x[N]+x[N]) seg3.update(N,E-x[N]+3*x[N]) for i in range(N-1,-1,-1): id=bisect.bisect_right(X,T+2*x[i+1]) test,test2=10**20,10**20 if id>i+1: #test1=min(dp[j]+x[j] for j in range(i+1,id))+T test1=seg1.query(i+1,id)+T if N+1>id: #test2=min(3*x[j]+dp[j] for j in range(id,N+1))-2*x[i+1] test2=seg3.query(id,N+1)-2*x[i+1] dp[i]=min(test1,test2)-x[i] seg1.update(i,dp[i]+x[i]) seg3.update(i,dp[i]+3*x[i]) #dp[i]=min(max(T,2*x[j]-2*x[i+1])+dp[j]+x[j] for j in range(i+1,N+1))-x[i] print(dp[0]) ```
output
1
73,185
19
146,371
Provide a correct Python 3 solution for this coding contest problem. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996
instruction
0
73,186
19
146,372
"Correct Solution: ``` n,e,t=map(int,input().split()) a,f,l,c=[0]+list(map(int,input().split())),[0]*(n+1),1,int(1e18) for i in range(1,n+1): while 2*(a[i]-a[l])>=t: c=min(c,f[l-1]-2*a[l]) l+=1 f[i]=min(f[l-1]+t,c+2*a[i]) print(f[n]+e) ```
output
1
73,186
19
146,373
Provide a correct Python 3 solution for this coding contest problem. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996
instruction
0
73,187
19
146,374
"Correct Solution: ``` import sys from bisect import bisect, bisect_left class BinaryIndexedTree: def __init__(self, n): self.size = n self.INF = 10 ** 18 self.tree = [self.INF] * (n + 1) def get_min(self, i): s = self.INF while i > 0: s = min(s, self.tree[i]) i -= i & -i return s def update(self, i, x): while i <= self.size: if self.tree[i] <= x: break self.tree[i] = x i += i & -i def solve(n, e, t, xxx): if n == 1: return e + t dp1 = [0] * (n + 1) dp2 = BinaryIndexedTree(n + 1) dp2.update(1, -xxx[0] * 2) for i in range(n): x = xxx[i] j = bisect_left(xxx, x - t // 2, hi=i) ex_time = dp1[j] + t if j > 0: ex_time = min(ex_time, x * 2 + dp2.get_min(j)) dp1[i + 1] = ex_time if i < n - 1: dp2.update(i + 2, ex_time - xxx[i + 1] * 2) return e + dp1[-1] n, e, t, *xxx = map(int, sys.stdin.buffer.read().split()) print(solve(n, e, t, xxx)) ```
output
1
73,187
19
146,375
Provide a correct Python 3 solution for this coding contest problem. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996
instruction
0
73,188
19
146,376
"Correct Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from bisect import bisect_left N,E,T = map(int,readline().split()) X = [0] + list(map(int,read().split())) half = T//2 I = [bisect_left(X,x-half) for x in X] INF = 10**18 def base_solution(): # これをseg木に乗せまーす dp = [0] * (N+1) for n in range(1,N+1): x = X[n] i = I[n] # i-1番目まで戻る → 待ち時間なし # i番目まで戻る → 待ち時間発生 if i >= 1: t1 = min((dp[k]-X[k] for k in range(i-1,n)),default=INF)+x+T t2 = min((dp[k]-X[k]-2*X[k+1] for k in range(i-1)),default=INF)+3*x else: t1 = min((dp[k]-X[k] for k in range(n)),default=INF)+x+T t2 = INF dp[n] = min(t1,t2) answer = dp[N] + (E-X[-1]) print(answer) class MinSegTree(): def __init__(self,N): self.Nelem = N self.size = 1<<(N.bit_length()) # 葉の要素数 def build(self,raw_data): # raw_data は 0-indexed INF = 10**18 self.data = [INF] * (2*self.size) for i,x in enumerate(raw_data): self.data[self.size+i] = x for i in range(self.size-1,0,-1): x = self.data[i+i]; y = self.data[i+i+1] self.data[i] = x if x<y else y def update(self,i,x): i += self.size self.data[i] = x i >>= 1 while i: x = self.data[i+i]; y = self.data[i+i+1] self.data[i] = x if x<y else y i >>= 1 def get_value(self,L,R): # [L,R] に対する値を返す L += self.size R += self.size + 1 # [L,R) に変更 x = 10**18 while L < R: if L&1: y = self.data[L] if x > y: x = y L += 1 if R&1: R -= 1 y = self.data[R] if x > y: x = y L >>= 1; R >>= 1 return x dp1 = MinSegTree(N+1) # dp[k]-X[k] を格納する dp2 = MinSegTree(N+1) # dp[k]-X[k]-2X[k+1] を格納する dp1.build([0]*(N+1)) dp2.build([0]*(N+1)) dp2.update(0,-2*X[1]) X.append(E) for n in range(1,N+1): x = X[n]; i = I[n] if i >= 1: t1 = dp1.get_value(i-1,n-1)+x+T t2 = dp2.get_value(0,i-2)+3*x t = t1 if t1<t2 else t2 else: t = dp1.get_value(0,n-1)+x+T dp1.update(n,t-x) dp2.update(n,t-x-2*X[n+1]) answer = t+E-x print(answer) ```
output
1
73,188
19
146,377
Provide a correct Python 3 solution for this coding contest problem. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996
instruction
0
73,189
19
146,378
"Correct Solution: ``` import sys readline = sys.stdin.readline class Segtree: def __init__(self, A, intv, initialize = True, segf = max): self.N = len(A) self.N0 = 2**(self.N-1).bit_length() self.intv = intv self.segf = segf if initialize: self.data = [intv]*self.N0 + A + [intv]*(self.N0 - self.N) for i in range(self.N0-1, 0, -1): self.data[i] = self.segf(self.data[2*i], self.data[2*i+1]) else: self.data = [intv]*(2*self.N0) def update(self, k, x): k += self.N0 self.data[k] = x while k > 0 : k = k >> 1 self.data[k] = self.segf(self.data[2*k], self.data[2*k+1]) def query(self, l, r): L, R = l+self.N0, r+self.N0 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 binsearch(self, l, r, check, reverse = False): L, R = l+self.N0, r+self.N0 SL, SR = [], [] while L < R: if R & 1: R -= 1 SR.append(R) if L & 1: SL.append(L) L += 1 L >>= 1 R >>= 1 if reverse: for idx in (SR + SL[::-1]): if check(self.data[idx]): break else: return -1 while idx < self.N0: if check(self.data[2*idx+1]): idx = 2*idx + 1 else: idx = 2*idx return idx - self.N0 else: pre = self.data[l+self.N0] for idx in (SL + SR[::-1]): if not check(self.segf(pre, self.data[idx])): pre = self.segf(pre, self.data[idx]) else: break else: return -1 while idx < self.N0: if check(self.segf(pre, self.data[2*idx])): idx = 2*idx else: pre = self.segf(pre, self.data[2*idx]) idx = 2*idx + 1 return idx - self.N0 INF = 10**18 + 3 N, E, T = map(int, readline().split()) X = list(map(int, readline().split())) X = [0] + [x-X[0] for x in X] + [INF] E -= X[0] dp = [0]*(N+2) dpl = Segtree([0]*(N+2), INF, initialize = False, segf = min) dpr = Segtree([0]*(N+2), INF, initialize = False, segf = min) dpl.update(0, 0) dpr.update(0, 0) for i in range(1, N+1): di = X[i] dn = X[i+1] ok = i ng = -1 while abs(ok-ng) > 1: med = (ok+ng)//2 if (X[i] - X[med])*2 <= T: ok = med else: ng = med left = ok-1 resr = dpr.query(left, i) + T + di resl = dpl.query(0, left) + 3*di dp[i] = min(resl, resr) dpl.update(i, dp[i] - di - 2*dn) dpr.update(i, dp[i] - di) print(dp[N] + E - X[N]) ```
output
1
73,189
19
146,379
Provide a correct Python 3 solution for this coding contest problem. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996
instruction
0
73,190
19
146,380
"Correct Solution: ``` """ Writer: SPD_9X2 https://atcoder.jp/contests/agc007/tasks/agc007_d まぁdpだよね 選択は 1.前の奴から引き継ぐ 2.新たに始める の2択か? ABCDの4つを同時に回収するとき Aアメ→Dコインまでの時間は max(3*(D-A),T+D-A) 待ち時間がちょうどないくらいが望ましいはず すなわち、2*(D-A)と Tの差が小さくなるように選ぶべき? 左から歩いて行き、毎回止まって待つ場合 時間はE+NTである ここからどれだけ減らせるかを基準に考えてみよう T以内にx個追加で回ってこれた場合、減少するのはxT x個回ってきたが、aだけ時間制限を超えた場合、減少はxT-a 少なくとも回れるならばすべて回ったほうが良い→右方向T/2以下にあるやつは確定で同時に取る そうでない場合、新たに始める or x-増加分 のコストを払うを選択できる これをうまくdpに落とし込めないか?? dp[ai][連続/始点] = その頂点が始点 or 連続点の場合の減少量の最大値 始点は,T/2より1つだけ右にある要素にあげるdpをする(二分探索で位置を求める) 連続の場合、+1のところの連続or始点にあげるdpをする あげるものは、E+NTからの減少量。よって最大値を求める 始点から上げる場合 iからT/2より+1右にある要素jの始点にあげる場合、(j-i-1)*T 可算 連続にあげる場合は、あまり分を考慮 (j-i)*T - 2*(A[j]-A[i])-T 連続から始点にあげる場合、+-0であげちゃう 連続から連続にあげる場合、T-(A[i+1]-A[i])*2 可算 大体おkだと思うけど 始点と終点の処理は? 始点は考慮する必要無し 終点は…ちょっと面倒くさい 座標infをおいておけばいいかな 座標infの始点が答えになりそう """ import bisect N,E,T = map(int,input().split()) A = list(map(int,input().split())) A.append(float("inf")) dp = [[float("-inf")] * 2 for i in range(N+1)] dp[0][0] = 0 for i in range(N): j = bisect.bisect_right(A,A[i] + T//2) dp[j][0] = max(dp[j][0] , dp[i][0] + (j-i-1)*T ) dp[j][1] = max(dp[j][1] , dp[i][0] + (j-i)*T - (2*(A[j]-A[i]) - T) ) dp[i+1][0] = max(dp[i+1][0] , dp[i][1]) dp[i+1][1] = max(dp[i+1][1] , dp[i][1] + T - (A[i+1]-A[i])*2 ) #print (dp) print (E+N*T - dp[-1][0]) ```
output
1
73,190
19
146,381
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996 Submitted Solution: ``` N,E,T=map(int,input().split()) if N>2000: exit() x=list(map(int,input().split())) x=[0]+x dp=[0 for i in range(N+1)] dp[N]=abs(E-x[N]) for i in range(N-1,-1,-1): dp[i]=min(max(T,2*x[j]-2*x[i+1])+dp[j]+x[j] for j in range(i+1,N+1))-x[i] print(dp[0]) ```
instruction
0
73,191
19
146,382
No
output
1
73,191
19
146,383
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996 Submitted Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from bisect import bisect_left N,E,T = map(int,readline().split()) X = [0] + list(map(int,read().split())) half = T//2 I = [bisect_left(X,x-half) for x in X] INF = 10**18 def base_solution(): # これをseg木に乗せまーす dp = [0] * (N+1) for n in range(1,N+1): x = X[n] i = I[n] # i-1番目まで戻る → 待ち時間なし # i番目まで戻る → 待ち時間発生 if i >= 1: t1 = min((dp[k]-X[k] for k in range(i-1,n)),default=INF)+x+T t2 = min((dp[k]-X[k]-2*X[k+1] for k in range(i-1)),default=INF)+3*x else: t1 = min((dp[k]-X[k] for k in range(n)),default=INF)+x+T t2 = INF dp[n] = min(t1,t2) answer = dp[N] + (E-X[-1]) print(answer) if N >= 10**4: print(-1) exit() base_solution() ```
instruction
0
73,192
19
146,384
No
output
1
73,192
19
146,385
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996 Submitted Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from bisect import bisect_left N,E,T = map(int,readline().split()) X = [0] + list(map(int,read().split())) half = T//2 I = [bisect_left(X,x-half) for x in X] INF = 10**18 def base_solution(): # これをseg木に乗せまーす dp = [0] * (N+1) for n in range(1,N+1): x = X[n] i = I[n] # i-1番目まで戻る → 待ち時間なし # i番目まで戻る → 待ち時間発生 if i >= 1: t1 = min((dp[k]-X[k] for k in range(i-1,n)),default=INF)+x+T t2 = min((dp[k]-X[k]-2*X[k+1] for k in range(i-1)),default=INF)+3*x else: t1 = min((dp[k]-X[k] for k in range(n)),default=INF)+x+T t2 = INF dp[n] = min(t1,t2) answer = dp[N] + (E-X[-1]) print(answer) class MinSegTree(): def __init__(self,N): self.Nelem = N self.size = 1<<(N.bit_length()) # 葉の要素数 def build(self,raw_data): # raw_data は 0-indexed INF = 10**18 self.data = [INF] * (2*self.size) for i,x in enumerate(raw_data): self.data[self.size+i] = x for i in range(self.size-1,0,-1): x = self.data[i+i]; y = self.data[i+i+1] self.data[i] = x if x<y else y def update(self,i,x): i += self.size self.data[i] = x i >>= 1 while i: x = self.data[i+i]; y = self.data[i+i+1] self.data[i] = x if x<y else y i >>= 1 def get_value(self,L,R): # [L,R] に対する値を返す L += self.size R += self.size + 1 # [L,R) に変更 x = 10**18 while L < R: if L&1: y = self.data[L] if x > y: x = y L += 1 if R&1: R -= 1 y = self.data[R] if x > y: x = y L >>= 1; R >>= 1 return x dp1 = MinSegTree(N+1) # dp[k]-X[k] を格納する dp2 = MinSegTree(N+1) # dp[k]-X[k]-2X[k+1] を格納する dp1.build([0]*(N+1)) dp2.build([0]*(N+1)) dp2.update(0,-2*X[1]) X.append(E) for n in range(1,N+1): x = X[n]; i = I[n] if i >= 1: t1 = dp1.get_value(i-1,n-1)+x+T t2 = dp2.get_value(0,i-2)+3*x t = t1 if t1<t2 else t2 else: t = dp1.get_value(0,n-1)+x+T dp1.update(n,t-x) dp2.update(n,t-x-2*X[n+1]) answer = t+E-x print(answer) ```
instruction
0
73,193
19
146,386
No
output
1
73,193
19
146,387
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a candy to a bear, it will provide a coin after T units of time. More specifically, if the i-th bear is given a candy at time t, it will put a coin at its position at time t+T. The purpose of this game is to give candies to all the bears, pick up all the coins, and go to the exit. Note that the player can only give a candy to a bear if the player is at the exact same position of the bear. Also, each bear will only produce a coin once. If the player visits the position of a coin after or at the exact same time that the coin is put down, the player can pick up the coin. Coins do not disappear until collected by the player. Shik is an expert of this game. He can give candies to bears and pick up coins instantly. You are given the configuration of the game. Please calculate the minimum time Shik needs to collect all the coins and go to the exit. Constraints * 1 \leq N \leq 100,000 * 1 \leq T, E \leq 10^9 * 0 < x_i < E * x_i < x_{i+1} for 1 \leq i < N * All input values are integers. Input The input is given from Standard Input in the following format: N E T x_1 x_2 ... x_N Output Print an integer denoting the answer. Examples Input 3 9 1 1 3 8 Output 12 Input 3 9 3 1 3 8 Output 16 Input 2 1000000000 1000000000 1 999999999 Output 2999999996 Submitted Solution: ``` s=input().split();n,e,t=int(s[0]),int(s[1]),int(s[2]) s=input().split() if (int(s[n-1])-int(s[0]))+t>t*n: print(e+t*n) elif t>int(s[n-1])*2: print(int(s[0])+(int(s[n-1])-int(s[0]))+t+(e-int(s[0]))) else: print(int(s[0])+(int(s[n-1])-int(s[0]))*2+(e-int(s[0]))) ```
instruction
0
73,194
19
146,388
No
output
1
73,194
19
146,389
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the i-th ball is ci and the value of the i-th ball is vi. Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence. The value of the sequence is defined as the sum of following values for each ball (where a and b are given constants): * If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) × a. * Otherwise, add (the value of the ball) × b. You are given q queries. Each query contains two integers ai and bi. For each query find the maximal value of the sequence she can make when a = ai and b = bi. Note that the new sequence can be empty, and the value of an empty sequence is defined as zero. Input The first line contains two integers n and q (1 ≤ n ≤ 105; 1 ≤ q ≤ 500). The second line contains n integers: v1, v2, ..., vn (|vi| ≤ 105). The third line contains n integers: c1, c2, ..., cn (1 ≤ ci ≤ n). The following q lines contain the values of the constants a and b for queries. The i-th of these lines contains two integers ai and bi (|ai|, |bi| ≤ 105). In each line integers are separated by single spaces. Output For each query, output a line containing an integer — the answer to the query. The i-th line contains the answer to the i-th query in the input order. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 6 3 1 -2 3 4 0 -1 1 2 1 2 1 1 5 1 -2 1 1 0 Output 20 9 4 Input 4 1 -3 6 -1 2 1 2 3 1 1 -1 Output 5 Note In the first example, to achieve the maximal value: * In the first query, you should select 1st, 3rd, and 4th ball. * In the second query, you should select 3rd, 4th, 5th and 6th ball. * In the third query, you should select 2nd and 4th ball. Note that there may be other ways to achieve the maximal value. Submitted Solution: ``` INF = 10 ** 18 n, q = map(int, input().split()) v = list(map(int, input().split())) c = list(map(int, input().split())) for t in range(q): a, b = map(int, input().split()) mx1, mx2 = -INF, -INF who1, who2 = -1, -1 ans = 0 dp = [-INF for i in range(n + 1)] for i in range(n): tmp = dp[c[i]] + v[i] * a if c[i] == who1: tmp = max(tmp, mx2 + v[i] * b) elif c[i] == who2: tmp = max(tmp, mx1 + v[i] * b) tmp = max(tmp, v[i] * b) ans = max(ans, tmp) dp[c[i]] = max(dp[c[i]], tmp) if c[i] == who1: mx1 = max(mx1, tmp) elif c[i] == who2: mx2 = max(mx2, tmp) if mx2 > mx1: mx1, mx2 = mx2, mx1 who1, who2 = who2, who1 elif tmp > mx1: mx1, mx2 = tmp, mx1 who1, who2 = c[i], who1 elif tmp > mx2: mx2 = tmp who2 = c[i] print(ans) ```
instruction
0
73,611
19
147,222
No
output
1
73,611
19
147,223
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the i-th ball is ci and the value of the i-th ball is vi. Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence. The value of the sequence is defined as the sum of following values for each ball (where a and b are given constants): * If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) × a. * Otherwise, add (the value of the ball) × b. You are given q queries. Each query contains two integers ai and bi. For each query find the maximal value of the sequence she can make when a = ai and b = bi. Note that the new sequence can be empty, and the value of an empty sequence is defined as zero. Input The first line contains two integers n and q (1 ≤ n ≤ 105; 1 ≤ q ≤ 500). The second line contains n integers: v1, v2, ..., vn (|vi| ≤ 105). The third line contains n integers: c1, c2, ..., cn (1 ≤ ci ≤ n). The following q lines contain the values of the constants a and b for queries. The i-th of these lines contains two integers ai and bi (|ai|, |bi| ≤ 105). In each line integers are separated by single spaces. Output For each query, output a line containing an integer — the answer to the query. The i-th line contains the answer to the i-th query in the input order. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 6 3 1 -2 3 4 0 -1 1 2 1 2 1 1 5 1 -2 1 1 0 Output 20 9 4 Input 4 1 -3 6 -1 2 1 2 3 1 1 -1 Output 5 Note In the first example, to achieve the maximal value: * In the first query, you should select 1st, 3rd, and 4th ball. * In the second query, you should select 3rd, 4th, 5th and 6th ball. * In the third query, you should select 2nd and 4th ball. Note that there may be other ways to achieve the maximal value. Submitted Solution: ``` n, q = map(int, input().split()) v = list(map(int, input().split())) c = list(map(int, input().split())) INF = 10 ** 18 for t in range(q): a, b = map(int, input().split()) mx1, mx2 = -INF, -INF who1, who2 = 0, 0 ans = 0 for i in range(n): tmp = -INF if c[i] == who1: tmp = max(tmp, max(mx1 + v[i] * a, mx2 + v[i] * b)) elif c[i] == who2: tmp = max(tmp, max(mx1 + v[i] * b, mx2 + v[i] * a)) else: tmp = max(tmp, max(mx1 + v[i] * b, mx2 + v[i] * b)) tmp = max(tmp, v[i] * b) ans = max(ans, tmp) if c[i] == who1: mx1 = max(mx1, tmp) elif c[i] == who2: mx2 = max(mx2, tmp) if mx2 > mx1: mx1, mx2, who1, who2 = mx2, mx1, who2, who1 elif tmp > mx1: mx1, mx2 = tmp, mx1 who1, who2 = c[i], who1 elif tmp > mx2: mx2 = tmp who2 = c[i] print(ans) ```
instruction
0
73,612
19
147,224
No
output
1
73,612
19
147,225
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the i-th ball is ci and the value of the i-th ball is vi. Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence. The value of the sequence is defined as the sum of following values for each ball (where a and b are given constants): * If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) × a. * Otherwise, add (the value of the ball) × b. You are given q queries. Each query contains two integers ai and bi. For each query find the maximal value of the sequence she can make when a = ai and b = bi. Note that the new sequence can be empty, and the value of an empty sequence is defined as zero. Input The first line contains two integers n and q (1 ≤ n ≤ 105; 1 ≤ q ≤ 500). The second line contains n integers: v1, v2, ..., vn (|vi| ≤ 105). The third line contains n integers: c1, c2, ..., cn (1 ≤ ci ≤ n). The following q lines contain the values of the constants a and b for queries. The i-th of these lines contains two integers ai and bi (|ai|, |bi| ≤ 105). In each line integers are separated by single spaces. Output For each query, output a line containing an integer — the answer to the query. The i-th line contains the answer to the i-th query in the input order. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 6 3 1 -2 3 4 0 -1 1 2 1 2 1 1 5 1 -2 1 1 0 Output 20 9 4 Input 4 1 -3 6 -1 2 1 2 3 1 1 -1 Output 5 Note In the first example, to achieve the maximal value: * In the first query, you should select 1st, 3rd, and 4th ball. * In the second query, you should select 3rd, 4th, 5th and 6th ball. * In the third query, you should select 2nd and 4th ball. Note that there may be other ways to achieve the maximal value. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=-10**12, func=lambda a, b: max(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n,q=map(int,input().split()) l1=list(map(int,input().split())) l=list(map(int,input().split())) e=[-1]*(n+1) prev=[-1]*(n+1) for i in range(n): prev[i]=e[l[i]] e[l[i]]=i for iw in range(q): a,b=map(int,input().split()) dp=[0]*(n+1) e=[0]*(n+1) ma=0 ind=-1 ma2=0 ind2=-1 for i in range(n): if e[l[i]]==0: dp[l[i]]=l1[i]*b e[l[i]]=1 else: dp[l[i]]=max(dp[l[i]],dp[l[i]]+l1[i]*a) if ind!=l[i]: dp[l[i]]=max(dp[l[i]],ma+l1[i]*b) else: dp[l[i]] = max(dp[l[i]], ma2+l1[i]*b) if dp[l[i]]>=ma: ma2=ma ind2=ind ma=dp[l[i]] ind=l[i] elif dp[l[i]]>=ma2: ma2 = dp[l[i]] ind2 = l[i] print(max(0,max(dp))) ```
instruction
0
73,613
19
147,226
No
output
1
73,613
19
147,227
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the i-th ball is ci and the value of the i-th ball is vi. Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence. The value of the sequence is defined as the sum of following values for each ball (where a and b are given constants): * If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) × a. * Otherwise, add (the value of the ball) × b. You are given q queries. Each query contains two integers ai and bi. For each query find the maximal value of the sequence she can make when a = ai and b = bi. Note that the new sequence can be empty, and the value of an empty sequence is defined as zero. Input The first line contains two integers n and q (1 ≤ n ≤ 105; 1 ≤ q ≤ 500). The second line contains n integers: v1, v2, ..., vn (|vi| ≤ 105). The third line contains n integers: c1, c2, ..., cn (1 ≤ ci ≤ n). The following q lines contain the values of the constants a and b for queries. The i-th of these lines contains two integers ai and bi (|ai|, |bi| ≤ 105). In each line integers are separated by single spaces. Output For each query, output a line containing an integer — the answer to the query. The i-th line contains the answer to the i-th query in the input order. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 6 3 1 -2 3 4 0 -1 1 2 1 2 1 1 5 1 -2 1 1 0 Output 20 9 4 Input 4 1 -3 6 -1 2 1 2 3 1 1 -1 Output 5 Note In the first example, to achieve the maximal value: * In the first query, you should select 1st, 3rd, and 4th ball. * In the second query, you should select 3rd, 4th, 5th and 6th ball. * In the third query, you should select 2nd and 4th ball. Note that there may be other ways to achieve the maximal value. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: math.gcd(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n,q=map(int,input().split()) l1=list(map(int,input().split())) l=list(map(int,input().split())) e=[-1]*(n+1) prev=[-1]*(n+1) for i in range(n): prev[i]=e[l[i]] e[l[i]]=i for iw in range(q): a,b=map(int,input().split()) dp=[[-10**12 for i1 in range(2)]for j in range(n)] dp[0][1]=l1[0]*b for i in range(1,n): dp[i][0]=max(dp[i-1][0],dp[i-1][1],dp[i][0]) if prev[i]!=-1: dp[i][1]=max(dp[prev[i]][1]+l1[i]*a,dp[i][1]) if prev[i]!=i-1: dp[i][1]=max(dp[i][1],dp[i-1][1]+l1[i]*b) print(max(0,max(dp[-1]))) ```
instruction
0
73,614
19
147,228
No
output
1
73,614
19
147,229
Provide tags and a correct Python 3 solution for this coding contest problem. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image>
instruction
0
73,658
19
147,316
Tags: combinatorics, math, probabilities Correct Solution: ``` m, n = map(int, input().split()) if m == 1: print(1) else: print(1/m + (m-1)/m*(n-1)/(n*m-1)) ```
output
1
73,658
19
147,317
Provide tags and a correct Python 3 solution for this coding contest problem. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image>
instruction
0
73,659
19
147,318
Tags: combinatorics, math, probabilities Correct Solution: ``` n,m=map(int,input().split()) if n*m==1: print(1) else: print(1/n+(n-1)*(m-1)/(n*(n*m-1))) ```
output
1
73,659
19
147,319
Provide tags and a correct Python 3 solution for this coding contest problem. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image>
instruction
0
73,660
19
147,320
Tags: combinatorics, math, probabilities Correct Solution: ``` # https://codeforces.com/problemset/problem/452/C n, m = map(int, input().split()) if n*m==1: print(1) else: print(1/n + (m-1)*(n-1) / ((m*n-1) * n)) ```
output
1
73,660
19
147,321
Provide tags and a correct Python 3 solution for this coding contest problem. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image>
instruction
0
73,661
19
147,322
Tags: combinatorics, math, probabilities Correct Solution: ``` def main(): n, m = map(int, input().split()) if n == 1 == m: res = 1. else: res = (2 * n * m - n - m) / (n * m - 1) / n print('{:.16f}'.format(res)) if __name__ == '__main__': main() ```
output
1
73,661
19
147,323
Provide tags and a correct Python 3 solution for this coding contest problem. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image>
instruction
0
73,662
19
147,324
Tags: combinatorics, math, probabilities Correct Solution: ``` import math import decimal import functools @functools.lru_cache(maxsize=None) def factorial(n): return math.factorial(n) @functools.lru_cache(maxsize=None) def binomial(k, n): if k > n // 2: return product(range(k + 1, n + 1)) / factorial(n - k) else: return product(range(n - k + 1, n + 1)) / factorial(k) def P(k, n, m): return k ** 2 / n * binomial(k, n) * product((m - i) / (m * n - i) for i in range(k)) * product( (m * n - i - (m - k)) / (m * n - i) for i in range(k, n)) def product(iterable): res = 1 for e in iterable: res *= e return res def solve(n, m): return sum(P(k, n, m) for k in range(1, min(n, m) + 1)) if __name__ == '__main__': n, m = map(int, input().split()) print(solve(n, m)) ```
output
1
73,662
19
147,325
Provide tags and a correct Python 3 solution for this coding contest problem. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image>
instruction
0
73,663
19
147,326
Tags: combinatorics, math, probabilities Correct Solution: ``` S=str(input()) l=list(map(int, S.split(' '))) n,m=l[0],l[1] S=0 t=1/n l=m*n-m-n y=min(n,m) z=max(n,m) for i in range(1,y+1): if i>1: t=t*i*(m+1-i)*(m*n-z-i+2)*(n+1-i)/((i-1)*(i-1)*(l+i)*(n*m-i+1)) S=S*(m*n-z-i+2)/(n*m-i+1)+t print(S) ```
output
1
73,663
19
147,327
Provide tags and a correct Python 3 solution for this coding contest problem. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image>
instruction
0
73,664
19
147,328
Tags: combinatorics, math, probabilities Correct Solution: ``` def cal(m,n,i): tot=1 for j in range(1,n-i+1): tot=tot*(n*m-m-n+i+j)/(n*m-n+i+j) for j in range(1,i+1): tot=tot*(m-i+j)*(n-i+j)/(n*m-n+j)/j return tot n,m = input().split() n = int(n) m = int(m) ans = 0 for i in range(1, min(n,m)+1): ans += i * i /n * cal(m,n,i) print(ans) ```
output
1
73,664
19
147,329
Provide tags and a correct Python 3 solution for this coding contest problem. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image>
instruction
0
73,665
19
147,330
Tags: combinatorics, math, probabilities Correct Solution: ``` n,m = map(float, input().split()) if n==1:print(1) else:print((1+(n-1)*(m-1)/(n*m-1))/n) ```
output
1
73,665
19
147,331
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image> Submitted Solution: ``` n,m=map(int,input().split()) print(1.0 if n==m==1 else 1/n*((n-1)*(m-1)/(n*m-1)+1)) # Made By Mostafa_Khaled ```
instruction
0
73,666
19
147,332
Yes
output
1
73,666
19
147,333
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image> Submitted Solution: ``` n, m = map(int, input().split()) print('{:.9}'.format((1 + (n - 1) * (m - 1) / (n * m - 1)) / n) if n > 1 or m > 1 else 1) ```
instruction
0
73,667
19
147,334
Yes
output
1
73,667
19
147,335
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image> Submitted Solution: ``` n, m = map(int, input().split()) print(1 if n*m == 1 else 1/n + (n-1) / n * (m-1) / (n*m - 1)) ```
instruction
0
73,668
19
147,336
Yes
output
1
73,668
19
147,337
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image> Submitted Solution: ``` n, m = list(map(int, (input().split()))) if(m*n > 1): print(1 / n + (n - 1) * (m - 1) / n / (m*n - 1)) else: print(1) # Thu Feb 27 2020 19:23:17 GMT+0300 (MSK) ```
instruction
0
73,669
19
147,338
Yes
output
1
73,669
19
147,339
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image> Submitted Solution: ``` def C(a,b): return fact(a)//(b*fact(a-b)) def fact(a): ans=1 for i in range(2,a+1): ans*=i return ans n,m=map(int,input().split()) if n==4 and m==4: print(0.4) print(m/C(n*m,n)*(1+(n*(n-1)*(n-1))/2)) ```
instruction
0
73,670
19
147,340
No
output
1
73,670
19
147,341
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image> Submitted Solution: ``` def C(a,b): return fact(a)//(b*fact(a-b)) def fact(a): ans=1 for i in range(2,a+1): ans*=i return ans n,m=map(int,input().split()) print(m/C(n*m,n)*(1+(n*(n-1)*(n-1))/2)) ```
instruction
0
73,671
19
147,342
No
output
1
73,671
19
147,343
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image> Submitted Solution: ``` S=str(input()) l=list(map(int, S.split(' '))) n,m=l[0],l[1] S=0 t=1/m l=m*n-m-n x=max(n,m) y=min(n,m) for i in range(1,y+1): if i>1: t=t*i*(n+1-i)*(n+1-i)/((i-1)*(i-1)*(l+i)*(n*m-i+1)) S=S/(n*m-i+1)+t for i in range(x*y-x-y+2,x*y-x+1): S=S*i print(S) ```
instruction
0
73,672
19
147,344
No
output
1
73,672
19
147,345
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards. The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful. You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case. Input First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks. Output On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10 - 6. Examples Input 2 2 Output 0.6666666666666666 Input 4 4 Output 0.4000000000000000 Input 1 2 Output 1.0000000000000000 Note In the first sample, with probability <image> Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed. With the remaining <image> probability he took two different cards, and the probability of pulling off the trick is <image>. The resulting probability is <image> Submitted Solution: ``` import sys input=sys.stdin.readline n,m=map(int,input().split()) print((2*m*n-m-n)/(m*(n*m-1))) ```
instruction
0
73,673
19
147,346
No
output
1
73,673
19
147,347
Provide tags and a correct Python 3 solution for this coding contest problem. Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game. Output If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output. If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print "Friendship" (without quotes). Examples Input 6 ADAAAA Output Anton Input 7 DDDAADA Output Danik Input 6 DADADA Output Friendship Note In the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton". In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik". In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".
instruction
0
73,799
19
147,598
Tags: implementation, strings Correct Solution: ``` n = int(input()) s = input().upper() if s.count('A')>s.count('D'): print('Anton') elif s.count('A') == s.count('D'): print('Friendship') else: print('Danik') ```
output
1
73,799
19
147,599
Provide tags and a correct Python 3 solution for this coding contest problem. Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose. Input The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000). The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: 1. Binary number of exactly m bits. 2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different. Output In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers. Examples Input 3 3 a := 101 b := 011 c := ? XOR b Output 011 100 Input 5 1 a := 1 bb := 0 cx := ? OR a d := ? XOR ? e := d AND bb Output 0 0 Note In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15. For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
instruction
0
73,824
19
147,648
Tags: bitmasks, brute force, dfs and similar, expression parsing, implementation Correct Solution: ``` f = {'OR': lambda x, y: x | y, 'AND': lambda x, y: x & y, 'XOR': lambda x, y: x ^ y} n, m = map(int, input().split()) p, u, v = [], [], [] l = {'?': n} for i in range(n): q, s = input().split(' := ') if ' ' in s: x, t, y = s.split() p += [(l[x], f[t], l[y])] u += [i] else: p += [int(s, 2)] v += [i] l[q] = i s = [0] * (n + 1) def g(k, l): s[n] = k for i in v: s[i] = (p[i] & l) > 0 for i in u: x, f, y = p[i] s[i] = f(s[x], s[y]) return sum(s) - k a = b = '' for j in range(m): l = 1 << m - j - 1 x, y = g(0, l), g(1, l) a += '01'[y < x] b += '01'[y > x] print(a, b) ```
output
1
73,824
19
147,649
Provide tags and a correct Python 3 solution for this coding contest problem. Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose. Input The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000). The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: 1. Binary number of exactly m bits. 2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different. Output In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers. Examples Input 3 3 a := 101 b := 011 c := ? XOR b Output 011 100 Input 5 1 a := 1 bb := 0 cx := ? OR a d := ? XOR ? e := d AND bb Output 0 0 Note In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15. For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
instruction
0
73,825
19
147,650
Tags: bitmasks, brute force, dfs and similar, expression parsing, implementation Correct Solution: ``` n, m = map(int, input().split()) vars = {} def mxor(a, b): if a == b: return '0' elif (a == '0' and b == '1') or (a == '1' and b =='0'): return '1' elif (a == '0' and b == 'x') or (a == 'x' and b == '0'): return 'x' elif (a == '0' and b == '!') or (a == '!' and b == '0'): return '!' elif (a == '1' and b == 'x') or (a == 'x' and b == '1'): return '!' elif (a == '1' and b == '!') or (a == '!' and b == '1'): return 'x' elif (a == 'x' and b == '!') or (a == '!' and b == 'x'): return '1' def mand(a, b): if a == b: return a elif (a == '0' or b =='0'): return '0' elif (a == '1' and b == 'x') or (a == 'x' and b == '1'): return 'x' elif (a == '1' and b == '!') or (a == '!' and b == '1'): return '!' elif (a == 'x' and b == '!') or (a == '!' and b == 'x'): return '0' def mor(a, b): if a == b: return a if a == '1' or b == '1': return '1' elif a == '0': return b elif b == '0': return a elif (a == 'x' and b == '!') or (a == '!' and b == 'x'): return '1' def calc(a, op, b): global m global vars a = (['x']*m if a == '?' else vars[a]) b = (['x']*m if b == '?' else vars[b]) if op == 'XOR': op = mxor elif op == 'AND': op = mand else: # op == 'OR': op = mor return ''.join([op(x, y) for x, y in zip(a, b)]) for _ in range(n): i = input().split() if len(i) == 3: vars[i[0]] = i[2] else: vars[i[0]] = calc(*i[2:]) r = [0] * m for i in range(m): for v in vars.values(): if v[i] == 'x': r[i] += 1 elif v[i] == '!': r[i] -= 1 mmin = ['0'] * m mmax = ['0'] * m for i in range(m): if r[i] < 0: mmin[i] = '1' for i in range(m): if r[i] > 0: mmax[i] = '1' print(''.join(mmin)) print(''.join(mmax)) ```
output
1
73,825
19
147,651
Provide tags and a correct Python 3 solution for this coding contest problem. Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose. Input The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000). The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: 1. Binary number of exactly m bits. 2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different. Output In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers. Examples Input 3 3 a := 101 b := 011 c := ? XOR b Output 011 100 Input 5 1 a := 1 bb := 0 cx := ? OR a d := ? XOR ? e := d AND bb Output 0 0 Note In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15. For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
instruction
0
73,826
19
147,652
Tags: bitmasks, brute force, dfs and similar, expression parsing, implementation Correct Solution: ``` f = {'OR': lambda x, y: x | y, 'AND': lambda x, y: x & y, 'XOR': lambda x, y: x ^ y} n, m = map(int, input().split()) u, v = [], [] d = {'?': n} for i in range(n): q, s = input().split(' := ') if ' ' in s: x, t, y = s.split() u += [(i, d[x], f[t], d[y])] else: v += [(i, s)] d[q] = i s = [0] * (n + 1) def g(k, j): s[n] = k for i, q in v: s[i] = q[j] == '1' for i, x, f, y in u: s[i] = f(s[x], s[y]) return sum(s) - k a = b = '' for j in range(m): d = g(1, j) - g(0, j) a += '01'[d < 0] b += '01'[d > 0] print(a, b) ```
output
1
73,826
19
147,653
Provide tags and a correct Python 3 solution for this coding contest problem. Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose. Input The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000). The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: 1. Binary number of exactly m bits. 2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different. Output In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers. Examples Input 3 3 a := 101 b := 011 c := ? XOR b Output 011 100 Input 5 1 a := 1 bb := 0 cx := ? OR a d := ? XOR ? e := d AND bb Output 0 0 Note In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15. For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
instruction
0
73,827
19
147,654
Tags: bitmasks, brute force, dfs and similar, expression parsing, implementation Correct Solution: ``` n, m = map(int, input().split()) v = [('?', '')] temp = [(0, 1)] d = {} d['?'] = 0 mn, mx = '', '' for i in range(n): name, val = input().split(' := ') v.append((name, val.split())) temp.append((-1, -1)) d[name] = i + 1 def eval(expr, bit1, bit2): if expr == 'OR': return bit1 | bit2 elif expr == 'AND': return bit1 and bit2 elif expr == 'XOR': return bit1 ^ bit2 else: raise AttributeError() for i in range(m): for name, expr in v[1:]: j = d[name] if len(expr) == 1: temp[j] = (int(expr[0][i]), int(expr[0][i])) else: bit1, bit2 = temp[d[expr[0]]], temp[d[expr[2]]] temp[j] = (eval(expr[1], bit1[0], bit2[0]), eval(expr[1], bit1[1], bit2[1])) z, o = sum(temp[_][0] for _ in range(1, n + 1)), sum(temp[_][1] for _ in range(1, n + 1)) mn += '1' if o < z else '0' mx += '1' if o > z else '0' print(mn) print(mx) ```
output
1
73,827
19
147,655
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one). Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game. Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number. Input The first line contains 3 integers n, m and c (<image>, <image> means <image> rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process. Interaction In each round, your program needs to read one line containing a single integer pi (1 ≤ pi ≤ c), indicating the number given to Chtholly. Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in. After outputting each line, don't forget to flush the output. For example: * fflush(stdout) in C/C++; * System.out.flush() in Java; * sys.stdout.flush() in Python; * flush(output) in Pascal; * See the documentation for other languages. If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game. Example Input 2 4 4 2 1 3 Output 1 2 2 Note In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round. The input format for hacking: * The first line contains 3 integers n, m and c; * The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.
instruction
0
73,884
19
147,768
Tags: binary search, constructive algorithms, games, greedy, interactive Correct Solution: ``` n, m, c = map(int, input().split()) a = [0] * n while a.count(0): x = int(input()) if x > c // 2: i = n - 1 while a[i] >= x: i -= 1 a[i] = x else: i = 0 while a[i] and a[i] <= x: i += 1 a[i] = x print(i + 1) ```
output
1
73,884
19
147,769
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one). Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game. Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number. Input The first line contains 3 integers n, m and c (<image>, <image> means <image> rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process. Interaction In each round, your program needs to read one line containing a single integer pi (1 ≤ pi ≤ c), indicating the number given to Chtholly. Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in. After outputting each line, don't forget to flush the output. For example: * fflush(stdout) in C/C++; * System.out.flush() in Java; * sys.stdout.flush() in Python; * flush(output) in Pascal; * See the documentation for other languages. If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game. Example Input 2 4 4 2 1 3 Output 1 2 2 Note In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round. The input format for hacking: * The first line contains 3 integers n, m and c; * The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.
instruction
0
73,885
19
147,770
Tags: binary search, constructive algorithms, games, greedy, interactive Correct Solution: ``` import sys def output(n): print(n) sys.stdout.flush() n, m, c = map(int, input().split()) arr = [0 for _ in range(n)] l = -1 r = n while 1 < r - l: p = int(input()) if p <= (c + 1) // 2: for i in range(0, r): if arr[i] == 0: l += 1 output(i + 1) arr[i] = p break elif p < arr[i]: output(i + 1) arr[i] = p break else: for i in range(n - 1, l, -1): if arr[i] == 0: r -= 1 output(i + 1) arr[i] = p break elif arr[i] < p: output(i + 1) arr[i] = p break ```
output
1
73,885
19
147,771
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one). Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game. Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number. Input The first line contains 3 integers n, m and c (<image>, <image> means <image> rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process. Interaction In each round, your program needs to read one line containing a single integer pi (1 ≤ pi ≤ c), indicating the number given to Chtholly. Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in. After outputting each line, don't forget to flush the output. For example: * fflush(stdout) in C/C++; * System.out.flush() in Java; * sys.stdout.flush() in Python; * flush(output) in Pascal; * See the documentation for other languages. If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game. Example Input 2 4 4 2 1 3 Output 1 2 2 Note In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round. The input format for hacking: * The first line contains 3 integers n, m and c; * The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.
instruction
0
73,886
19
147,772
Tags: binary search, constructive algorithms, games, greedy, interactive Correct Solution: ``` import sys n, m, c = map(int, input().split()) l = [0 for _ in range(n)] for j in range(m): p = int(input()) if p>c//2: i = n-1 while (i>0 and p<=l[i]): i-=1 l[i] = p else: i = 0 while (l[i]!=0 and i<n-1 and p>=l[i]): i+=1 l[i] = p print(i+1) # print(l) sys.stdout.flush() if (0 not in l) and (sorted(l)==l): break ```
output
1
73,886
19
147,773
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one). Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game. Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number. Input The first line contains 3 integers n, m and c (<image>, <image> means <image> rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process. Interaction In each round, your program needs to read one line containing a single integer pi (1 ≤ pi ≤ c), indicating the number given to Chtholly. Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in. After outputting each line, don't forget to flush the output. For example: * fflush(stdout) in C/C++; * System.out.flush() in Java; * sys.stdout.flush() in Python; * flush(output) in Pascal; * See the documentation for other languages. If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game. Example Input 2 4 4 2 1 3 Output 1 2 2 Note In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round. The input format for hacking: * The first line contains 3 integers n, m and c; * The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.
instruction
0
73,887
19
147,774
Tags: binary search, constructive algorithms, games, greedy, interactive Correct Solution: ``` import sys from bisect import bisect_left, bisect_right from itertools import * class Antiint: def __init__(self, i): self.i = i def __lt__(self, other): return self.i > other.i def __eq__(self, other): return self.i == other.i n, m, c = map(int, input().split()) down_c = c // 2 paper_left = [0] paper_right = [Antiint(c + 1)] while len(paper_left) + len(paper_right) < n + 2: next = int(input()) if next <= down_c: if next >= paper_left[-1]: paper_left.append(next) print(len(paper_left) - 1) else: index = bisect_right(paper_left, next) paper_left[index] = next print(index) else: if next <= paper_right[-1].i: paper_right.append(Antiint(next)) print(n + 2 - len(paper_right)) else: index = bisect_right(paper_right, Antiint(next)) paper_right[index] = Antiint(next) print(n + 1 - index) sys.stdout.flush() ```
output
1
73,887
19
147,775
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one). Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game. Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number. Input The first line contains 3 integers n, m and c (<image>, <image> means <image> rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process. Interaction In each round, your program needs to read one line containing a single integer pi (1 ≤ pi ≤ c), indicating the number given to Chtholly. Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in. After outputting each line, don't forget to flush the output. For example: * fflush(stdout) in C/C++; * System.out.flush() in Java; * sys.stdout.flush() in Python; * flush(output) in Pascal; * See the documentation for other languages. If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game. Example Input 2 4 4 2 1 3 Output 1 2 2 Note In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round. The input format for hacking: * The first line contains 3 integers n, m and c; * The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.
instruction
0
73,888
19
147,776
Tags: binary search, constructive algorithms, games, greedy, interactive Correct Solution: ``` def main(): n, m, c = map(int, input().split()) middle = ((c + 1) // 2) * 2 + 1 xs = [middle for _ in range(n)] def value(a, b): # moving from a to b. What is the value of that? if a > middle: return b - a elif a < middle: return a - b return c for _ in range(m): sheet = int(input().strip()) * 2 best_i = -1 best_value = -1 for i in range(n): if (i == 0 or xs[i - 1] <= sheet) and (i == n - 1 or sheet <= xs[i + 1]): tmp_value = value(xs[i], sheet) if tmp_value > best_value: best_value = tmp_value best_i = i xs[best_i] = sheet print(best_i + 1, flush=True) if not any(x == middle for x in xs): break if __name__ == '__main__': main() ```
output
1
73,888
19
147,777
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one). Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game. Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number. Input The first line contains 3 integers n, m and c (<image>, <image> means <image> rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process. Interaction In each round, your program needs to read one line containing a single integer pi (1 ≤ pi ≤ c), indicating the number given to Chtholly. Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in. After outputting each line, don't forget to flush the output. For example: * fflush(stdout) in C/C++; * System.out.flush() in Java; * sys.stdout.flush() in Python; * flush(output) in Pascal; * See the documentation for other languages. If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game. Example Input 2 4 4 2 1 3 Output 1 2 2 Note In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round. The input format for hacking: * The first line contains 3 integers n, m and c; * The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.
instruction
0
73,889
19
147,778
Tags: binary search, constructive algorithms, games, greedy, interactive Correct Solution: ``` def get_int(string, n): i = j = k = 0 for s in string: k += 1 for s in string: if i == n - 1: break if s == ' ': i += 1 j += 1 i = 0 while j < k: if string[j] == ' ': break i = 10 * i + int(string[j]) j += 1 return i def check_order(ls, n): for i in ls: if i == None: return 0 for i in range(0, n - 1): if ls[i] > ls[i + 1]: return -1 return 1 def forward(p, ls, n): for i in range(0, n): if ls[i] == None: ls[i] = p print(i + 1) return 0 if ls[i] > p: ls[i] = p print(i + 1) return 0 def reverse(p, ls, n): for i in range(0, n): if ls[n - 1 - i] == None: ls[n - 1 - i] = p print(n - i) return 0 elif ls[n - 1 - i] < p: ls[n - i - 1] = p print(n - i) return 0 x = input() n = get_int(x, 1) m = get_int(x, 2) c = get_int(x, 3) ls = [] for i in range(0, n): ls += [None] for i in range(0, m): p = int(input()) if p > c/2: reverse(p, ls, n) else: forward(p, ls, n) if check_order(ls, n) == 1: break ```
output
1
73,889
19
147,779
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one). Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game. Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number. Input The first line contains 3 integers n, m and c (<image>, <image> means <image> rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process. Interaction In each round, your program needs to read one line containing a single integer pi (1 ≤ pi ≤ c), indicating the number given to Chtholly. Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in. After outputting each line, don't forget to flush the output. For example: * fflush(stdout) in C/C++; * System.out.flush() in Java; * sys.stdout.flush() in Python; * flush(output) in Pascal; * See the documentation for other languages. If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game. Example Input 2 4 4 2 1 3 Output 1 2 2 Note In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round. The input format for hacking: * The first line contains 3 integers n, m and c; * The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.
instruction
0
73,890
19
147,780
Tags: binary search, constructive algorithms, games, greedy, interactive Correct Solution: ``` import bisect import sys def output(n): print(n) sys.stdout.flush() n, m, c = map(int, input().split()) al = [c + 1 for _ in range(n)] ar = [0 for _ in range(n)] l = -1 r = n while 1 < r - l: p = int(input()) if p <= (c + 1) // 2: i = bisect.bisect_right(al, p) output(i + 1) if al[i] == c + 1: l += 1 al[i] = p else: i = bisect.bisect_right(ar, -p) output(n - i) if ar[i] == 0: r -= 1 ar[i] = -p ```
output
1
73,890
19
147,781
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. <image> Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right. This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one). Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game. Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number. Input The first line contains 3 integers n, m and c (<image>, <image> means <image> rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process. Interaction In each round, your program needs to read one line containing a single integer pi (1 ≤ pi ≤ c), indicating the number given to Chtholly. Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in. After outputting each line, don't forget to flush the output. For example: * fflush(stdout) in C/C++; * System.out.flush() in Java; * sys.stdout.flush() in Python; * flush(output) in Pascal; * See the documentation for other languages. If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game. Example Input 2 4 4 2 1 3 Output 1 2 2 Note In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round. The input format for hacking: * The first line contains 3 integers n, m and c; * The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.
instruction
0
73,891
19
147,782
Tags: binary search, constructive algorithms, games, greedy, interactive Correct Solution: ``` import sys n, m, c = map(int, input().split()) free = n nums = [0] * n for i in range(m): pi = int(input()) if(pi > c//2): current = n - 1 while(nums[current] > 0 and nums[current] >= pi and current >= 0):current -= 1 if(current == -1):current = 0 if(nums[current] == 0):free -= 1 nums[current] = pi print(current + 1) else: current = 0 while(current < n and nums[current] > 0 and nums[current] <= pi):current += 1 if(current == n):current = n - 1 if(nums[current] == 0):free -=1 nums[current] = pi print(current + 1) if(free == 0):break ```
output
1
73,891
19
147,783
Provide a correct Python 3 solution for this coding contest problem. A Bingo game is played by one gamemaster and several players. At the beginning of a game, each player is given a card with M × M numbers in a matrix (See Figure 10). <image> As the game proceeds, the gamemaster announces a series of numbers one by one. Each player punches a hole in his card on the announced number, if any. When at least one 'Bingo' is made on the card, the player wins and leaves the game. The 'Bingo' means that all the M numbers in a line are punched vertically, horizontally or diagonally (See Figure 11). <image> The gamemaster continues announcing numbers until all the players make a Bingo. In the ordinary Bingo games, the gamemaster chooses numbers by a random process and has no control on them. But in this problem the gamemaster knows all the cards at the beginning of the game and controls the game by choosing the number sequence to be announced at his will. Specifically, he controls the game to satisfy the following condition. Cardi makes a Bingo no later than Cardj, for i < j. (*) Figure 12 shows an example of how a game proceeds. The gamemaster cannot announce '5' before '16', because Card4 makes a Bingo before Card2 and Card3, violating the condition (*). Your job is to write a program which finds the minimum length of such sequence of numbers for the given cards. Input The input consists of multiple datasets. The format of each dataset is as follows. <image> All data items are integers. P is the number of the cards, namely the number of the players. M is the number of rows and the number of columns of the matrix on each card. Nkij means the number written at the position (i, j) on the k-th card. If (i, j) ≠ (p, q), then Nkij ≠ Nkpq. The parameters P, M, and N satisfy the conditions 2 ≤ P ≤ 4, 3 ≤ M ≤ 4, and 0 ≤ Nkij ≤ 99. The end of the input is indicated by a line containing two zeros separated by a space. It is not a dataset. Output For each dataset, output the minimum length of the sequence of numbers which satisfy the condition (*). Output a zero if there are no such sequences. Output for each dataset must be printed on a separate line. Example Input 4 3 10 25 11 20 6 2 1 15 23 5 21 3 12 23 17 7 26 2 8 18 4 22 13 27 16 5 11 19 9 24 2 11 5 14 28 16 4 3 12 13 20 24 28 32 15 16 17 12 13 21 25 29 33 16 17 18 12 13 22 26 30 34 17 18 15 12 13 23 27 31 35 18 15 16 4 3 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 41 42 43 44 45 46 47 48 49 4 4 2 6 9 21 15 23 17 31 33 12 25 4 8 24 13 36 22 18 27 26 35 28 3 7 11 20 38 16 5 32 14 29 26 7 16 29 27 3 38 14 18 28 20 32 22 35 11 5 36 13 24 8 4 25 12 33 31 17 23 15 21 9 6 2 0 0 Output 5 4 12 0
instruction
0
74,127
19
148,254
"Correct Solution: ``` def solve(): from itertools import product from sys import stdin f_i = stdin while True: P, M = map(int, f_i.readline().split()) if P == 0: break bingo = [] for i in range(P): b = [] card = list(map(int, f_i.readline().split())) d1 = [] # diagonally d2 = [] # diagonally for i in range(M): b.append(card[i::M]) # vertically b.append(card[i*M:i*M+M]) # horizontally d1.append(card[i*M+i]) d2.append(card[(M-1)*(i+1)]) b += [d1, d2] bingo.append(set(frozenset(b_i) for b_i in b)) if P == 2: ans = min(len(t1 | t2) for t1, t2 in product(*bingo)) elif P == 3: ans = P * M + 1 c0, c1, c2 = bingo for b0 in c0: if b0 in c2: for b1 in c1: if b1.intersection(b0): break else: continue for b1 in c1: b01 = b0.union(b1) last = set(b for b in c2 if b.issubset(b01)) if last: if not b1.intersection(*last): continue for b2 in c2: tmp = len(b2.union(b01)) if tmp < ans: ans = tmp if ans == P * M + 1: ans = 0 else: ans = P * M + 1 c0, c1, c2, c3 = bingo for b0 in c0: if b0 in c2: for b1 in c1: if b1.intersection(b0): break else: continue if b0 in c3: for b1, b2 in product(c1, c2): if b0.intersection(b1, b2): break else: continue for b1 in c1: b01 = b0.union(b1) third = set(b2 for b2 in c2 if b2.issubset(b01)) if third: if not b1.intersection(*third): continue last = set(b3 for b3 in c3 if b3.issubset(b01)) if last: if not b1.intersection(*last): continue if third and last: if not b1.intersection(*third, *last): continue if not third and last: for b2, b3 in product(c2, last): if b1.intersection(b2, b3): break else: continue for b2 in c2: b012 = b0.union(b1, b2) last = set(b for b in c3 if b.issubset(b012)) if last: last_num = b2.intersection(*last) if not last_num: continue first = set(b for b in c0 if b.issubset(b012)) if first.issubset(last): sec = set(b for b in c1 if b.issubset(b012)) if not last_num.intersection(*sec): continue for b3 in c3: tmp = len(b012.union(b3)) if tmp < ans: ans = tmp if ans == P * M + 1: ans = 0 print(ans) solve() ```
output
1
74,127
19
148,255
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n cards in the pile are also given in the order from top to bottom. In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile. Nauuo wants to make the n numbered cards piled up in increasing order (the i-th card in the pile from top to bottom is the card i) as quickly as possible. Can you tell her the minimum number of operations? Input The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of numbered cards. The second line contains n integers a_1,a_2,…,a_n (0≤ a_i≤ n) — the initial cards in Nauuo's hands. 0 represents an empty card. The third line contains n integers b_1,b_2,…,b_n (0≤ b_i≤ n) — the initial cards in the pile, given in order from top to bottom. 0 represents an empty card. It is guaranteed that each number from 1 to n appears exactly once, either in a_{1..n} or b_{1..n}. Output The output contains a single integer — the minimum number of operations to make the n numbered cards piled up in increasing order. Examples Input 3 0 2 0 3 0 1 Output 2 Input 3 0 2 0 1 0 3 Output 4 Input 11 0 0 0 5 0 0 0 4 0 0 11 9 2 6 0 8 1 7 0 3 0 10 Output 18 Note Example 1 We can play the card 2 and draw the card 3 in the first operation. After that, we have [0,3,0] in hands and the cards in the pile are [0,1,2] from top to bottom. Then, we play the card 3 in the second operation. The cards in the pile are [1,2,3], in which the cards are piled up in increasing order. Example 2 Play an empty card and draw the card 1, then play 1, 2, 3 in order.
instruction
0
74,223
19
148,446
Tags: greedy, implementation Correct Solution: ``` N = int(input()) a_list = list(map(int, input().split())) b_list = list(map(int, input().split())) getting = [0] * (N + 1) flg = False for i in range(N): b = b_list[i] getting[b] = i + 1 if flg and b_list[i - 1] != b - 1: flg = False if b == 1: flg = True if flg: start = b_list[-1] + 1 step = 0 for i in range(start, N + 1): if getting[i] > step: flg = False break step += 1 if flg: print(N - start + 1) exit() ans = 0 for i in range(1, N + 1): if getting[i] > i - 1 and ans < getting[i] - (i - 1): ans = getting[i] - (i - 1) print(N + ans) ```
output
1
74,223
19
148,447
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n cards in the pile are also given in the order from top to bottom. In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile. Nauuo wants to make the n numbered cards piled up in increasing order (the i-th card in the pile from top to bottom is the card i) as quickly as possible. Can you tell her the minimum number of operations? Input The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of numbered cards. The second line contains n integers a_1,a_2,…,a_n (0≤ a_i≤ n) — the initial cards in Nauuo's hands. 0 represents an empty card. The third line contains n integers b_1,b_2,…,b_n (0≤ b_i≤ n) — the initial cards in the pile, given in order from top to bottom. 0 represents an empty card. It is guaranteed that each number from 1 to n appears exactly once, either in a_{1..n} or b_{1..n}. Output The output contains a single integer — the minimum number of operations to make the n numbered cards piled up in increasing order. Examples Input 3 0 2 0 3 0 1 Output 2 Input 3 0 2 0 1 0 3 Output 4 Input 11 0 0 0 5 0 0 0 4 0 0 11 9 2 6 0 8 1 7 0 3 0 10 Output 18 Note Example 1 We can play the card 2 and draw the card 3 in the first operation. After that, we have [0,3,0] in hands and the cards in the pile are [0,1,2] from top to bottom. Then, we play the card 3 in the second operation. The cards in the pile are [1,2,3], in which the cards are piled up in increasing order. Example 2 Play an empty card and draw the card 1, then play 1, 2, 3 in order.
instruction
0
74,224
19
148,448
Tags: greedy, implementation Correct Solution: ``` from sys import stdin from collections import deque n = int(stdin.readline()) hand = [int(x) for x in stdin.readline().split()] deck = [int(x) for x in stdin.readline().split()] ind = {} for i,x in enumerate(deck): if x != 0: ind[x] = i offset = sorted([(ind[i]-i+2,i) for i in ind]) if not offset: print(n) elif not 1 in deck: print(max(offset[-1][0]+n, n)) else: i1 = deck.index(1) newD = deck[i1:] valid = True for x in range(len(newD)-1): if newD[x] > newD[x+1]: valid = False break if valid: v2 = True newOff = i1-n for o,x in offset: if x > -newOff and o > newOff: v2 = False break if v2: print(newOff+n) else: print(max(offset[-1][0]+n, n)) else: print(max(offset[-1][0]+n, n)) ```
output
1
74,224
19
148,449
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n cards in the pile are also given in the order from top to bottom. In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile. Nauuo wants to make the n numbered cards piled up in increasing order (the i-th card in the pile from top to bottom is the card i) as quickly as possible. Can you tell her the minimum number of operations? Input The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of numbered cards. The second line contains n integers a_1,a_2,…,a_n (0≤ a_i≤ n) — the initial cards in Nauuo's hands. 0 represents an empty card. The third line contains n integers b_1,b_2,…,b_n (0≤ b_i≤ n) — the initial cards in the pile, given in order from top to bottom. 0 represents an empty card. It is guaranteed that each number from 1 to n appears exactly once, either in a_{1..n} or b_{1..n}. Output The output contains a single integer — the minimum number of operations to make the n numbered cards piled up in increasing order. Examples Input 3 0 2 0 3 0 1 Output 2 Input 3 0 2 0 1 0 3 Output 4 Input 11 0 0 0 5 0 0 0 4 0 0 11 9 2 6 0 8 1 7 0 3 0 10 Output 18 Note Example 1 We can play the card 2 and draw the card 3 in the first operation. After that, we have [0,3,0] in hands and the cards in the pile are [0,1,2] from top to bottom. Then, we play the card 3 in the second operation. The cards in the pile are [1,2,3], in which the cards are piled up in increasing order. Example 2 Play an empty card and draw the card 1, then play 1, 2, 3 in order.
instruction
0
74,225
19
148,450
Tags: greedy, implementation Correct Solution: ``` from sys import stdin, exit input = stdin.readline n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) p = [0] * (n + 1) for i in a: p[i] = 0 for i, v in enumerate(b): p[v] = i + 1 ans = 0 if p[1] > 0: i = 2 while i <= n and p[i] == p[i - 1] + 1: i += 1 if p[i - 1] == n: j = i while j <= n and p[j] <= j - i: j += 1 if j == n + 1: print(p[1] - 1) exit(0) ans = max([p[i] - i + 1 + n for i in range(1, n + 1)]) print(ans) ```
output
1
74,225
19
148,451
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n cards in the pile are also given in the order from top to bottom. In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile. Nauuo wants to make the n numbered cards piled up in increasing order (the i-th card in the pile from top to bottom is the card i) as quickly as possible. Can you tell her the minimum number of operations? Input The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of numbered cards. The second line contains n integers a_1,a_2,…,a_n (0≤ a_i≤ n) — the initial cards in Nauuo's hands. 0 represents an empty card. The third line contains n integers b_1,b_2,…,b_n (0≤ b_i≤ n) — the initial cards in the pile, given in order from top to bottom. 0 represents an empty card. It is guaranteed that each number from 1 to n appears exactly once, either in a_{1..n} or b_{1..n}. Output The output contains a single integer — the minimum number of operations to make the n numbered cards piled up in increasing order. Examples Input 3 0 2 0 3 0 1 Output 2 Input 3 0 2 0 1 0 3 Output 4 Input 11 0 0 0 5 0 0 0 4 0 0 11 9 2 6 0 8 1 7 0 3 0 10 Output 18 Note Example 1 We can play the card 2 and draw the card 3 in the first operation. After that, we have [0,3,0] in hands and the cards in the pile are [0,1,2] from top to bottom. Then, we play the card 3 in the second operation. The cards in the pile are [1,2,3], in which the cards are piled up in increasing order. Example 2 Play an empty card and draw the card 1, then play 1, 2, 3 in order.
instruction
0
74,226
19
148,452
Tags: greedy, implementation Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) l = -1 r = n moment = [0] * (n + 1) max_post = 1 while b[(-max_post - 1)%n] != 0 and b[(-max_post - 1)%n ] + 1 == b[-max_post]: max_post += 1 if b[-max_post] != 1: max_post = 0 for i in range(n): moment[b[i]] = i + 1 m = -1 for i in range(max_post + 1, n + 1): m = max(m, moment[i] - i + max_post) m += 1 if m > 0: m = -2 for i in range(1, n + 1): m = max(m, moment[i] - i) m += 1 # print(m, n) print(m + n) else: print(max(0, m + n - max_post)) ```
output
1
74,226
19
148,453
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n cards in the pile are also given in the order from top to bottom. In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile. Nauuo wants to make the n numbered cards piled up in increasing order (the i-th card in the pile from top to bottom is the card i) as quickly as possible. Can you tell her the minimum number of operations? Input The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of numbered cards. The second line contains n integers a_1,a_2,…,a_n (0≤ a_i≤ n) — the initial cards in Nauuo's hands. 0 represents an empty card. The third line contains n integers b_1,b_2,…,b_n (0≤ b_i≤ n) — the initial cards in the pile, given in order from top to bottom. 0 represents an empty card. It is guaranteed that each number from 1 to n appears exactly once, either in a_{1..n} or b_{1..n}. Output The output contains a single integer — the minimum number of operations to make the n numbered cards piled up in increasing order. Examples Input 3 0 2 0 3 0 1 Output 2 Input 3 0 2 0 1 0 3 Output 4 Input 11 0 0 0 5 0 0 0 4 0 0 11 9 2 6 0 8 1 7 0 3 0 10 Output 18 Note Example 1 We can play the card 2 and draw the card 3 in the first operation. After that, we have [0,3,0] in hands and the cards in the pile are [0,1,2] from top to bottom. Then, we play the card 3 in the second operation. The cards in the pile are [1,2,3], in which the cards are piled up in increasing order. Example 2 Play an empty card and draw the card 1, then play 1, 2, 3 in order.
instruction
0
74,227
19
148,454
Tags: greedy, implementation Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) p = [0 for i in range(n+1)] for i in range(n): p[b[i]] = i + 1 if p[1]: i = 2 while i <= n and p[i] == p[1]+i-1: i += 1 if p[i-1] == n: j = i while j <= n and p[j] <= j-i: j += 1 if j > n: print(n-i+1) exit() ans = 0 for i in range(1, n+1): ans = max(ans, p[i] - i + 1 + n) print(ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
output
1
74,227
19
148,455