message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way.
instruction
0
94,617
13
189,234
Tags: combinatorics, dfs and similar, graphs, math, shortest paths, trees Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) MOD = 998244353 adjList = [] dist = [] ans = [] for _ in range(n): adjList.append([]) for _ in range(m): a,b = map(int,input().split()) adjList[a - 1].append(b - 1) adjList[b - 1].append(a - 1) for i in range(n): curDist = [-1] * n curDist[i] = 0 bfsQueue = [i] bfsIndex = 0 while len(bfsQueue) > bfsIndex: c = bfsQueue[bfsIndex] bfsIndex += 1 for elem in adjList[c]: if curDist[elem] == -1: curDist[elem] = curDist[c] + 1 bfsQueue.append(elem) dist.append(curDist) for _ in range(n): ans.append([0] * n) for i in range(n): for j in range(i, n): # Find shortest path between i and j isCovered = [False] * n isCovered[i] = True isCovered[j] = True jCpy = j flag = True while jCpy != i: cnt = 0 cntIndex = -1 for elem in adjList[jCpy]: if dist[i][elem] == dist[i][jCpy] - 1: cnt += 1 cntIndex = elem if cnt >= 2: flag = False break else: isCovered[cntIndex] = True jCpy = cntIndex if not flag: ans[i][j] = 0 ans[j][i] = 0 else: curAns = 1 for k in range(n): if isCovered[k]: continue cnt = 0 for elem in adjList[k]: if dist[i][elem] == dist[i][k] - 1 and dist[j][elem] == dist[j][k] - 1: cnt += 1 curAns *= cnt curAns %= MOD ans[i][j] = curAns ans[j][i] = curAns for elem in ans: print(" ".join(map(str,elem))) # 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
94,617
13
189,235
Provide tags and a correct Python 3 solution for this coding contest problem. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way.
instruction
0
94,618
13
189,236
Tags: combinatorics, dfs and similar, graphs, math, shortest paths, trees Correct Solution: ``` import io import os from collections import deque def solve(N, M, edges): graph = [[] for i in range(N)] for u, v in edges: graph[u].append(v) graph[v].append(u) def bfs(source): q = deque([source]) dist = [-1] * N dist[source] = 0 while q: node = q.popleft() d = dist[node] for nbr in graph[node]: if dist[nbr] == -1: q.append(nbr) dist[nbr] = d + 1 return dist dists = [bfs(u) for u in range(N)] MOD = 998244353 ans = [[0 for i in range(N)] for j in range(N)] for x in range(N): for y in range(x, N): onPath = 0 for i in range(N): if dists[x][i] + dists[y][i] == dists[x][y]: onPath += 1 numVertices = dists[x][y] + 1 # including x and y ways = 1 if onPath > numVertices: ways = 0 else: for i in range(N): if dists[x][i] + dists[y][i] != dists[x][y]: count = 0 for j in graph[i]: if ( dists[x][i] == dists[x][j] + 1 and dists[y][i] == dists[y][j] + 1 ): count += 1 ways = (ways * count) % MOD if not ways: break ans[x][y] = ways ans[y][x] = ways return "\n".join(" ".join(map(str, row)) for row in ans) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline TC = 1 for tc in range(1, TC + 1): N, M = [int(x) for x in input().split()] edges = [[int(x) - 1 for x in input().split()] for i in range(M)] # 0 indexed ans = solve(N, M, edges) print(ans) ```
output
1
94,618
13
189,237
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Submitted Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num):#排他的論理和の階乗 if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n): self.BIT=[0]*(n+1) self.num=n def query(self,idx): res_sum = 0 while idx > 0: res_sum += self.BIT[idx] idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): while idx <= self.num: self.BIT[idx] += x idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class Matrix(): mod=10**9+7 def set_mod(m): Matrix.mod=m def __init__(self,L): self.row=len(L) self.column=len(L[0]) self._matrix=L for i in range(self.row): for j in range(self.column): self._matrix[i][j]%=Matrix.mod def __getitem__(self,item): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item return self._matrix[i][j] def __setitem__(self,item,val): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item self._matrix[i][j]=val def __add__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]+other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __sub__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]-other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __mul__(self,other): if type(other)!=int: if self.column!=other.row: raise SizeError("sizes of matrixes are different") res=[[0 for j in range(other.column)] for i in range(self.row)] for i in range(self.row): for j in range(other.column): temp=0 for k in range(self.column): temp+=self._matrix[i][k]*other._matrix[k][j] res[i][j]=temp%Matrix.mod return Matrix(res) else: n=other res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)] return Matrix(res) def __pow__(self,m): if self.column!=self.row: raise MatrixPowError("the size of row must be the same as that of column") n=self.row res=Matrix([[int(i==j) for i in range(n)] for j in range(n)]) while m: if m%2==1: res=res*self self=self*self m//=2 return res def __str__(self): res=[] for i in range(self.row): for j in range(self.column): res.append(str(self._matrix[i][j])) res.append(" ") res.append("\n") res=res[:len(res)-1] return "".join(res) class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): 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): 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 def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import log,gcd input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) mod = 998244353 N = 2*10**3 g1 = [1]*(N+1) g2 = [1]*(N+1) inverse = [1]*(N+1) for i in range( 2, N + 1 ): g1[i]=( ( g1[i-1] * i ) % mod ) inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod ) g2[i]=( (g2[i-1] * inverse[i]) % mod ) inverse[0]=0 mod = 998244353 n,m = mi() edge = [[] for i in range(n)] Edge = [] for _ in range(m): a,b = mi() edge[a-1].append(b-1) edge[b-1].append(a-1) Edge.append((a-1,b-1)) dist = [[10**17 for j in range(n)] for i in range(n)] for s in range(n): deq = deque([s]) dist[s][s] = 0 while deq: v = deq.popleft() for nv in edge[v]: if dist[s][nv]==10**17: dist[s][nv] = dist[s][v] + 1 deq.append(nv) ans = [[0 for j in range(n)] for i in range(n)] for i in range(n): for j in range(n): tmp = [0 for i in range(n)] tmp_edge = [[] for i in range(n)] deg = [0 for i in range(n)] for k in range(m): a,b = Edge[k] if dist[i][a]==dist[i][b]+1 and dist[j][a]==dist[j][b]+1: tmp[a] += 1 elif dist[i][a]+1==dist[i][b] and dist[j][a]+1==dist[j][b]: tmp[b] += 1 elif dist[i][a]==dist[i][b]+1 and dist[j][a]+1==dist[j][b]: tmp_edge[b].append(a) deg[a] += 1 elif dist[i][a]+1==dist[i][b] and dist[j][a]==dist[j][b]+1: tmp_edge[a].append(b) deg[b] += 1 deq = deque([i]) res = [] while deq: v = deq.popleft() res.append(v) for nv in tmp_edge[v]: deg[nv] -= 1 if not deg[nv]: deq.append(nv) check = [v for v in res if tmp[v]==0] ttt = len(check) dp = [0 for i in range(n)] dp[i] = 1 for k in range(1,ttt): if dist[i][check[k]]==dist[i][check[k-1]]: dp[i] = 0 pos = 0 L = 0 for v in res: if check[pos] == v: for k in range(L,v): dp[k] = 0 L = v pos += 1 else: dp[v] *= inverse[tmp[v]] dp[v] %= mod for nv in tmp_edge[v]: dp[nv] += dp[v] dp[nv] %= mod res = dp[j] for k in range(n): if tmp[k]!=0: res *= tmp[k] res %= mod ans[i][j] = res for i in range(n): print(*ans[i]) ```
instruction
0
94,619
13
189,238
No
output
1
94,619
13
189,239
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Submitted Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num):#排他的論理和の階乗 if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n): self.BIT=[0]*(n+1) self.num=n def query(self,idx): res_sum = 0 while idx > 0: res_sum += self.BIT[idx] idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): while idx <= self.num: self.BIT[idx] += x idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class Matrix(): mod=10**9+7 def set_mod(m): Matrix.mod=m def __init__(self,L): self.row=len(L) self.column=len(L[0]) self._matrix=L for i in range(self.row): for j in range(self.column): self._matrix[i][j]%=Matrix.mod def __getitem__(self,item): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item return self._matrix[i][j] def __setitem__(self,item,val): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item self._matrix[i][j]=val def __add__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]+other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __sub__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]-other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __mul__(self,other): if type(other)!=int: if self.column!=other.row: raise SizeError("sizes of matrixes are different") res=[[0 for j in range(other.column)] for i in range(self.row)] for i in range(self.row): for j in range(other.column): temp=0 for k in range(self.column): temp+=self._matrix[i][k]*other._matrix[k][j] res[i][j]=temp%Matrix.mod return Matrix(res) else: n=other res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)] return Matrix(res) def __pow__(self,m): if self.column!=self.row: raise MatrixPowError("the size of row must be the same as that of column") n=self.row res=Matrix([[int(i==j) for i in range(n)] for j in range(n)]) while m: if m%2==1: res=res*self self=self*self m//=2 return res def __str__(self): res=[] for i in range(self.row): for j in range(self.column): res.append(str(self._matrix[i][j])) res.append(" ") res.append("\n") res=res[:len(res)-1] return "".join(res) class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): 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): 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 def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import log,gcd input = lambda :sys.stdin.buffer.readline() mi = lambda :map(int,input().split()) li = lambda :list(mi()) mod = 998244353 N = 2*10**3 g1 = [1]*(N+1) g2 = [1]*(N+1) inverse = [1]*(N+1) for i in range( 2, N + 1 ): g1[i]=( ( g1[i-1] * i ) % mod ) inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod ) g2[i]=( (g2[i-1] * inverse[i]) % mod ) inverse[0]=0 mod = 998244353 n,m = mi() edge = [[] for i in range(n)] Edge = [] for _ in range(m): a,b = mi() edge[a-1].append(b-1) edge[b-1].append(a-1) Edge.append((a-1,b-1)) dist = [[10**17 for j in range(n)] for i in range(n)] for s in range(n): deq = deque([s]) dist[s][s] = 0 while deq: v = deq.popleft() for nv in edge[v]: if dist[s][nv]==10**17: dist[s][nv] = dist[s][v] + 1 deq.append(nv) node_dist = [[j for j in range(n)] for i in range(n)] for i in range(n): node_dist[i].sort(key=lambda v:dist[i][v]) ans = [[0 for j in range(n)] for i in range(n)] for i in range(n): di = dist[i] for j in range(i,n): dj = dist[j] tmp = [0 for i in range(n)] tmp_edge = [[] for i in range(n)] deg = [0 for i in range(n)] for k in range(m): a,b = Edge[k] if di[a]==di[b]+1: if dj[a]==dj[b]+1: tmp[a] += 1 elif dj[a]+1==dj[b]: tmp_edge[b].append(a) deg[a] += 1 elif di[a]+1==di[b]: if dj[a]+1==dj[b]: tmp[b] += 1 elif dj[a]==dj[b]+1: tmp_edge[a].append(b) deg[b] += 1 deq = deque([i]) res = [] while deq: v = deq.popleft() res.append(v) for nv in tmp_edge[v]: deg[nv] -= 1 if not deg[nv]: deq.append(nv) res = [v for v in node_dist[i] if not tmp[v]] ttt = len(res) dp = [0 for i in range(n)] dp[i] = 1 for k in range(1,ttt): if di[res[k]]==di[res[k-1]]: dp[i] = 0 for v in res: if tmp[v]!=0: dp[v] *= inverse[tmp[v]] dp[v] %= mod for nv in tmp_edge[v]: dp[nv] += dp[v] dp[nv] %= mod res = dp[j] for k in range(n): if tmp[k]!=0: res *= tmp[k] res %= mod ans[i][j] = ans[j][i] = res % mod for i in range(n): print(*ans[i]) ```
instruction
0
94,620
13
189,240
No
output
1
94,620
13
189,241
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Submitted Solution: ``` import sys from sys import stdin from collections import deque tt = 1 for loop in range(tt): n,m = map(int,stdin.readline().split()) lis = [ [] for i in range(n) ] for i in range(m): a,b = map(int,stdin.readline().split()) a -= 1 b -= 1 lis[a].append(b) lis[b].append(a) able = [True] * n ans = [[0] * n for i in range(n)] mod = 998244353 for st in range(n): if able[st] and len(lis[st]) == 1: nums = [0] * n d = [float("inf")] * n d[st] = 0 q = deque([st]) while q: v = q.popleft() for nex in lis[v]: if d[nex] >= d[v] + 1: nums[nex] += 1 if d[nex] > d[v] + 1: d[nex] = d[v] + 1 q.append(nex) ed = 1 for i in range(n): if nums[i] > 1: ed *= nums[i] ed %= mod #print (nums,ed) for i in range(n): for j in range(n): if nums[i] <= 1 and nums[j] <= 1: ans[i][j] = ed ans[j][i] = ed for i in range(n): if nums[i] <= 1: able[i] = False for ii in ans: print (*ii) ```
instruction
0
94,621
13
189,242
No
output
1
94,621
13
189,243
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time. You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353. Input The first line contains two integers n, m (1 ≤ n ≤ 400, 0 ≤ m ≤ 600) — the number of vertices and the number of edges in the graph. The i-th of the next m lines contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i < b_i), representing an edge connecting a_i and b_i. It is guaranteed that all edges are distinct and the graph is connected. Output Print n lines, each consisting of n integers. The integer printed in the row i and the column j should be f(i,j) mod 998 244 353. Examples Input 4 4 1 2 2 3 3 4 1 4 Output 2 1 0 1 1 2 1 0 0 1 2 1 1 0 1 2 Input 8 9 1 2 1 3 1 4 2 7 3 5 3 6 4 8 2 3 3 4 Output 1 0 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 1 0 1 1 0 0 0 0 0 2 0 0 0 2 0 0 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 2 0 0 0 0 2 0 0 0 0 2 0 0 0 2 Note The following picture describes the first example. <image> The tree with red edges is a BFS tree rooted at both 1 and 2. <image> Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) MOD = 998244353 adjList = [] dist = [] ans = [] for _ in range(n): adjList.append([]) for _ in range(m): a,b = map(int,input().split()) adjList[a - 1].append(b - 1) adjList[b - 1].append(a - 1) for i in range(n): curDist = [-1] * n curDist[i] = 0 bfsQueue = [i] bfsIndex = 0 while len(bfsQueue) > bfsIndex: c = bfsQueue[bfsIndex] bfsIndex += 1 for elem in adjList[c]: if curDist[elem] == -1: curDist[elem] = curDist[c] + 1 bfsQueue.append(elem) dist.append(curDist) for i in range(n): ans.append([]) for j in range(n): # Find shortest path between i and j isCovered = [False] * n isCovered[i] = True isCovered[j] = True jCpy = j flag = True while jCpy != i: cnt = 0 cntIndex = -1 for elem in adjList[jCpy]: if dist[i][elem] == dist[i][jCpy] - 1: cnt += 1 cntIndex = elem if cnt >= 2: flag = False break else: isCovered[cntIndex] = True jCpy = cntIndex if not flag: ans[i].append(0) else: curAns = 1 for k in range(n): if isCovered[k]: continue cnt = 0 for elem in adjList[k]: if dist[i][elem] == dist[i][k] - 1 and dist[j][elem] == dist[j][k] - 1: cnt += 1 curAns = (curAns * cnt) % MOD if not curAns: break ans[i].append(curAns) for elem in ans: print(" ".join(map(str,elem))) # 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() ```
instruction
0
94,622
13
189,244
No
output
1
94,622
13
189,245
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory)
instruction
0
94,729
13
189,458
Tags: data structures, dfs and similar, trees Correct Solution: ``` class BIT(): """区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する add: 区間[begin, end)にvalを加える get_val: i番目(0-indexed)の値を求める """ def __init__(self, n): self.n = n self.bit = [0] * (n + 1) def get_val(self, i): i = i + 1 s = 0 while i <= self.n: s += self.bit[i] i += i & -i return s def _add(self, i, val): while i > 0: self.bit[i] += val i -= i & -i def add(self, i, j, val): self._add(j, val) self._add(i, -val) from collections import deque import sys input = sys.stdin.readline def eular_tour(tree: list, root: int): """頂点に対するオイラーツアーを行う posの部分木に区間[begin[pos], end[pos])が対応する """ n = len(tree) res = [] begin = [-1] * n end = [-1] * n visited = [False] * n visited[root] = True q = deque([root]) while q: pos = q.pop() res.append(pos) end[pos] = len(res) if begin[pos] == -1: begin[pos] = len(res) - 1 for next_pos in tree[pos]: if visited[next_pos]: continue else: visited[next_pos] = True q.append(pos) q.append(next_pos) return res, begin, end n, q = map(int, input().split()) init_cost = list(map(int, input().split())) info = [list(map(int, input().split())) for i in range(n-1)] query = [list(map(int, input().split())) for i in range(q)] tree = [[] for i in range(n)] for i in range(n-1): a, b = info[i] a -= 1 b -= 1 tree[a].append(b) tree[b].append(a) res, begin, end = eular_tour(tree, 0) even_res = [] odd_res = [] for i in range(len(res)): if i % 2 == 0: even_res.append(res[i]) else: odd_res.append(res[i]) even_bit = BIT(len(even_res)) odd_bit = BIT(len(odd_res)) for i in range(q): if query[i][0] == 1: _, pos, cost = query[i] pos -= 1 if begin[pos] % 2 == 0: even_bit.add(begin[pos] // 2, (end[pos] + 1) // 2, cost) odd_bit.add(begin[pos] // 2, end[pos] // 2, -cost) else: odd_bit.add(begin[pos] // 2, end[pos] // 2, cost) even_bit.add((begin[pos] + 1) // 2, end[pos] // 2, -cost) else: _, pos = query[i] pos -= 1 if begin[pos] % 2 == 0: ans = even_bit.get_val(begin[pos] // 2) else: ans = odd_bit.get_val(begin[pos] // 2) print(ans + init_cost[pos]) ```
output
1
94,729
13
189,459
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) Submitted Solution: ``` from sys import setrecursionlimit import threading setrecursionlimit(10 ** 9) threading.stack_size(67108864) __author__ = 'Pavel Mavrin' n, m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] nb = [[] for x in range(n)] for i in range(n - 1): x, y = [int(x) - 1 for x in input().split()] nb[x].append(y) nb[y].append(x) p = [0] * (2 * n) l = [0] * n r = [0] * n c = 0 def dfs(i, parent): global c global p l[i] = c p[c] = i c += 1 for j in nb[i]: if j != parent: dfs(j, i) p[c] = i c += 1 r[i] = c def make_tree(l, r): if r == l + 1: if l % 2 == 0: return [nonode, nonode, a[p[l]]] else: return [nonode, nonode, -a[p[l]]] else: m = (l + r) // 2 ll = make_tree(l, m) rr = make_tree(m, r) return [ll, rr, 0] def add(tree, l, r, a, b, val): if l >= b or a >= r: return if l >= a and r <= b: tree[2] += val else: m = (l + r) // 2 tree[0][2] += tree[2] tree[1][2] += tree[2] add(tree[0], l, m, a, b, val) add(tree[1], m, r, a, b, val) tree[2] = 0 def get(tree, l, r, i): if r == l + 1: return tree[2] m = (l + r) // 2 if i < m: return tree[2] + get(tree[0], l, m, i) else: return tree[2] + get(tree[1], m, r, i) #print([get(tree, 0, 2 * n, i) for i in range(2 * n)]) def main(): dfs(0, -1) nonode = [None, None, 0, 0] tree = make_tree(0, 2 * n) for i in range(m): z = [int(x) for x in input().split()] if z[0] == 1: if l[z[1] - 1] % 2 == 0: add(tree, 0, 2 * n, l[z[1] - 1], r[z[1] - 1], z[2]) else: add(tree, 0, 2 * n, l[z[1] - 1], r[z[1] - 1], -z[2]) # print([get(tree, 0, 2 * n, i) for i in range(2 * n)]) else: zz = get(tree, 0, 2 * n, l[z[1] - 1]) if l[z[1] - 1] % 2 == 0: print(zz) else: print(-zz) thread = threading.Thread(target=main) thread.start() ```
instruction
0
94,730
13
189,460
No
output
1
94,730
13
189,461
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) Submitted Solution: ``` n,m = map(int,input().split()) values = list(map(int,input().split())) rebra = [] for i in range(n-1): rebra.append(list(map(int,input().split()))) zapr = [] for i in range(m-1): z = list(map(int,input().split())) if z[0] == 1: v = -z[2] values[z[1]-1] -= v for j in range(z[1],n): for e in rebra: if e[0] == j: #2 values[e[1]-1] += v v = -v else: zapr.append(values[z[1]-1]) for i in zapr: print(i) ```
instruction
0
94,731
13
189,462
No
output
1
94,731
13
189,463
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) Submitted Solution: ``` n,m = map(int,input().split()) values = list(map(int,input().split())) rebra = [] for i in range(n-1): rebra.append(list(map(int,input().split()))) zapr = [] for i in range(m): z = list(map(int,input().split())) if z[0] == 1: v = -z[2] values[z[1]-1] -= v for j in range(z[1],n): for e in rebra: if e[0] == j: #2 values[e[1]-1] += v v = -v else: zapr.append(values[z[1]-1]) for i in zapr: print(i) ```
instruction
0
94,732
13
189,464
No
output
1
94,732
13
189,465
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) Submitted Solution: ``` n,m = map(int,input().split()) values = list(map(int,input().split())) rebra = [] for i in range(n-1): rebra.append(list(map(int,input().split()))) zapr = [] for i in range(m): z = list(map(int,input().split())) if z[0] == 1: v = -z[2] values[z[1]-1] -= v for j in range(z[1],n+1): for e in rebra: if e[0] == j: #2 values[e[1]-1] += v v = -v else: zapr.append(values[z[1]-1]) for i in zapr: print(i) ```
instruction
0
94,733
13
189,466
No
output
1
94,733
13
189,467
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7
instruction
0
94,750
13
189,500
Tags: dp, implementation, trees Correct Solution: ``` n,v,d=list(map(int,input().split())) dp=[[0]*2 for i in range(n+1)] dp[0][0]=1 for i in range(1,n+1): for k in range(1,min(i,v)+1): dp[i][0]+=dp[i-k][0] if k>=d: dp[i][1]+=dp[i-k][0] else: dp[i][1]+=dp[i-k][1] print(dp[n][1]%(10**9+7)) ```
output
1
94,750
13
189,501
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7
instruction
0
94,751
13
189,502
Tags: dp, implementation, trees Correct Solution: ``` mod = 10**9+7 def countWays(arr, m, N,d): count = [0 for i in range(N + 1)] count[0] = 1 for i in range(1, N + 1): for j in range(m): if (i >= arr[j]) and arr[j]<d: count[i] += count[i - arr[j]] count[i]%=mod return count[N] def countWays1(arr, m, N): count = [0 for i in range(N + 1)] count[0] = 1 for i in range(1, N + 1): for j in range(m): if (i >= arr[j]): count[i] += count[i - arr[j]] count[i]%=mod return count[N] n,k,d = map(int,input().split()) a = [i for i in range(1,k+1)] t1 = countWays(a,len(a),n,d) t2 = countWays1(a,len(a),n) print((t2-t1+mod)%mod) ```
output
1
94,751
13
189,503
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7
instruction
0
94,752
13
189,504
Tags: dp, implementation, trees Correct Solution: ``` def dp(curr, least, k, total, loc=0): global d if curr == total: return int(least == 0) if d[curr][int(least==0)] != -1: return d[curr][int(least==0)] for i in range(1, k+1): if curr+i > total: break loc+= dp(curr+i, 0 if least <= i else least, k, total) d[curr][int(least==0)] = loc % 1000000007 return loc % 1000000007 n, k, dd = map(int, input().split()) d = [[-1, -1] for i in range(n)] print(dp(0, dd, k, n)) ```
output
1
94,752
13
189,505
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7
instruction
0
94,753
13
189,506
Tags: dp, implementation, trees Correct Solution: ``` mod=int(1e9+7) n,k,d=map(int,input().split()) dp=[0 for i in range(n+k+1)] dp[0]=1 for i in range(n+1): for j in range(1,k+1): dp[i+j]+=dp[i] dp[i+j]%=mod dp2=[0 for i in range(n+k+1)] dp2[0]=1 for i in range(n+1): for j in range(1,d): dp2[i+j]+=dp2[i] dp[i+j]%=mod print((dp[n]-dp2[n]+mod)%mod) ```
output
1
94,753
13
189,507
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7
instruction
0
94,754
13
189,508
Tags: dp, implementation, trees Correct Solution: ``` n, k, d = [int(x) for x in input().split()] z = [[1], [1]] for i in range(1, n + 1): z[0].append(sum(z[0][max(i-d+1, 0):])) z[1].append(sum(z[1][max(i-k, 0):])) print((z[1][-1] - z[0][-1]) % (10**9+7)) ```
output
1
94,754
13
189,509
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7
instruction
0
94,755
13
189,510
Tags: dp, implementation, trees Correct Solution: ``` N,K,D=map(int,input().split()) mod=10**9+7 dpK=[0 for i in range(N+1)] dpK[0]=1 for i in range(1,N+1): for j in range(1,K+1): if i>=j: dpK[i]+=dpK[i-j] dpK[i]%=mod dp=[0 for i in range(N+1)] dp[0]=1 for i in range(1,N+1): for j in range(1,D): if i>=j: dp[i]+=dp[i-j] dp[i]%=mod ans=dpK[N]-dp[N] print(ans%mod) ```
output
1
94,755
13
189,511
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7
instruction
0
94,756
13
189,512
Tags: dp, implementation, trees Correct Solution: ``` n, k, d = map(int, input().split()) dp = [[0 for i in range(2)] for j in range(n + 10)] dp[0][0] = 1 MOD = int(1e9) + 7 for i in range(1, n + 1): for j in range(1, min(d - 1, n) + 1): dp[i][0] += dp[i - j][0] % MOD for j in range(1, min(d - 1, n) + 1): dp[i][1] += dp[i - j][1] % MOD for j in range(d, min(n, k) + 1): dp[i][1] += (dp[i - j][0] + dp[i - j][1]) % MOD print(dp[n][1] % MOD) ```
output
1
94,756
13
189,513
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7
instruction
0
94,757
13
189,514
Tags: dp, implementation, trees Correct Solution: ``` import sys from math import log2,floor,ceil,sqrt,gcd # import bisect # from collections import deque # sys.setrecursionlimit(7*10**4) Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 1000000007 n,k,d = Ri() no = [0]*(n+1) no[0] = 1 for i in range(1,n+1): for j in range(1,k+1): if j > i: break no[i]+=no[i-j] # no[i] = no[i]%MOD # print(no) nod = [0]*(n+1) nod[0] = 1 for i in range(1,n+1): for j in range(1,k+1): if j > i : break if j >= d : break nod[i]+=nod[i-j] # nod[i]%=MOD # print(nod) print((no[n]-nod[n])%MOD) ```
output
1
94,757
13
189,515
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions,statistics from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal from sys import stdout from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest sys.setrecursionlimit(111111) INF=999999999999999999999999 class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def main(): mod=1000000007 # InverseofNumber(mod) # InverseofFactorial(mod) # factorial(mod) starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") ###CODE tc = 1 for _ in range(tc): n,k,d=ria() coins=[int(x) for x in range(1,k+1)] x=n dp=[0]*1000005 dp[0]=1 mod=int(1e9)+7 for i in range(1,x+1): for j in coins: if j-i>0: break dp[i]=(dp[i]+dp[i-j])%mod total=(dp[x]) coins=[int(x) for x in range(1,d)] x=n dp=[0]*1000005 dp[0]=1 mod=int(1e9)+7 for i in range(1,x+1): for j in coins: if j-i>0: break dp[i]=(dp[i]+dp[i-j])%mod waste=dp[x] print((total-waste)%mod) #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) 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, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) 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() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main() ```
instruction
0
94,758
13
189,516
Yes
output
1
94,758
13
189,517
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` #!/usr/bin/env python3 import itertools, functools, math MOD = 1000000007 @functools.lru_cache(None) def dp(n, k, d, d_used=False): if n == d and not d_used: return 1 if n == 0: return 1 if n < d and not d_used: return 0 r = 0 for i in range(1, min(n+1, k+1)): r = (r + dp(n-i, k, d, d_used or i>=d))%MOD return r def solve(): n, k, d = map(int, input().split()) return dp(n, k, d) if __name__ == '__main__': print(solve()) ```
instruction
0
94,759
13
189,518
Yes
output
1
94,759
13
189,519
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` import functools import sys p = 10**9 + 7 line = input() tokens = line.split() n, k, d = int(tokens[0]), int(tokens[1]), int(tokens[2]) @functools.lru_cache(None) def f(s): if s == 0: return 1 total = 0 for w in range(1, k + 1): if w > s: break total += f(s - w) return total % p @functools.lru_cache(None) def g(s): if s == 0: return 1 total = 0 for w in range(1, min(d, k + 1)): if w > s: break total += g(s - w) return total % p print((f(n) - g(n)) % p) ```
instruction
0
94,760
13
189,520
Yes
output
1
94,760
13
189,521
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` n, k, d = list(map(int, input().split())) MOD = 10 ** 9 + 7 dp = {} def rec(remaining, flag = False): if remaining < 0: return 0 if remaining == 0 and flag == True: return 1 if (remaining, flag) in dp: return dp[(remaining, flag)] ans = 0 for i in range(1,k+1): if i <= remaining: ans += rec(remaining - i, flag | (i>=d)) ans %= MOD dp[(remaining, flag)] = ans return ans ans = rec(n) % MOD print(ans) ```
instruction
0
94,761
13
189,522
Yes
output
1
94,761
13
189,523
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` memo = {} tg,k,d = map(int,input().split()) def rec(n): if n in memo: return memo[n] ans = [0,0] for b in range(1, min(k,n)+1): if b == n: ans[b>=d]+=1 continue r = rec(n-b) ans[1]+=r[1] ans[b>=d]+=r[0] memo[n] = ans return ans print(rec(tg)[1]) ```
instruction
0
94,762
13
189,524
No
output
1
94,762
13
189,525
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` import sys sys.setrecursionlimit(100000) n, k, d = [int(x) for x in sys.stdin.readline().strip().split()] memo = {} m = 10**9 +7 def dp(n,k,d): if n in memo: return memo[n] if n==0: return 1 if n<0: return 0 s = 0 for i in range(1,k+1): if i>=d : s+=dp(n-i,k,0) elif n-i>=d: s+=dp(n-i,k,d) memo[n]=s return s print(dp(n,k,d)%m) ```
instruction
0
94,763
13
189,526
No
output
1
94,763
13
189,527
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush # from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time # import numpy as np starttime = time.time() # import numpy as np mod = int(pow(10, 9) + 7) mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] try: # sys.setrecursionlimit(int(pow(10,6))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass n,k,d=L() def func(n,A): @lru_cache def rec(s): # print(s) if s==0: return 1 if s<0: return 0 ans=0 for x in A: ans+=rec(s-x) ans%=mod return ans return rec(n) ans=func(n,[i for i in range(1,k+1)]) if d!=1: ans-=func(n,[i for i in range(1,d)]) print(ans) endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ```
instruction
0
94,764
13
189,528
No
output
1
94,764
13
189,529
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` n,k,d=map(int,input().split(" ")) dp=[[0,0] for i in range(n+1)] dp[0][0]=1 for i in range(1,n+1): for j in range(1,k+1): if(i-j<0): break if(j<d): dp[i][0]+=dp[i-j][0]%1000000007 dp[i][1]+=dp[i-j][1]%1000000007 else: dp[i][1]+=dp[i-j][0]%1000000007 dp[i][1]+=dp[i-j][1]%1000000007 print(dp[n][1]) ```
instruction
0
94,765
13
189,530
No
output
1
94,765
13
189,531
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image>
instruction
0
94,942
13
189,884
Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` n,k=list(map(int,input().strip().split(' '))) import math L=math.ceil((n-(k+1))/(k)) remain=(n-(k+1))%(k) if (n-(k+1))%(k)==0: remain+=k #print(L,remain,'L,remain') if remain%(k)==1: print(2*(L)+1) else: print(2*(L+1)) if 1==1: if n==2: print(1,2) else: temp=0 end=k+1 for j in range(2,k+1+1): print(1,j) if temp<remain: for p in range(0,L): if p==0: print(j,end+1) end+=1 else: print(end,end+1) end+=1 temp+=1 else: for p in range(0,L-1): if p==0: print(j,end+1) end+=1 else: print(end,end+1) end+=1 ```
output
1
94,942
13
189,885
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image>
instruction
0
94,943
13
189,886
Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` inp = [ int(x) for x in input().split() ] n = inp[0] k = inp[1] mainLen = (n-1) // k nodeLeft = (n-1) % k if nodeLeft == 0: print(mainLen*2) elif nodeLeft == 1: print(mainLen*2 + 1) else: print(mainLen*2 + 2) for i in range(1, n): if i <= k: print(str(n) + ' ' + str(i)) else: print(str(i-k) + ' ' + str(i)) ```
output
1
94,943
13
189,887
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image>
instruction
0
94,944
13
189,888
Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` import sys def main(): n,k = map(int,sys.stdin.readline().split()) a = n-k if a ==1: print(2) for i in range(k): print(1,i+2) elif a > k+1 : l = ((a-1)//k +1)*2 if (a-1)%k>1: print(l+2) elif (a-1)%k==1: print(l+1) else: print(l) c = 2 for i in range(k): print(1,c) for j in range(l//2-1): print(c,c+1) c+=1 if i<((a-1)%k): print(c,c+1) c+=1 c+=1 else: if a==2: print(3) else: print(4) c =2 for i in range(a-1): print(1,c) print(c, c+1) c+=2 for i in range(c,n+1): print(1,i) main() ```
output
1
94,944
13
189,889
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image>
instruction
0
94,945
13
189,890
Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` n, k = map(int, input().split()) div = (n - 1) // k rem = (n - 1) % k if rem == 0: print(div * 2) elif rem == 1: print(2 * div + 1) else: print(2 * (div + 1)) j = 2 rest = k - rem while rem > 0: print(1, j) for i in range(div): print(i + j, i + j + 1) j += (div + 1) rem -= 1 while rest > 0: print(1, j) for i in range(div - 1): print(i + j, i + j + 1) j += div rest -= 1 ```
output
1
94,945
13
189,891
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image>
instruction
0
94,946
13
189,892
Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` from sys import stdin, stdout from collections import deque def bfs(v): ans = 0 visit[v] = 1 queue = deque() queue.append((v, 0)) while (queue): v, dist = queue.popleft() ans = max(ans, dist) for u in vertices[v]: if not visit[u]: queue.append((u, dist + 1)) visit[u] = 1 return ans n, k = map(int, stdin.readline().split()) challengers = [] ans = [] for i in range(2, k + 2): ans.append((1, i)) challengers.append(i) n = n - k - 1 v = k + 2 for i in range(n // k): update = [] for u in challengers: update.append(v) ans.append((u, v)) v += 1 challengers = update[:] for u in challengers[:n % k]: ans.append((u, v)) v += 1 visit = [0 for i in range(v)] vertices = [[] for i in range(v)] for a, b in ans: vertices[a].append(b) vertices[b].append(a) stdout.write(str(bfs(v - 1)) + '\n') for a, b in ans: stdout.write(str(a) + ' ' + str(b) + '\n') ```
output
1
94,946
13
189,893
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image>
instruction
0
94,947
13
189,894
Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` n, k = map(int, input().split()) reb = n - 1 our = reb // k if reb % k == 0: eps = 0 elif reb % k == 1: eps = 1 else: eps = 2 print(our * 2 + eps) next = 2 big = reb % k for i in range(big): prev = 1 for j in range(our + 1): print(prev, next) prev = next next += 1 for i in range(k - big): prev = 1 for j in range(our): print(prev, next) prev = next next += 1 ```
output
1
94,947
13
189,895
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image>
instruction
0
94,948
13
189,896
Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` n,k = map(int,input().split()) n -= 1 val = n//k div = n%k i = 2 if div==0: print(val*2) elif div==1: print(val*2+1) else: print((val+1)*2) for a in range(k): print(1,i) for j in range(val-1): print(i,i+1) i+=1 i+=1 j = i-1 while(div): print(j,i) i+=1 j-=val div -= 1 ```
output
1
94,948
13
189,897
Provide tags and a correct Python 3 solution for this coding contest problem. Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints. Output In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them. Examples Input 3 2 Output 2 1 2 2 3 Input 5 3 Output 3 1 2 2 3 3 4 3 5 Note In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted. <image>
instruction
0
94,949
13
189,898
Tags: constructive algorithms, greedy, implementation, trees Correct Solution: ``` nodes, exits = [int(x) for x in input().split()] nonExits = nodes - exits nonE = list(range(exits + 1, nodes + 1)) #1 -> exits + 1 :: lopud #exits + 1 -> nodes + 1 :: mitte lopud nonStart = exits + 1 an = [] exitList = [] for i in range(1, exits + 1): exitList.append([i, i, 0]) if nonExits == 1: print(2) for i in range(2, nodes + 1): print(1, i) else: #maxDist = (nonExits + exits - 1) // exits while nonE: for item in exitList: if nonE: it = nonE.pop() an.append((item[1], it)) item[1] = it item[2] += 1 else: break for item in exitList: if item[2] == 0: an.append((item[0], nonStart)) for i in range(1, min(exits, nonExits)): an.append((exitList[0][1], exitList[i][1])) fix = 0 if len(exitList) > 2: if (exitList[2][2] == exitList[1][2] and exitList[2][2] == exitList[0][2]): fix = 1 print(exitList[0][2] + exitList[1][2] + 1 + fix) for i in an: print(i[0], i[1]) ```
output
1
94,949
13
189,899
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES
instruction
0
95,147
13
190,294
"Correct Solution: ``` import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) graph = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) def check(): stack = [0] checked = [False]*N need = [[] for _ in range(N)] Parent = [-1]*N while stack: p = stack.pop() if p >= 0: checked[p] = True stack.append(~p) for np in graph[p]: if not checked[np]: Parent[np] = p stack.append(np) else: p = ~p if len(need[p]) == 0: need[Parent[p]].append(A[p]) elif len(need[p]) == 1: if need[p][0] != A[p]: return False need[Parent[p]].append(A[p]) else: kmax = sum(need[p]) kmin = max(max(need[p]), (kmax+1)//2) if not kmin <= A[p] <= kmax: return False if p == 0 and kmax-2*(kmax-A[p]) != 0: return False need[Parent[p]].append(kmax-2*(kmax-A[p])) return True print("YES" if check() else "NO") ```
output
1
95,147
13
190,295
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES
instruction
0
95,148
13
190,296
"Correct Solution: ``` import sys sys.setrecursionlimit(10 ** 6) def dfs(v, p, aaa): if len(links[v]) == 1: return aaa[v] children = [] for u in links[v]: if u == p: continue result = dfs(u, v, aaa) if result == -1: return -1 children.append(result) if len(children) == 1: if aaa[v] != children[0]: return -1 return children[0] c_sum = sum(children) c_max = max(children) o_max = c_sum - c_max if o_max >= c_max: max_pairs = c_sum // 2 else: max_pairs = o_max min_remain = c_sum - max_pairs if not min_remain <= aaa[v] <= c_sum: return -1 return aaa[v] * 2 - c_sum def solve(n, aaa, links): if n == 2: return aaa[0] == aaa[1] # 葉でない頂点探し s = 0 while len(links[s]) == 1: s += 1 return dfs(s, -1, aaa) == 0 n = int(input()) aaa = list(map(int, input().split())) links = [set() for _ in range(n)] for line in sys.stdin: a, b = map(int, line.split()) a -= 1 b -= 1 links[a].add(b) links[b].add(a) print('YES' if solve(n, aaa, links) else 'NO') ```
output
1
95,148
13
190,297
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES
instruction
0
95,149
13
190,298
"Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10**8) N = int(input()) A = list(map(int,input().split())) AB = [tuple(map(int,input().split())) for i in range(N-1)] es = [[] for _ in range(N)] for a,b in AB: a,b = a-1,b-1 es[a].append(b) es[b].append(a) r = -1 for i in range(N): if len(es[i]) > 1: r = i break if r == -1: assert N==2 print('YES' if A[0]==A[1] else 'NO') exit() def dfs(v,p=-1): if len(es[v]) == 1: return A[v] s = mxc = 0 for to in es[v]: if to==p: continue c = dfs(to,v) s += c mxc = max(mxc,c) pair = s - A[v] ret = s - pair*2 if pair < 0 or ret < 0 or (mxc*2 > s and pair > s - mxc): print('NO') exit() return ret print('YES' if dfs(r)==0 else 'NO') ```
output
1
95,149
13
190,299
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES
instruction
0
95,150
13
190,300
"Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10**7) N = int(input()) A = [int(x) for x in input().split()] UV = [[int(x)-1 for x in row.split()] for row in sys.stdin.readlines()] if N == 2: x,y = A answer = 'YES' if x == y else 'NO' print(answer) exit() graph = [[] for _ in range(N)] for u,v in UV: graph[u].append(v) graph[v].append(u) def dfs(v,parent=None): x = A[v] if len(graph[v]) == 1: return x s = 0 for w in graph[v]: if w == parent: continue ret = dfs(w,v) if ret == None: return None if x < ret: return None s += ret if 2*x-s > s: return None if 2*x < s: return None return 2*x-s v=0 while len(graph[v]) == 1: v += 1 ret = dfs(v) bl = (ret == 0) answer = 'YES' if bl else 'NO' print(answer) ```
output
1
95,150
13
190,301
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES
instruction
0
95,151
13
190,302
"Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- def readln(ch): _res = list(map(int,str(input()).split(ch))) return _res n = int(input()) a = readln(' ') e = [set([]) for i in range(0,n+1)] for i in range(1,n): s = readln(' ') e[s[0]].add(s[1]) e[s[1]].add(s[0]) rt = 1 now = n v = [0 for i in range(0,n+1)] q = v[:] q[now] = rt v[rt] = 1 for i in range(1,n): s = q[n-i+1] for p in e[s]: if v[p] == 0: v[p] = 1 now = now - 1 q[now] = p res = 'YES' up = [0 for i in range(0,n+1)] for i in range(1,n+1): k = q[i] if len(e[k]) == 1: sum = a[k-1] else: sum = a[k-1] * 2 up[k] = sum for son in e[k]: up[k] = up[k] - up[son] if up[son] > a[k-1] and len(e[k]) > 1: res = 'NO' if up[k] < 0: res = 'NO' if len(e[k]) > 1 and up[k] > a[k-1]: res = 'NO' if up[rt] != 0 : res = 'NO' print(res) ```
output
1
95,151
13
190,303
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES
instruction
0
95,152
13
190,304
"Correct Solution: ``` def get_par(tree: list, root: int) -> list: """根付き木の頂点それぞれの親を求める""" n = len(tree) visited = [False] * n visited[root] = True par = [-1] * n stack = [root] while stack: v = stack.pop() for nxt_v in tree[v]: if visited[nxt_v]: continue visited[nxt_v] = True stack.append(nxt_v) par[nxt_v] = v return par def topological_sort(tree: list, root) -> list: """根付き木をトポロジカルソートする""" n = len(tree) visited = [False] * n visited[root] = True tp_sorted = [root] stack = [root] while stack: v = stack.pop() for nxt_v in tree[v]: if visited[nxt_v]: continue visited[nxt_v] = True stack.append(nxt_v) tp_sorted.append(nxt_v) return tp_sorted n = int(input()) a = list(map(int, input().split())) edges = [list(map(int, input().split())) for i in range(n - 1)] tree = [[] for i in range(n)] for u, v in edges: u -= 1 v -= 1 tree[u].append(v) tree[v].append(u) # rootには葉以外を選ぶ root = -1 for v in range(n): if len(tree[v]) != 1: root = v break # 頂点2つのときはrootを葉として選べない if root == -1: if a[0] == a[1]: print("YES") else: print("NO") exit() par = get_par(tree, root) tp_sorted = topological_sort(tree, root) stn_cnt = [[] for _ in range(n)] # 葉から探索 is_YES = True for v in tp_sorted[::-1]: if not stn_cnt[v]: par_v = par[v] stn_cnt[par_v].append(a[v]) continue sum_cnt = sum(stn_cnt[v]) max_cnt = max(stn_cnt[v]) if sum_cnt < a[v]: is_YES = False break cnt1 = 2 * a[v] - sum_cnt cnt2 = sum_cnt - a[v] if v == root and cnt1 != 0: is_YES = False break if cnt1 < 0: is_YES = False break if cnt2 < 0 or min(sum_cnt - max_cnt, sum_cnt // 2) < cnt2: is_YES = False break par_v = par[v] stn_cnt[par_v].append(cnt1) if is_YES: print("YES") else: print("NO") ```
output
1
95,152
13
190,305
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES
instruction
0
95,153
13
190,306
"Correct Solution: ``` import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") n = int(input()) a = list(map(int, input().split())) from collections import defaultdict ns = defaultdict(set) for i in range(n-1): u,v = map(int, input().split()) u -= 1 v -= 1 ns[u].add(v) ns[v].add(u) def sub(u, p): if len(ns[u])==1 and p in ns[u]: return a[u] ub = 0 mv = 0 msum = 0 for v in ns[u]: if p==v: continue val = sub(v, u) if val is None: return None mv = max(mv, val) msum += val lb = max(mv, msum//2) if not (lb<=a[u]<=msum): # print(u,lb, msum, mv) return None else: return a[u] - (msum-a[u]) if n==2: if a[0]==a[1]: print("YES") else: print("NO") else: if len(ns[0])>1: ans = sub(0, -1) else: ans = sub(list(ns[0])[0], -1) if ans is None or ans!=0: print("NO") else: print("YES") ```
output
1
95,153
13
190,307
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES
instruction
0
95,154
13
190,308
"Correct Solution: ``` def examA(): N = I() A = LI() ans = "YES" cur = 0 for a in A: if a%2==1: cur +=1 if cur%2==1: ans = "NO" print(ans) return def examB(): N = I() A = LI() ans = "YES" sumA = sum(A) oneA = (1+N)*N//2 if sumA%oneA!=0: ans = "NO" ope = sumA//oneA #各Aについて何回始点としたか二分探索 cur = 0 for i in range(N): now = ope - (A[i]-A[i-1]) if now%N!=0 or now<0: # print(now,i) ans = "NO" break cur += now//N if cur!=ope: ans = "NO" print(ans) return def examC(): N = I() A = LI() V = [[]for _ in range(N)] for i in range(N-1): a, b = LI() V[a-1].append(b-1) V[b-1].append(a-1) s = -1 for i,v in enumerate(V): if len(v)>1: s = i break if s==-1: if A[0]==A[1]: print("YES") else: print("NO") return def dfs(s,p): flag = 1 rep = 0 maxA = 0 for v in V[s]: if v==p: continue cur,next = dfs(v,s) if maxA<cur: maxA = cur rep += cur flag *= next if len(V[s])==1: return A[s],flag if (rep+1)//2>A[s] or rep<A[s] or maxA>A[s]: flag = 0 #print(s,rep) rep -= (rep-A[s])*2 return rep,flag rep,flag = dfs(s,-1) if rep!=0: flag = 0 if flag: print("YES") else: print("NO") return from decimal import Decimal as dec import sys,bisect,itertools,heapq,math,random from copy import deepcopy from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines def DI(): return dec(input()) def LDI(): return list(map(dec,sys.stdin.readline().split())) def I(): return int(input()) def LI(): return list(map(int,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,mod2,inf,alphabet,_ep mod = 10**9 + 7 mod2 = 998244353 inf = 1<<60 _ep = 10**(-16) alphabet = [chr(ord('a') + i) for i in range(26)] sys.setrecursionlimit(10**7) if __name__ == '__main__': examC() ```
output
1
95,154
13
190,309
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES Submitted Solution: ``` from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor from operator import mul from functools import reduce sys.setrecursionlimit(10 ** 9) INF = 10 ** 20 def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def I(): return int(sys.stdin.buffer.readline()) def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split() def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8') def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 10 ** 9 + 7 n = I() A = LI() graph = [[] for _ in range(n)] for u, v in LIR(n - 1): graph[u - 1] += [v - 1] graph[v - 1] += [u - 1] if n == 2: x, y = A answer = 'YES' if x == y else 'NO' print(answer) exit() def dfs(v, parent=None): x = A[v] if len(graph[v]) == 1: return x s = 0 for w in graph[v]: if w == parent: continue ret = dfs(w, v) if ret == None: return None if x < ret: print('NO') exit() s += ret if 2 * x - s > s: print('NO') exit() if 2 * x < s: print('NO') exit() return 2 * x - s v=0 while len(graph[v]) == 1: v += 1 if not dfs(v): print('YES') else: print('NO') ```
instruction
0
95,155
13
190,310
Yes
output
1
95,155
13
190,311
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES Submitted Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines n = int(readline()) a = [0] + list(map(int,readline().split())) data = list(map(int,read().split())) links = [[] for _ in range(n+1)] it = iter(data) for ai,bi in zip(it,it): links[ai].append(bi) links[bi].append(ai) links[0].append(1) links[1].append(0) tp = [] parent = [-1] * (n+1) stack = [0] while(stack): i = stack.pop() for j in links[i]: if(parent[i]==j): continue parent[j] = i stack.append(j) tp.append(j) tp = tp[::-1] come = [[] for _ in range(n+1)] for i in tp: if(len(come[i])==0): # print(i) # print(parent[i]) # print(a[i]) # print(come[parent[i]]) # print('--') come[parent[i]].append(a[i]) continue up = 2*a[i] - sum(come[i]) if(up < 0)|(max(up,max(come[i])) > a[i]): print('NO') exit() come[parent[i]].append(up) # print(come) if(len(come[1]) > 1)&(come[0][0] == 0): print('YES') elif(len(come[1]) == 1)&(come[0][0] == a[1]): print('YES') else: print('NO') ```
instruction
0
95,156
13
190,312
Yes
output
1
95,156
13
190,313
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES Submitted Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines N = int(readline()) A = (0, ) + tuple(map(int, readline().split())) m = map(int, read().split()) G = [[] for _ in range(N + 1)] for a, b in zip(m, m): G[a].append(b) G[b].append(a) def dfs_order(G, root=1): parent = [0] * (N + 1) order = [] stack = [root] while stack: x = stack.pop() order.append(x) for y in G[x]: if y == parent[x]: continue parent[y] = x stack.append(y) return parent, order def main(N, A, G): if N == 2: return A[1] == A[2] degree = [len(x) for x in G] root = degree.index(max(degree)) parent, order = dfs_order(G, root) # 上に伸ばすパスの個数 dp = [0] * (N + 1) for v in order[::-1]: if degree[v] == 1: dp[v] = A[v] continue p = parent[v] nums = [dp[w] for w in G[v] if v != p] x = sum(nums) y = max(nums) pair = x - A[v] if pair < 0 or pair > x - y or pair > x // 2: return False dp[v] = x - 2 * pair return dp[root] == 0 print('YES' if main(N, A, G) else 'NO') ```
instruction
0
95,157
13
190,314
Yes
output
1
95,157
13
190,315
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES Submitted Solution: ``` import sys sys.setrecursionlimit(10**6) N=int(input()) A=[int(i) for i in input().split()] G=[[] for i in range(N)] for i in range(N-1): a,b=map(int,input().split()) G[a-1].append(b-1) G[b-1].append(a-1) Visited=[False]*N B=[0]*N def B_map(x): C=[] S=0 Visited[x]=True for i in G[x]: if not Visited[i]: res=B_map(i) S+=res C.append(res) if len(C)==0: B[x]=A[x] elif len(C)==1: if A[x]==S: B[x]=S else: print("NO") exit() else: if 0<=S-A[x]<=min(S-max(C),S//2) and 2*A[x]-S>=0: B[x]=2*A[x]-S else: print("NO") exit() return B[x] B_map(0) if len(G[0])==1: if B[0]!=A[0]: print("NO") exit() else: if B[0]!=0: print("NO") exit() print("YES") ```
instruction
0
95,158
13
190,316
Yes
output
1
95,158
13
190,317
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES Submitted Solution: ``` import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") n = int(input()) a = list(map(int, input().split())) from collections import defaultdict ns = defaultdict(set) for i in range(n-1): u,v = map(int, input().split()) u -= 1 v -= 1 ns[u].add(v) ns[v].add(u) def sub(u, p): if len(ns[u])==1 and p in ns[u]: return a[u] ub = 0 mv = 0 msum = 0 for v in ns[u]: if p==v: continue val = sub(v, u) if val is None: return None mv = max(mv, val) msum += val lb = max(mv, msum//2) if not (lb<=a[u]<=msum): # print(u,lb, msum, mv) return None else: return a[u] - (msum-a[u]) if n==2: if a[0]==a[1]: print("YES") else: print("NO") else: if len(ns[0])>1: ans = sub(0, -1) else: ans = sub(list(ns[0])[0], -1) if ans is None or ans!=0: print("NO") else: print("YES") ```
instruction
0
95,159
13
190,318
No
output
1
95,159
13
190,319
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES Submitted Solution: ``` N = int(input()) A = [int(n) for n in input().split()] edges = {n+1:[] for n in range(N)} for n in range(N-1): a, b = [int(n) for n in input().split()] edges[a].append(b) edges[b].append(a) ends = [k for k, v in edges.items() if len(v)==1] roots = set() def search(past, p): dest = edges[p] if len(dest) == 1: past.append(p) roots.update(past) else : for i in range(dest): if dest[i] != past[-1]: past.append(p) search(past, dest[i]) for end in ends: search([end], edges[end][0]) # 全ての基底ベクトルはendsに収納されたので、このベクトルがはる空間にAが含まれるかどうかを検索したいだけの人生だった(敗北) ```
instruction
0
95,160
13
190,320
No
output
1
95,160
13
190,321
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them. Note that the operation cannot be performed if there is a vertex with no stone on the path. Constraints * 2 ≦ N ≦ 10^5 * 1 ≦ a_i,b_i ≦ N * 0 ≦ A_i ≦ 10^9 * The given graph is a tree. Input The input is given from Standard Input in the following format: N A_1 A_2 … A_N a_1 b_1 : a_{N-1} b_{N-1} Output If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`. Examples Input 5 1 2 1 1 2 2 4 5 2 3 2 1 3 Output YES Input 3 1 2 1 1 2 2 3 Output NO Input 6 3 2 2 2 2 2 1 2 2 3 1 4 1 5 4 6 Output YES Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def main(): n = I() a = LI() if n == 2: if a[0] == a[1]: return 'YES' return 'NO' e = collections.defaultdict(list) for _ in range(n-1): b,c = LI_() e[b].append(c) e[c].append(b) def f(c,p): t = [] ac = a[c] for b in e[c]: if b == p: continue res = f(b,c) if not res: return t.append(res) if not t: return ac tm = max(t) ts = sum(t) mi = tm*2 - ts tt = ac-(ts-ac) if not (mi <= ac <= ts): return return tt for i in range(n): if len(e[i]) == 1: continue r = f(i,-1) if r == 0: return 'YES' break return 'NO' print(main()) ```
instruction
0
95,161
13
190,322
No
output
1
95,161
13
190,323