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
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 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * The given graph is a tree. * All values in input are integers. Input Input is given from Standard Input in the following format: N Q a_1 b_1 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60 Submitted Solution: ``` import sys sys.setrecursionlimit(10**5+5) from collections import defaultdict,deque input = sys.stdin.readline def bfs(): q = deque([1]) while q: now = q.popleft() for nex,c,w in e[now]: if depth[nex]>= 0: continue depth[nex] = depth[now]+1 dis[nex] = dis[now]+w lca[0][nex] = now q.append(nex) def dfs1(now,p,count1,count2): for cou in dcount[now]: dcount[now][cou] = count1[cou] for wei in dweight[now]: dweight[now][wei] = count2[wei] for nex,c,w in e[now]: if nex == p: continue count1[c] += 1 count2[c] += w dfs1(nex,now,count1,count2) count1[c] -= 1 count2[c] -= w n,q = map(int,input().split()) e = [[] for i in range(n+1)] for i in range(n-1): a,b,c,d = map(int,input().split()) e[a].append((b,c,d)) e[b].append((a,c,d)) size = n+1 bitlen = 19 lca = [[0]*size for i in range(bitlen)] depth = [-1]*size dis = [-1]*size depth[1] = 0 dis[1] = 0 bfs() for i in range(1,bitlen): for j in range(1,size): if lca[i-1][j] > 0: lca[i][j] = lca[i-1][lca[i-1][j]] def search(x,y): if depth[x] > depth[y]: x,y = y,x for i in range(bitlen): if ((depth[y]-depth[x])>>i) & 1: y = lca[i][y] if x == y: return x for i in range(bitlen-1,-1,-1): if lca[i][x] != lca[i][y]: x = lca[i][x] y = lca[i][y] return lca[0][x] Q = [] dcount = defaultdict(lambda : defaultdict(int)) dweight = defaultdict(lambda : defaultdict(int)) for i in range(q): x,y,u,v = map(int,input().split()) a = search(u,v) dcount[u][x] = 0 dcount[v][x] = 0 dcount[a][x] = 0 dweight[u][x] = 0 dweight[v][x] = 0 dweight[a][x] = 0 Q.append((x,y,u,v,a)) dfs1(1,0,defaultdict(int),defaultdict(int)) for x,y,u,v,a in Q: cal = dis[u]+dis[v]-2*dis[a] cal += y*(dcount[u][x]+dcount[v][x]-2*dcount[a][x]) - dweight[u][x]-dweight[v][x]+2*dweight[a][x] print(cal) ```
instruction
0
53,712
13
107,424
Yes
output
1
53,712
13
107,425
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 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * The given graph is a tree. * All values in input are integers. Input Input is given from Standard Input in the following format: N Q a_1 b_1 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60 Submitted Solution: ``` # ABC133 オイラーツアー import sys from collections import defaultdict readline = sys.stdin.readline N, Q = map(int, readline().split()) vs = set() def dfs_w(v, d): S, F, depth, depthh = [], [None]+[0]*N, [-1] + [0]*N, [0] + [0]*N mmn, msn, iin = [[0] for _ in range(N)], [[0] for _ in range(N)], [[0] for _ in range(N)] pvs, stack, path = set(), [(1, 0, 0)], [0] # dfs while版 while True: if len(stack) == 0: break v, cc, dpd = stack.pop() if v > 0: parent = path[-1] path.append(v) pvs.add(v) vs.add(v) F[v] = len(S) depth[v], depthh[v] = depth[parent] + 1, depthh[parent] + dpd mmn[cc].append(mmn[cc][-1]+1) msn[cc].append(msn[cc][-1]+dpd) iin[cc].append(len(S)) S.append(v) for u, ucc, udpd in d[v]: if u in pvs: continue # 閉路あり for i, c in enumerate(path): if c == u: break return path[i+1:] + [u] if u in vs: continue stack += [(-v, ucc, udpd), (u, ucc, udpd)] else: pvs.remove(path[-1]) path.pop() mmn[cc].append(mmn[cc][-1]-1) msn[cc].append(msn[cc][-1]-dpd) iin[cc].append(len(S)) S.append(v) return S, F, depth, depthh, mmn, msn, iin class SegTree: def __init__(self, init_val, n, ide_ele, seg_func): self.segfunc = seg_func self.num = 2**(n-1).bit_length() self.ide_ele = ide_ele self.seg=[self.ide_ele]*2*self.num for i in range(n): self.seg[i+self.num-1]=init_val[i] for i in range(self.num-2,-1,-1) : self.seg[i]=self.segfunc(self.seg[2*i+1],self.seg[2*i+2]) def update(self, k, x): k += self.num-1 self.seg[k] = x while k+1: k = (k-1)//2 self.seg[k] = self.segfunc(self.seg[k*2+1],self.seg[k*2+2]) def query(self, p, q): if q<=p: return self.ide_ele p += self.num-1 q += self.num-2 res=self.ide_ele while q-p>1: if p&1 == 0: res = self.segfunc(res,self.seg[p]) if q&1 == 1: res = self.segfunc(res,self.seg[q]) q -= 1 p = p//2 q = (q-1)//2 if p == q: res = self.segfunc(res,self.seg[p]) else: res = self.segfunc(self.segfunc(res,self.seg[p]),self.seg[q]) return res def bsearch(ll, target, min_i, max_i): # l[index] <= target < l[index+1] となるindexを返す if ll[max_i] <= target: return max_i if target < ll[min_i]: return None index = len(ll)//2 while True: if ll[index] <= target: if target < ll[index+1]: return index index, min_i = (index+1 + max_i)//2, index+1 continue index, max_i = (index-1 + min_i)//2, index-1 def process(): G = [set() for _ in range(N+1)] for _ in range(N-1): a, b, c, d = map(int, readline().split()) G[a].add((b,c,d)) G[b].add((a,c,d)) S, F, depth, depthh, mmn, msn, iin = dfs_w(1, G) stree = SegTree([(depth[abs(v)], i) for i, v in enumerate(S)], len(S), (N, None), min) for _ in range(Q): x, y, u, v = map(int, readline().split()) fu, fv = sorted([F[u], F[v]]) cc = abs(S[stree.query(fu, fv+1)[1]]) r = depthh[u] + depthh[v] - 2*depthh[cc] index = bsearch(iin[x], F[u], 0, len(iin[x])-1) r += mmn[x][index] * y - msn[x][index] index = bsearch(iin[x], F[v], 0, len(iin[x])-1) r += mmn[x][index] * y - msn[x][index] index = bsearch(iin[x], F[cc], 0, len(iin[x])-1) r -= 2 * (mmn[x][index] * y - msn[x][index]) print(r) if __name__ == '__main__': process() ```
instruction
0
53,713
13
107,426
Yes
output
1
53,713
13
107,427
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 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * The given graph is a tree. * All values in input are integers. Input Input is given from Standard Input in the following format: N Q a_1 b_1 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60 Submitted Solution: ``` import sys sys.setrecursionlimit(10**5+5) from collections import defaultdict,deque input = sys.stdin.readline class LCA: def __init__(self,n): self.size = n+1 self.bitlen = n.bit_length() self.lca = [[0]*self.size for i in range(self.bitlen)] self.depth = [-1]*self.size self.dis = [-1]*self.size self.depth[1] = 0 self.dis[1] = 0 def make(self,root): q = deque([root]) while q: now = q.popleft() for nex,c,w in e[now]: if self.depth[nex]>= 0: continue self.depth[nex] = self.depth[now]+1 self.dis[nex] = self.dis[now]+w self.lca[0][nex] = now q.append(nex) for i in range(1,self.bitlen): for j in range(self.size): if self.lca[i-1][j] > 0: self.lca[i][j] = self.lca[i-1][self.lca[i-1][j]] def search(self,x,y): dx = self.depth[x] dy = self.depth[y] if dx < dy: x,y = y,x dx,dy = dy,dx dif = dx-dy while dif: s = dif & (-dif) x = self.lca[s.bit_length()-1][x] dif -= s while x != y: j = 0 while self.lca[j][x] != self.lca[j][y]: j += 1 if j == 0: return self.lca[0][x] x = self.lca[j-1][x] y = self.lca[j-1][y] return x n,q = map(int,input().split()) e = [[] for i in range(n+1)] for i in range(n-1): a,b,c,d = map(int,input().split()) e[a].append((b,c,d)) e[b].append((a,c,d)) lca = LCA(n) lca.make(1) Q = [[] for i in range(n+1)] ans = [] for i in range(q): x,y,u,v = map(int,input().split()) a = lca.search(u,v) ans.append(lca.dis[u]+lca.dis[v]-2*lca.dis[a]) Q[u].append((x,y,i,1)) Q[v].append((x,y,i,1)) Q[a].append((x,y,i,-2)) count = defaultdict(int) weight = defaultdict(int) def dfs1(now,p): for x,y,ind,z in Q[now]: ans[ind] += z*(y*count[x]-weight[x]) for nex,c,w in e[now]: if nex == p: continue count[c] += 1 weight[c] += w dfs1(nex,now) count[c] -= 1 weight[c] -= w dfs1(1,0) for i in ans: print(i) ```
instruction
0
53,714
13
107,428
Yes
output
1
53,714
13
107,429
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 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * The given graph is a tree. * All values in input are integers. Input Input is given from Standard Input in the following format: N Q a_1 b_1 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60 Submitted Solution: ``` # -*- coding: utf-8 -*- import sys from collections import defaultdict sys.setrecursionlimit(10**9) INF=10**18 MOD=10**9+7 input=lambda: sys.stdin.readline().rstrip() YesNo=lambda b: bool([print('Yes')] if b else print('No')) YESNO=lambda b: bool([print('YES')] if b else print('NO')) int1=lambda x:int(x)-1 N,Q=map(int,input().split()) edge=[[] for _ in range(N)] for _ in range(N-1): a,b,c,d=map(int1,input().split()) d+=1 edge[a].append((b,c,d)) edge[b].append((a,c,d)) U=defaultdict(list) V=defaultdict(list) Query=[] for i in range(Q): x,y,u,v=map(int1,input().split()) Query.append((x,y,u,v)) y+=1 U[u].append((x,y,i)) V[v].append((x,y,i)) S=[0]*(2*N-1) def EulerTour(start,n,edges): used=[False]*n et=[] left=[-1]*n right=[-1]*n depth=[] stack=[(start,-1,-1)] cur_depth=-1 while stack: v,c,d=stack.pop() if et: S[len(et)]=S[len(et)-1]+d if v>=0: used[v]=True cur_depth+=1 left[v]=right[v]=len(et) et.append(v) depth.append(cur_depth) for nv,c,d in edges[v]: if not used[nv]: stack.append((~v,c,-d)) stack.append((nv,c,d)) else: cur_depth-=1 right[~v]=len(et) et.append(~v) depth.append(cur_depth) return et,left,depth et,left,depth=EulerTour(0,N,edge) class SegmentTree: def __init__(self,n,segfunc,ide_ele): self.segfunc=segfunc self.ide_ele=ide_ele self.num=2**(n-1).bit_length() self.dat=[ide_ele]*2*self.num def init(self,iter): for i in range(len(iter)): self.dat[i+self.num]=iter[i] for i in range(self.num-1,0,-1): self.dat[i]=self.segfunc(self.dat[i*2],self.dat[i*2+1]) def update(self,k,x): k+=self.num self.dat[k]=x while k: k//=2 self.dat[k]=self.segfunc(self.dat[k*2],self.dat[k*2+1]) def query(self,p,q): if q<=p: return self.ide_ele p+=self.num q+=self.num-1 res=self.ide_ele while q-p>1: if p&1==1: res=self.segfunc(res,self.dat[p]) if q&1==0: res=self.segfunc(res,self.dat[q]) q-=1 p=(p+1)//2 q=q//2 if p==q: res=self.segfunc(res,self.dat[p]) else: res=self.segfunc(self.segfunc(res,self.dat[p]),self.dat[q]) return res s=SegmentTree(2*N-1,lambda a,b:min(a,b,key=lambda t:t[0]),(INF,INF)) for i in range(2*N-1): s.update(i,(depth[i],i)) LCA=defaultdict(list) LLCA=[-1]*Q for i,(x,y,u,v) in enumerate(Query): p,q=min(left[u],left[v]),max(left[u],left[v])+1 res=s.query(p,q) LCA[et[res[1]]].append((x,y,i)) LLCA[i]=res[1] diff=[0]*Q def EulerTour2(start,n,edges): used=[False]*n et=[] left=[-1]*n right=[-1]*n depth=[] stack=[(start,-1,-1)] cur_depth=-1 col=[[0,0] for _ in range(N)] while stack: v,c,d=stack.pop() if v>=0: col[c][0]+=d col[c][1]+=1 used[v]=True cur_depth+=1 left[v]=right[v]=len(et) et.append(v) depth.append(cur_depth) for nv,c,d in edges[v]: if not used[nv]: stack.append((~v,c,-d)) stack.append((nv,c,d)) else: col[c][0]+=d col[c][1]-=1 cur_depth-=1 right[~v]=len(et) et.append(~v) depth.append(cur_depth) while LCA[v]: qc,qd,qi=LCA[v].pop() diff[qi]-=(col[qc][0]-col[qc][1]*qd)*2 while U[v]: qc,qd,qi=U[v].pop() diff[qi]+=col[qc][0]-col[qc][1]*qd while V[v]: qc,qd,qi=V[v].pop() diff[qi]-=col[qc][0]-col[qc][1]*qd return EulerTour2(0,N,edge) for i,(x,y,u,v) in enumerate(Query): print(S[left[v]]+S[left[u]]-S[LLCA[i]]*2+diff[i]) ```
instruction
0
53,715
13
107,430
No
output
1
53,715
13
107,431
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 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * The given graph is a tree. * All values in input are integers. Input Input is given from Standard Input in the following format: N Q a_1 b_1 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60 Submitted Solution: ``` import sys input=lambda :sys.stdin.readline().rstrip() sys.setrecursionlimit(10**8) class LCA(object): def __init__(self, to, root=0): self.__n = len(to) self.__to = to self.__logn = (self.__n - 1).bit_length() self.__depth = [-1] * self.__n self.__dist = [-1] * self.__n self.__depth[root] = 0 self.__dist[root] = 0 self.__parents = [[-1] * self.__n for _ in range(self.__logn)] self.__dfs(root) self.__doubling() def __dfs(self, v): for u, c, d in self.__to[v]: if self.__depth[u] != -1: continue self.__parents[0][u] = v self.__depth[u] = self.__depth[v] + 1 self.__dist[u] = self.__dist[v] + d self.__dfs(u) def __doubling(self): for i in range(1, self.__logn): for v in range(self.__n): if self.__parents[i - 1][v] == -1: continue self.__parents[i][v] = \ self.__parents[i - 1][self.__parents[i - 1][v]] @property def depth(self): return self.__depth @property def dist(self): return self.__dist def get(self, u, v): dd = self.__depth[v] - self.__depth[u] if dd < 0: u, v = v, u dd *= -1 for i in range(self.__logn): if dd & (2 ** i): v = self.__parents[i][v] if v == u: return v for i in range(self.__logn - 1, -1, -1): pu = self.__parents[i][u] pv = self.__parents[i][v] if pu != pv: u, v = pu, pv return self.__parents[0][u] def resolve(): n, q = map(int, input().split()) to = [[] for _ in range(n)] for _ in range(n-1): a, b, c, d = map(int, input().split()) a -= 1 b -= 1 to[a].append((b, c, d)) to[b].append((a, c, d)) G = LCA(to) Query = [[] for _ in range(n)] for i in range(q): # idx, color, mag, coef x, y, u, v = map(int, input().split()) u -= 1 v -= 1 c = G.get(u, v) Query[u].append((i, x, y, 1)) Query[v].append((i, x, y, 1)) Query[c].append((i, x, y, -2)) ans = [0] * q S = [[0, 0] for _ in range(n)] def dfs(v, p=-1): for idx, color, mag, coef in Query[v]: x = G.dist[v] x -= S[color][1] x += mag * S[color][0] ans[idx] += x * coef for nv, color, d in to[v]: if nv == p: continue S[color][0] += 1 S[color][1] += d dfs(nv, v) S[color][0] -= 1 S[color][1] -= d dfs(0) print(*ans, sep="\n") resolve() ```
instruction
0
53,716
13
107,432
No
output
1
53,716
13
107,433
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 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * The given graph is a tree. * All values in input are integers. Input Input is given from Standard Input in the following format: N Q a_1 b_1 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60 Submitted Solution: ``` import sys from collections import defaultdict sys.setrecursionlimit(10**7) readline = sys.stdin.readline write = sys.stdout.write N, Q = map(int, readline().split()) G = [] g = defaultdict(list) dp = {} cdd = {} for v in range(N-1): a, b, c, d = map(int, readline().split()) a, b = a-1, b-1 g[a].append(b) g[b].append(a) dp["{}-{}".format(min(a,b), max(a,b))] = d cdd["{}-{}".format(min(a,b), max(a,b))] = c cc = set() for i in range(N): cc.add(i) G.append([]) for vv in g[i]: if vv not in cc: G[i].append(vv) S = [] F = [0]*N depth = [0]*N depthh = [0]*N vn = [[] for _ in range(N)] sn = [[] for _ in range(N)] iin = [[] for _ in range(N)] aii = [] w2i = {} ii = 0 def dfs(bb, v, d, dd, cc, dpd): global ii F[v] = len(S) depth[v] = d depthh[v] = dd S.append(v) vn[cc].append(1) sn[cc].append(dpd) iin[cc].append(v) aii.append(v) w2i[v] = ii ii += 1 for w in G[v]: nvn = cdd["{}-{}".format(min(v,w), max(v,w))] dpd = dp["{}-{}".format(min(v,w), max(v,w))] dfs(v, w, d+1, dd+dpd, nvn, dpd) S.append(v) vn[nvn].append(-1) sn[nvn].append(-dpd) iin[nvn].append(-w) aii.append(-w) w2i[-w] = ii ii += 1 dfs(None, 0, 0, 0, 0,0) #print(S) #print(vn) #print(sn) #print(iin) #print(aii) #print(w2i) from itertools import accumulate mmn = [] lnc = [] for vvv in vn: lnc.append(len(vvv)) mmn.append(list(accumulate(vvv))) msn = [] for vvv in sn: msn.append(list(accumulate(vvv))) INF = (N, None) M = 2*N M0 = 2**(M-1).bit_length() data = [INF]*(2*M0) for i, v in enumerate(S): data[M0-1+i] = (depth[v], i) for i in range(M0-2, -1, -1): data[i] = min(data[2*i+1], data[2*i+2]) def _query(a, b): yield INF a += M0; b += M0 while a < b: if b & 1: b -= 1 yield data[b-1] if a & 1: yield data[a-1] a += 1 a >>= 1; b >>= 1 def query(u, v): fu = F[u]; fv = F[v] if fu > fv: fu, fv = fv, fu return S[min(_query(fu, fv+1))[1]] def b_s(ll, mm, ms, ind, lw, hw, target_i, lncc): return 0, 0 if w2i[ll[ind]] <= target_i: if ind+1 >= len(ll): return 0, 0 if target_i < w2i[ll[ind+1]]: return (mm[ind], ms[ind]) return b_s(ll, mm, ms, (ind+1 + hw)//2, ind+1, hw, target_i, lncc) elif w2i[ll[ind]] > target_i: return b_s(ll, mm, ms, (ind + lw)//2, lw, ind-1, target_i, lncc) return 0, 0 def iro(u, v, cc, x, y): if w2i[u] < w2i[iin[x][0]]: u_n, u_d = 0, 0 else: u_n, u_d = b_s(iin[x], mmn[x], msn[x], (lnc[x]-1)//2, 0, lnc[x]-1, w2i[u], lnc[x]-1) if w2i[v] < w2i[iin[x][0]]: v_n, v_d = 0, 0 else: v_n, v_d = b_s(iin[x], mmn[x], msn[x], (lnc[x]-1)//2, 0, lnc[x]-1, w2i[v], lnc[x]-1) if w2i[cc] < w2i[iin[x][0]]: c_n, c_d = 0, 0 else: c_n, c_d = b_s(iin[x], mmn[x], msn[x], (lnc[x]-1)//2, 0, lnc[x]-1, w2i[cc], lnc[x]-1) return (u_n + v_n - 2 * (c_n)) * y - (u_d + v_d - 2 * (c_d)) #x = 2 #u_n, u_d = b_s(iin[x], mmn[x], msn[x], (lnc[x]-1)//2, 0, lnc[x]-1, w2i[2], lnc[x]-1) #print(u_n, u_d) #sys.exit() for q in range(Q): x, y, u, v = map(int, readline().split()) u, v = u-1, v-1 cc = query(u, v) diff = 0 if lnc[x] == 0: diff = 0 else: diff = iro(u, v, cc, x, y) # print("query, col : {} v_ind : {}".format(x, v), b_s(iin[x], mmn[x], msn[x], (lnc[x]-1)//2, 0, lnc[x]-1, w2i[v], lnc[x]-1)) print(depthh[u] + depthh[v] - 2*depthh[cc] + diff) ```
instruction
0
53,717
13
107,434
No
output
1
53,717
13
107,435
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 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * The given graph is a tree. * All values in input are integers. Input Input is given from Standard Input in the following format: N Q a_1 b_1 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60 Submitted Solution: ``` class Node: def __init__(self, v): self.value = v self.depth = None self.parent = None def root(node): w = node r = set() while w.parent is not None: r.add(w.parent) w = w.parent return r N, Q = list(map(int, input().split())) color, distance = {}, {} nodes = {v: Node(v) for v in range(1, N + 1)} links = {i: set() for i in range(1, N + 1)} for _ in range(N - 1): a, b, c, d = list(map(int, input().split())) if a > b: a, b = b, a if c in color: color[c].add((a, b)) else: color[c] = {(a, b)} distance[(a, b)] = d links[a].add(nodes[b]) links[b].add(nodes[a]) q = [list(map(int, input().split())) for _ in range(Q)] def link_distance(x, y, i, j): if i > j: i, j = j, i if x in color and (i, j) in color[x]: return y else: return distance[(i, j)] # nodeにリンクを張る。baseは1 parents = [nodes[1]] while True: next_parents = set() for parent in parents: children = links[parent.value] next_parents |= children for child in children: child.parent = parent links[child.value].remove(parent) if len(next_parents) == 0: break parents = next_parents for x, y, u, v in q: node1, node2 = nodes[u], nodes[v] if (u, v) in distance: print(link_distance(x, y, u, v)) continue root1, root2 = root(node1), root(node2) root1, root2 = root1 - root2, root2 - root1 d = 0 w = node1 for r in root1: d += link_distance(x, y, w.value, r.value) w = r if node1 in root2: root2.remove(node1) else: r = w.parent d += link_distance(x, y, w.value, r.value) w = r for r in root2: d += link_distance(x, y, w.value, r.value) w = r d += link_distance(x, y, node2.value, node2.parent.value) print(d) ```
instruction
0
53,718
13
107,436
No
output
1
53,718
13
107,437
Provide a correct Python 3 solution for this coding contest problem. Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i. He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subset of the edges such that any vertex can be reached from at least one of the vertices S_i or T_i by traversing chosen edges. For each round, find the minimum possible total weight of the edges chosen by Takahashi. Constraints * 1 ≦ N ≦ 4,000 * 1 ≦ M ≦ 400,000 * 1 ≦ Q ≦ 100,000 * 1 ≦ a_i,b_i,S_i,T_i ≦ N * 1 ≦ c_i ≦ 10^{9} * a_i \neq b_i * S_i \neq T_i * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Q S_1 T_1 S_2 T_2 : S_Q T_Q Output Print Q lines. The i-th line should contain the minimum possible total weight of the edges chosen by Takahashi. Examples Input 4 3 1 2 3 2 3 4 3 4 5 2 2 3 1 4 Output 8 7 Input 4 6 1 3 5 4 1 10 2 4 6 3 2 2 3 4 5 2 1 3 1 2 3 Output 8
instruction
0
53,799
13
107,598
"Correct Solution: ``` import sys input = sys.stdin.readline from operator import itemgetter from collections import deque class Unionfindtree: def __init__(self, number): self.par = [i for i in range(number)] self.rank = [0] * (number) def find(self, x): # 親を探す if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): # x,yを繋げる px = self.find(x) py = self.find(y) if px == py: return if self.rank[px] < self.rank[py]: self.par[px] = py else: self.par[py] = px if self.rank[px] == self.rank[py]: self.rank[px] += 1 def connect(self, x, y): # 親が同じかみる return self.find(x) == self.find(y) N,M=map(int,input().split()) table=[[int(i) for i in input().split()]for i in range(M)] Q=int(input()) query=[[int(i) for i in input().split()]for i in range(Q)] table = sorted(table,key=itemgetter(2)) if N<3: for a,b in query: print(0) sys.exit() T=Unionfindtree(N) sear=Unionfindtree(2*N-1) ans=0 value=[0]*(N+N-1) dp=[[0]*(2*N-1) for i in range(16)] table2=[[] for i in range(2*N-1)] s=0 for i in range(M): a,b,c=table[i] a,b=a-1,b-1 if not T.connect(a,b): ans+=c T.union(a,b) value[s+N]=c le=a ri=b for j in range(s+N,N-1,-1): if sear.connect(a,j): le=j break for j in range(s+N,N-1,-1): if sear.connect(b,j): ri=j break table2[s+N].append(le) table2[s+N].append(ri) sear.union(le,s+N) sear.union(ri,s+N) s+=1 if s==N-1: break H=deque() H.append((0,2*N-2)) depth=[-1]*(2*N-1) depth[2*N-2]=0 while H: dep,pt=H.popleft() for p in table2[pt]: H.append((dep+1,p)) depth[p]=dep+1 dp[0][p]=pt #print(table2) #print(depth,dp[0]) for k in range(1,16): for x in range(2*N-1): dp[k][x]=dp[k-1][dp[k-1][x]] def LCA(s,t): if depth[s]>depth[t]: s,t=t,s for k in range(16): if ((depth[t]-depth[s] )>>k) & 1: t = dp[k][t] if s==t: return s for k in range(15,-1,-1): if dp[k][s]!=dp[k][t]: s=dp[k][s] t=dp[k][t] return dp[0][s] for s,t in query: s,t=s-1,t-1 pa=LCA(s,t) #print(pa,value[pa]) print(ans-value[pa]) ```
output
1
53,799
13
107,599
Provide a correct Python 3 solution for this coding contest problem. Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i. He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subset of the edges such that any vertex can be reached from at least one of the vertices S_i or T_i by traversing chosen edges. For each round, find the minimum possible total weight of the edges chosen by Takahashi. Constraints * 1 ≦ N ≦ 4,000 * 1 ≦ M ≦ 400,000 * 1 ≦ Q ≦ 100,000 * 1 ≦ a_i,b_i,S_i,T_i ≦ N * 1 ≦ c_i ≦ 10^{9} * a_i \neq b_i * S_i \neq T_i * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Q S_1 T_1 S_2 T_2 : S_Q T_Q Output Print Q lines. The i-th line should contain the minimum possible total weight of the edges chosen by Takahashi. Examples Input 4 3 1 2 3 2 3 4 3 4 5 2 2 3 1 4 Output 8 7 Input 4 6 1 3 5 4 1 10 2 4 6 3 2 2 3 4 5 2 1 3 1 2 3 Output 8
instruction
0
53,800
13
107,600
"Correct Solution: ``` from collections import deque import sys sys.setrecursionlimit(10**5) N, M = map(int, input().split()) E = [] for i in range(M): a, b, c = map(int, input().split()) E.append((c, a-1, b-1)) E.sort() *p, = range(N) def root(x): if x == p[x]: return x p[x] = y = root(p[x]) return y L = 2*N-1 G = [[]] * L C = [0]*L *lb, = range(N) cur = N s = 0 for c, a, b in E: pa = root(a); pb = root(b) if pa == pb: continue s += c chds = [lb[pa], lb[pb]] if pa < pb: p[pb] = pa lb[pa] = cur else: p[pa] = pb lb[pb] = cur C[cur] = c G[cur] = chds cur += 1 H = [0]*L prv = [-1]*L def dfs(v): s = 1; heavy = -1; m = 0 for w in G[v]: prv[w] = v c = dfs(w) if m < c: heavy = w m = c s += c H[v] = heavy return s dfs(L-1) SS = [] D = [] LB = [0]*L I = [0]*L que = deque([(L-1, 0)]) while que: v, d = que.popleft() S = [] k = len(SS) while v != -1: I[v] = len(S) S.append(v) LB[v] = k h = H[v] for w in G[v]: if h == w: continue que.append((w, d+1)) v = h SS.append(S) D.append(d) def query(u, v): lu = LB[u]; lv = LB[v] dd = D[lv] - D[lu] if dd < 0: lu, lv = lv, lu v, u = u, v dd = -dd for _ in range(dd): v = prv[SS[lv][0]] lv = LB[v] while lu != lv: u = prv[SS[lu][0]] lu = LB[u] v = prv[SS[lv][0]] lv = LB[v] return u if I[u] < I[v] else v def gen(): Q = int(input()) for i in range(Q): u, v = map(int, input().split()) w = query(u-1, v-1) yield "%d\n" % (s - C[w]) ans = list(gen()) sys.stdout.writelines(ans) ```
output
1
53,800
13
107,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i. He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subset of the edges such that any vertex can be reached from at least one of the vertices S_i or T_i by traversing chosen edges. For each round, find the minimum possible total weight of the edges chosen by Takahashi. Constraints * 1 ≦ N ≦ 4,000 * 1 ≦ M ≦ 400,000 * 1 ≦ Q ≦ 100,000 * 1 ≦ a_i,b_i,S_i,T_i ≦ N * 1 ≦ c_i ≦ 10^{9} * a_i \neq b_i * S_i \neq T_i * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Q S_1 T_1 S_2 T_2 : S_Q T_Q Output Print Q lines. The i-th line should contain the minimum possible total weight of the edges chosen by Takahashi. Examples Input 4 3 1 2 3 2 3 4 3 4 5 2 2 3 1 4 Output 8 7 Input 4 6 1 3 5 4 1 10 2 4 6 3 2 2 3 4 5 2 1 3 1 2 3 Output 8 Submitted Solution: ``` INF = 10**7 class PPUnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n self.time = [INF] * n self.number_time = [[0] for _ in [None] * n] self.number_dots = [[1] for _ in [None] * n] def find(self, x, t): while self.time[x] <= t: x = self.parents[x] return x def union(self, x, y, t): x = self.find(x, t) y = self.find(y, t) if x == y: return 0 if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x self.number_time[x] += [t] self.number_dots[x] += [-self.parents[x]] self.time[y] = t return t def size(self, x, y, t): x = self.find(x, t) y = self.find(y, t) a = self.number_dots[x][bisect_left(self.number_time[x], t) - 1] if x != y: a += self.number_dots[y][bisect_left(self.number_time[y], t) - 1] return a def same(self, x, y, t = 0): if x == y: return t if self.time[x] == self.time[y] == INF: return -1 if self.time[x] > self.time[y]: x, y = y, x return self.same(self.parents[x], y, self.time[x]) (n, m), *q = [[*map(int, o.split())] for o in open(0)] UF = PPUnionFind(n) ans = sum(UF.union(a - 1, b - 1, c) for a, b, c in sorted(q[:m], key = lambda t: t[2])) for s, t in q[m+1:]: print(ans - UF.same(s - 1, t - 1)) ```
instruction
0
53,801
13
107,602
No
output
1
53,801
13
107,603
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i. He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subset of the edges such that any vertex can be reached from at least one of the vertices S_i or T_i by traversing chosen edges. For each round, find the minimum possible total weight of the edges chosen by Takahashi. Constraints * 1 ≦ N ≦ 4,000 * 1 ≦ M ≦ 400,000 * 1 ≦ Q ≦ 100,000 * 1 ≦ a_i,b_i,S_i,T_i ≦ N * 1 ≦ c_i ≦ 10^{9} * a_i \neq b_i * S_i \neq T_i * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Q S_1 T_1 S_2 T_2 : S_Q T_Q Output Print Q lines. The i-th line should contain the minimum possible total weight of the edges chosen by Takahashi. Examples Input 4 3 1 2 3 2 3 4 3 4 5 2 2 3 1 4 Output 8 7 Input 4 6 1 3 5 4 1 10 2 4 6 3 2 2 3 4 5 2 1 3 1 2 3 Output 8 Submitted Solution: ``` import sys input = sys.stdin.readline from operator import itemgetter class Unionfindtree: def __init__(self, number): self.par = [i for i in range(number)] self.rank = [0] * (number) def find(self, x): # 親を探す if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): # x,yを繋げる px = self.find(x) py = self.find(y) if px == py: return if self.rank[px] < self.rank[py]: self.par[px] = py else: self.par[py] = px if self.rank[px] == self.rank[py]: self.rank[px] += 1 def connect(self, x, y): # 親が同じかみる return self.find(x) == self.find(y) N,M=map(int,input().split()) table=[[int(i) for i in input().split()]for i in range(M)] Q=int(input()) query=[[int(i) for i in input().split()]for i in range(Q)] if Q>1: sys.exit() table = sorted(table,key=itemgetter(2)) T=Unionfindtree(N) s,t=query[0] s,t=s-1,t-1 T.union(s,t) ans=0 for a,b,c in table: a,b=a-1,b-1 if not T.connect(a,b): ans+=c T.union(a,b) print(ans) ```
instruction
0
53,802
13
107,604
No
output
1
53,802
13
107,605
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i. He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subset of the edges such that any vertex can be reached from at least one of the vertices S_i or T_i by traversing chosen edges. For each round, find the minimum possible total weight of the edges chosen by Takahashi. Constraints * 1 ≦ N ≦ 4,000 * 1 ≦ M ≦ 400,000 * 1 ≦ Q ≦ 100,000 * 1 ≦ a_i,b_i,S_i,T_i ≦ N * 1 ≦ c_i ≦ 10^{9} * a_i \neq b_i * S_i \neq T_i * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Q S_1 T_1 S_2 T_2 : S_Q T_Q Output Print Q lines. The i-th line should contain the minimum possible total weight of the edges chosen by Takahashi. Examples Input 4 3 1 2 3 2 3 4 3 4 5 2 2 3 1 4 Output 8 7 Input 4 6 1 3 5 4 1 10 2 4 6 3 2 2 3 4 5 2 1 3 1 2 3 Output 8 Submitted Solution: ``` import sys input = sys.stdin.readline from operator import itemgetter from collections import deque class Unionfindtree: def __init__(self, number): self.par = [i for i in range(number)] self.rank = [0] * (number) def find(self, x): # 親を探す if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): # x,yを繋げる px = self.find(x) py = self.find(y) if px == py: return if self.rank[px] < self.rank[py]: self.par[px] = py else: self.par[py] = px if self.rank[px] == self.rank[py]: self.rank[px] += 1 def connect(self, x, y): # 親が同じかみる return self.find(x) == self.find(y) def dfs(s): H=deque() visit=[False]*N H.append((0,s)) visit[s]=True L=[0]*N while H: pt,x=H.popleft() for y,cost in tree[x]: if visit[y]: continue c=max(cost,pt) H.append((c,y)) visit[y]=True L[y]=c return L N,M=map(int,input().split()) table=[[int(i) for i in input().split()]for i in range(M)] Q=int(input()) query=[[int(i) for i in input().split()]for i in range(Q)] table = sorted(table,key=itemgetter(2)) T=Unionfindtree(N) #s,t=query[0] #s,t=s-1,t-1 #T.union(s,t) ans=0 tree=[[] for i in range(N)] for i in range(M): a,b,c=table[i] a,b=a-1,b-1 if not T.connect(a,b): ans+=c T.union(a,b) tree[a].append((b,c)) tree[b].append((a,c)) M=[[0]*N for i in range(N)] for i in range(N): M[i]=dfs(i) for s,t in query: s,t=s-1,t-1 print(ans-M[s][t]) ```
instruction
0
53,803
13
107,606
No
output
1
53,803
13
107,607
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i. He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subset of the edges such that any vertex can be reached from at least one of the vertices S_i or T_i by traversing chosen edges. For each round, find the minimum possible total weight of the edges chosen by Takahashi. Constraints * 1 ≦ N ≦ 4,000 * 1 ≦ M ≦ 400,000 * 1 ≦ Q ≦ 100,000 * 1 ≦ a_i,b_i,S_i,T_i ≦ N * 1 ≦ c_i ≦ 10^{9} * a_i \neq b_i * S_i \neq T_i * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Q S_1 T_1 S_2 T_2 : S_Q T_Q Output Print Q lines. The i-th line should contain the minimum possible total weight of the edges chosen by Takahashi. Examples Input 4 3 1 2 3 2 3 4 3 4 5 2 2 3 1 4 Output 8 7 Input 4 6 1 3 5 4 1 10 2 4 6 3 2 2 3 4 5 2 1 3 1 2 3 Output 8 Submitted Solution: ``` # coding: utf-8 def solve(): s, t = map(int, input().split()) visited = [0] * N visited[s-1] = 1 visited[t-1] = 1 cost = 0 vss = [v for v in range(N) if visited[v] == 1] vts = [v for v in range(N) if visited[v] == 0] while vts: mc = 10 ** 9 + 1 mvt = None for vs in vss: for vt in vts: if edges[vs][vt] is not None and edges[vs][vt] < mc: mc = edges[vs][vt] mvt = vt vss.append(mvt) vts.remove(mvt) cost += mc return cost N, M = map(int, input().split()) edges = [[None] * N for _ in range(N)] for i in range(M): a, b, c = map(int, input().split()) edges[a-1][b-1] = c edges[b-1][a-1] = c Q = int(input()) for i in range(Q): print(solve()) ```
instruction
0
53,804
13
107,608
No
output
1
53,804
13
107,609
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
53,985
13
107,970
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` MOD = 998244353 def main(): buf = input() n = int(buf) edge = dict() for i in range(n): edge[i] = [] # zero index for i in range(n-1): buf = input() buflist = list(buf.split()) a = int(buflist[0])-1 # zero index b = int(buflist[1])-1 # zero index edge[a].append(b) edge[b].append(a) # 葉を含む辺を1つ固定 # 次数2の道について長さをkとすると # 2 ** (k-1) pow2 = [1] factorial = [1] for i in range(1, n+1): pow2.append((pow2[-1] * 2) % MOD) factorial.append((factorial[-1] * i) % MOD) root = 0 for v in edge: if len(edge[v]) == 1: root = v break visited = [] for i in range(n): visited.append(False) stack = [root] from_root = True permutation = 1 path_length = 0 while stack: current = stack.pop() visited[current] = True if len(edge[current]) == 1: if current == root: stack.append(edge[current][0]) else: permutation = (permutation * pow2[path_length]) % MOD path_length = 0 elif len(edge[current]) == 2: path_length += 1 for adj in edge[current]: if not visited[adj]: stack.append(adj) else: permutation = (permutation * pow2[path_length]) % MOD path_length = 0 permutation = (permutation * factorial[len(edge[current])]) % MOD for adj in edge[current]: if not visited[adj]: stack.append(adj) permutation = (permutation * n) % MOD print(permutation) if __name__ == '__main__': main() ```
output
1
53,985
13
107,971
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
53,986
13
107,972
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` from sys import stdin, exit from collections import defaultdict input = stdin.readline n = int(input()) edge = [tuple(map(int, line.split())) for line in stdin.read().splitlines()] res = n d = defaultdict(int) MOD = 998244353 for u, v in edge: d[u] += 1 d[v] += 1 res = res * d[u] % MOD * d[v] % MOD print(res) ```
output
1
53,986
13
107,973
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
53,987
13
107,974
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def main(): N = 10**6 mod = 998244353 fac = [1]*(N+1) finv = [1]*(N+1) for i in range(N): fac[i+1] = fac[i] * (i+1) % mod finv[-1] = pow(fac[-1], mod-2, mod) for i in reversed(range(N)): finv[i] = finv[i+1] * (i+1) % mod def cmb1(n, r, mod): if r <0 or r > n: return 0 r = min(r, n-r) return fac[n] * finv[r] * finv[n-r] % mod n = int(input()) g = [[] for i in range(n)] ind = [0]*n for i in range(n-1): u, v = map(int, input().split()) u, v = u-1, v-1 g[u].append(v) g[v].append(u) ind[u] += 1 ind[v] += 1 M = max(ind) for i in range(n): if ind[i] == M: s = i break #print(s) stack = [] stack.append(s) depth = [-1]*n depth[s] = 0 par = [-1]*n order = [] while stack: v = stack.pop() order.append(v) for u in g[v]: if u == par[v]: continue depth[u] = depth[v]+1 par[u] = v stack.append(u) C = [1]*n order.reverse() for v in order: if par[v] != -1: C[par[v]] += 1 dp = [1]*n for v in order: if par[v] != -1: dp[v] *= fac[C[v]] dp[v] %= mod dp[par[v]] *= dp[v] dp[par[v]] %= mod else: dp[v] *= n dp[v] *= fac[C[v]-1] print(dp[s]%mod) if __name__ == '__main__': main() ```
output
1
53,987
13
107,975
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
53,988
13
107,976
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` import sys n = int(sys.stdin.readline().strip()) D = [0] * n p = 998244353 for i in range (0, n - 1): u, v = list(map(int, sys.stdin.readline().strip().split())) D[u-1] = D[u-1] + 1 D[v-1] = D[v-1] + 1 ans = n for i in range (0, n): for j in range (0, D[i]): ans = (ans * (j + 1)) % p print(ans) ```
output
1
53,988
13
107,977
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
53,989
13
107,978
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` import io, os #input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline g = [0] * 200005 r = int(input()) n = r for i in range(1, n): u, v = map(int, input().split()) g[u] += 1 g[v] += 1 r *= g[u] * g[v] r %= 998244353 print(r) ```
output
1
53,989
13
107,979
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
53,990
13
107,980
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` # Enter your code here. Read input from STDIN. Print output to STDOUT# =============================================================================================== # importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from itertools import * import bisect from heapq import * from math import ceil, floor from copy import * from collections import deque, defaultdict from collections import Counter as counter # Counter(list) return a dict with {key: count} from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)] from itertools import permutations as permutate from bisect import bisect_left as bl from operator import * # If the element is already present in the list, # the left most position where element has to be inserted is returned. from bisect import bisect_right as br from bisect import bisect # If the element is already present in the list, # the right most position where element has to be inserted is returned # ============================================================================================== # fast I/O region BUFSIZE = 8192 from sys import stderr class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") # =============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### ########################### #Sorted list 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)) # =============================================================================================== # some shortcuts mod = 1000000007 def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def out(var): sys.stdout.write(str(var)) # for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) def fsep(): return map(float, inp().split()) def nextline(): out("\n") # as stdout.write always print sring. def testcase(t): for p in range(t): solve() def pow(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0): return 0 while (y > 0): if ((y & 1) == 1): # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res from functools import reduce def factors(n): return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))) def gcd(a, b): if a == b: return a while b > 0: a, b = b, a % b return a # discrete binary search # minimise: # def search(): # l = 0 # r = 10 ** 15 # # for i in range(200): # if isvalid(l): # return l # if l == r: # return l # m = (l + r) // 2 # if isvalid(m) and not isvalid(m - 1): # return m # if isvalid(m): # r = m + 1 # else: # l = m # return m # maximise: # def search(): # l = 0 # r = 10 ** 15 # # for i in range(200): # # print(l,r) # if isvalid(r): # return r # if l == r: # return l # m = (l + r) // 2 # if isvalid(m) and not isvalid(m + 1): # return m # if isvalid(m): # l = m # else: # r = m - 1 # return m ##############Find sum of product of subsets of size k in a array # ar=[0,1,2,3] # k=3 # n=len(ar)-1 # dp=[0]*(n+1) # dp[0]=1 # for pos in range(1,n+1): # dp[pos]=0 # l=max(1,k+pos-n-1) # for j in range(min(pos,k),l-1,-1): # dp[j]=dp[j]+ar[pos]*dp[j-1] # print(dp[k]) def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10] return list(accumulate(ar)) def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4] return list(accumulate(ar[::-1]))[::-1] def N(): return int(inp()) dx = [0, 0, 1, -1] dy = [1, -1, 0, 0] def YES(): print("YES") def NO(): print("NO") def Yes(): print("Yes") def No(): print("No") # ========================================================================================= from collections import defaultdict def numberOfSetBits(i): i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24 # # to find factorial and ncr tot=200005 mod = 998244353 fac = [1, 1] finv = [1, 1] inv = [0, 1] for i in range(2, tot + 1): fac.append((fac[-1] * i) % mod) inv.append(mod - (inv[mod % i] * (mod // i) % mod)) finv.append(finv[-1] * inv[-1] % mod) def comb(n, r): if n < r: return 0 else: return fac[n] * (finv[r] * finv[n - r] % mod) % mod class MergeFind: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n # self.lista = [[_] for _ in range(n)] def find(self, a): to_update = [] while a != self.parent[a]: to_update.append(a) a = self.parent[a] for b in to_update: self.parent[b] = a return self.parent[a] def merge(self, a, b): a = self.find(a) b = self.find(b) if a == b: return self.num_sets -= 1 self.parent[a] = b self.size[b] += self.size[a] # self.lista[a] += self.lista[b] # self.lista[b] = [] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets def lcm(a, b): return abs((a // gcd(a, b)) * b) def solve(): mod=998244353 n=N() deg=[0]*n for _ in range(n-1): a,b=sep() a-=1 b-=1 deg[a]+=1 deg[b]+=1 p=1 for i in range(n): p*=fac[deg[i]] p%=mod print((n*p)%mod) solve() #testcase(int(inp())) ```
output
1
53,990
13
107,981
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
53,991
13
107,982
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` import sys input=sys.stdin.readline #sys.setrecursionlimit(1000000) n=int(input()) fr=[0]*(n+2) fr[0]=1 d=[0]*(n+2) mod=int(998244353) for i in range(1,n+1): fr[i]=(fr[i-1]*i)%mod for i in range(n-1): u,v=map(int,input().split()) d[u]+=1;d[v]+=1 ans=n for i in range(1,n+1): ans=ans*fr[d[i]] ans%=mod print(ans) ```
output
1
53,991
13
107,983
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
53,992
13
107,984
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` import math def factorial(n,j): inf=998244353 j[0]=1 j[1]=1 for i in range(2,n+1): j[i]=j[i-1]*i j[i]%=inf return j l1=[0]*(200009) y=factorial(200008,l1) inf=998244353 n=int(input()) l=[0]*(200009) x=1 for i in range(n-1): u,v=input().split() u,v=[int(u),int(v)] l[u]+=1 l[v]+=1 for i in range(len(l)): if l[i]>0: x*=y[l[i]] x%=inf print((n*x)%inf) ```
output
1
53,992
13
107,985
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24. Submitted Solution: ``` import sys def topological_sort_tree(E, p): Q = [p] L = [] visited = set([p]) while Q: p = Q.pop() L.append(p) for vf in E[p]: if vf not in visited: visited.add(vf) Q.append(vf) return L def getpar(Edge, p): N = len(Edge) par = [0]*N par[p] -= 1 stack = [p] visited = set([p]) while stack: vn = stack.pop() for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn stack.append(vf) return par mod = 998244353 frac = [1]*364364 for i in range(2,364364): frac[i] = i * frac[i-1]%mod N = int(input()) Dim = [0]*N Edge = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, sys.stdin.readline().split()) a -= 1 b -= 1 Dim[a] += 1 Dim[b] += 1 Edge[a].append(b) Edge[b].append(a) L = topological_sort_tree(Edge, 0) P = getpar(Edge, 0) dp = [1]*N for l in L[::-1]: dp[l] = dp[l]*frac[Dim[l]] % mod dp[P[l]] = dp[P[l]]*dp[l] % mod print((N*dp[0])%mod) ```
instruction
0
53,993
13
107,986
Yes
output
1
53,993
13
107,987
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24. Submitted Solution: ``` n = int(input()) r = n; MAX = 998244353 arr = [0] * (n + 1) for i in range(n - 1): a, b = map(int, input().split()) arr[a] += 1; arr[b] += 1 r *= arr[a] * arr[b] r %= MAX print(r) ```
instruction
0
53,994
13
107,988
Yes
output
1
53,994
13
107,989
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24. Submitted Solution: ``` # https://codeforces.com/contest/1173/problem/D n = int(input()) mod = 998244353 gt = [1, 1] for i in range(2, 200000): gt.append(i*gt[-1] % mod) g = {} p = {i:-1 for i in range(1, n+1)} dp = {} for _ in range(n-1): u, v = map(int, input().split()) if u not in g: g[u] = [] if v not in g: g[v] = [] g[u].append(v) g[v].append(u) i = 0 S = [1] p[1] = 0 while i < len(S): cur = S[i] for next_n in g[cur]: if next_n == p[cur]: continue p[next_n] = cur S.append(next_n) i +=1 for x in S[1:][::-1]: if len(g[x]) == 1: dp[x] = 1 else: tmp = 1 for next_n in g[x]: if next_n == p[x]:continue tmp = tmp * dp[next_n] % mod tmp = tmp * gt[len(g[x])] % mod if x == 1: tmp = n * tmp % mod dp[x] = tmp dp[1] = n * gt[len(g[1])] % mod for x in g[1]: dp[1] = dp[1] * dp[x] % mod print(dp[1]) ```
instruction
0
53,995
13
107,990
Yes
output
1
53,995
13
107,991
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24. Submitted Solution: ``` p=998244353 n=int(input()) facs=[1] for i in range(1,n): facs.append(facs[-1]*i%p) graph=[0]*n for i in range(n-1): u,v=map(int,input().split()) graph[u-1]+=1 graph[v-1]+=1 prod=n for i in range(n): prod=prod*facs[graph[i]]%p print(prod) ```
instruction
0
53,996
13
107,992
Yes
output
1
53,996
13
107,993
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Sat Jun 8 23:34:53 2019 @author: Hamadeh """ class cinn: def __init__(self): self.x=[] def cin(self,t=int): if(len(self.x)==0): a=input() self.x=a.split() self.x.reverse() return self.get(t) def get(self,t): return t(self.x.pop()) def clist(self,n,t=int): #n is number of inputs, t is type to be casted l=[0]*n for i in range(n): l[i]=self.cin(t) return l def clist2(self,n,t1=int,t2=int,t3=int,tn=2): l=[0]*n for i in range(n): if(tn==2): a1=self.cin(t1) a2=self.cin(t2) l[i]=(a1,a2) elif (tn==3): a1=self.cin(t1) a2=self.cin(t2) a3=self.cin(t3) l[i]=(a1,a2,a3) return l def clist3(self,n,t1=int,t2=int,t3=int): return self.clist2(self,n,t1,t2,t3,3) def cout(self,i,ans=''): if(ans==''): print("Case #"+str(i+1)+":", end=' ') else: print("Case #"+str(i+1)+":",ans) def printf(self,thing): print(thing,end='') def countlist(self,l,s=0,e=None): if(e==None): e=len(l) dic={} for el in range(s,e): if l[el] not in dic: dic[l[el]]=1 else: dic[l[el]]+=1 return dic def talk (self,x): print(x,flush=True) def dp1(self,k): L=[-1]*(k) return L def dp2(self,k,kk): L=[-1]*(k) for i in range(k): L[i]=[-1]*kk return L c=cinn() n=c.cin() edges=c.clist2(n-1) graph={} for i in range(n+1): graph[i]=[] for el in edges: graph[el[0]].append(el[1]) #print(graph) cardios=[0]*(n+1) def cardfind(n): cyo=0 for el in graph[n]: cyo+=cardfind(el)+1 cardios[n]=cyo return cyo cardfind(1) #print(cardios) import math def rec(n): prod=1 prod*=math.factorial(len(graph[n])+1) for el in graph[n]: prod*=rec(el) return prod print(int(rec(1)/(len(graph[1])+1)*n)) ```
instruction
0
53,997
13
107,994
No
output
1
53,997
13
107,995
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24. Submitted Solution: ``` #!/usr/bin/env python import sys input = sys.stdin.readline def dfs(f): try: global answer for t in g[f]: if deg[t] == 0: deg[f] += 1 # print(f'From {f} to {t}, deg({f}) = {deg[f]}') answer *= deg[f] answer %= mod deg[t] = 1 dfs(t) except: print(f'Exception thrown in dfs({f}), answer was {answer}') mod = 998244353 n = int(input()) g = [[] for _ in range(n + 10)] deg = [0 for _ in range(n + 10)] for _ in range(n - 1): u, v = map(lambda _: int(_), input().split()) g[u].append(v); g[v].append(u) answer = n dfs(1) print(answer) ```
instruction
0
53,998
13
107,996
No
output
1
53,998
13
107,997
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24. Submitted Solution: ``` import sys sys.setrecursionlimit(int(1e9)) mod = 998244353 sz = int(2e5 + 2) f = [1] for i in range(1, sz): f.append(f[-1] * i % mod) n = int(input()) g = [[] for i in range(sz)] for i in range(n - 1): try: u, v = map(int, input().split()) except: print('ha') sys.exit(0) g[u].append(v) g[v].append(u) def dfs(z, p): try: a = f[len(g[z])] except: print('dfs') sys.exit(0) try: for y in g[z]: if y != p: a = a * dfs(y, z) except: print('for', z, a) sys.exit(0) return a print(dfs(1, 0) * n % mod) ```
instruction
0
53,999
13
107,998
No
output
1
53,999
13
107,999
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24. Submitted Solution: ``` p=998244353 n=int(input()) facs=[1] for i in range(1,n): facs.append(facs[-1]*i%p) graph=[[] for i in range(n)] for i in range(n-1): u,v=map(int,input().split()) graph[u-1].append(v-1) graph[v-1].append(u-1) prod=facs[len(graph[0])] leaves=0 for i in range(1,n): k=len(graph[i]) prod=prod*facs[k-1]%p if k==1: leaves+=1 prod=prod*2**(n-1-leaves)%p print(prod*n%p) ```
instruction
0
54,000
13
108,000
No
output
1
54,000
13
108,001
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24. Submitted Solution: ``` """ Python 3 compatibility tools. """ from __future__ import division, print_function import sys import os if False: from typing import List, Set, Dict, Tuple, Text, Optional, Callable, Any, Union from collections import deque import collections from types import GeneratorType import itertools import operator import functools import random import copy import heapq import math from atexit import register from io import BytesIO, IOBase import __pypy__ # type: ignore EPS = 10**-12 ######### # INPUT # ######### class Input(object): def __init__(self): if 'CPH' not in os.environ: sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) def rawInput(self): # type: () -> str return sys.stdin.readline().rstrip('\r\n') def readInt(self): return int(self.rawInput()) ########## # OUTPUT # ########## class Output(object): def __init__(self): self.out = __pypy__.builders.StringBuilder() def write(self, text): # type: (str) -> None self.out.append(str(text)) def writeLine(self, text): # type: (str) -> None self.write(str(text) + '\n') def finalize(self): if sys.version_info[0] < 3: os.write(1, self.out.build()) else: os.write(1, self.out.build().encode()) ########### # LIBRARY # ########### def isPrime(number): # type: (int) -> bool # Return if number is prime. # Complexity: n^{0.5} ''' >>> map(isPrime, [0, 1, 2, 4, 5, 8, 11, 21, 23]) [False, False, True, False, True, False, True, False, True] ''' if number <= 1: return False if number == 2: return True if number % 2 == 0: return False for factor in range(3, int(math.sqrt(number))+1, 2): if number % factor == 0: return False return True def bootstrap(f, stack=[]): # Deep Recursion helper. # From: https://github.com/cheran-senthil/PyRival/blob/c1972da95d102d95b9fea7c5c8e0474d61a54378/docs/bootstrap.rst # Usage: # @bootstrap # def recur(n): # if n == 0: # yield 1 # yield (yield recur(n-1)) * n def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc int_add = __pypy__.intop.int_add int_sub = __pypy__.intop.int_sub int_mul = __pypy__.intop.int_mul def make_mod_mul(mod): fmod_inv = 1.0 / mod def mod_mul(a, b, c=0): res = int_sub(int_add(int_mul(a, b), c), int_mul( mod, int(fmod_inv * a * b + fmod_inv * c))) if res >= mod: return res - mod elif res < 0: return res + mod else: return res return mod_mul class Tree(object): ''' >>> tp = Tree([(1, 3), (5, 0), (0, 4), (7, 2), (3, 0), (6, 2), (0, 2)], 3) >>> tp.parent(3) -1 >>> tp.parent(1) 3 >>> tp.parent(4) 0 >>> tp.parent(6) 2 >>> tp.parent(7) 2 >>> tp.parent(2) 0 >>> tp.height(3) 0 >>> tp.height(1) 1 >>> tp.height(2) 2 >>> tp.height(6) 3 >>> tp.children(3) [1, 0] >>> tp.children(1) [] >>> tp.children(0) [5, 4, 2] https://codeforces.com/contest/609/submission/117755214 ''' def __init__(self, edges, root): # type: (List[Tuple[int, int]], int) -> None self.n = n = len(edges) + 1 self._root = root # type: int self._adj = [[] for _ in range(n)] for u, v in edges: assert 0 <= u < n assert 0 <= v < n self._adj[u].append(v) self._adj[v].append(u) self._parent = [-1] * n self._height = [-1] * n stack = [self._root] self._height[self._root] = 0 while stack: node = stack.pop() for child in self._adj[node]: if self._height[child] == -1: self._parent[child] = node self._height[child] = self._height[node] + 1 stack.append(child) self._children = [[] for _ in range(n)] for i in range(n): for neighbor in self._adj[i]: if neighbor != self._parent[i]: self._children[i].append(neighbor) def children(self, node): return self._children[node] def parent(self, node): return self._parent[node] def height(self, node): return self._height[node] def tree_subtree_size(tree): # type: (Tree) -> List[int] ''' >>> tree = Tree([(1, 3), (5, 0), (0, 4), (7, 2), (3, 0), (6, 2), (0, 2)], 3) >>> tree_subtree_size(tree) [6, 1, 3, 8, 1, 1, 1, 1] >>> tree = Tree([], 0) >>> tree_subtree_size(tree) [1] answer[x] = number of nodes in subtree rooted at x, including x ''' answer = [0] * tree.n stack = [tree._root] while stack: node = stack[-1] if answer[node] == 0: # initialize answer[node] = -1 for child in tree._children[node]: stack.append(child) else: stack.pop() ans = 1 for child in tree._children[node]: ans += answer[child] answer[node] = ans return answer class Combination(object): ''' >>> tp = Combination(10, 11) >>> tp.factorial(0) 1 >>> tp.factorial(1) 1 >>> tp.factorial(2) 2 >>> tp.factorial(3) 6 >>> tp.factorial(4) 2 >>> tp.factorial(10) 10 >>> tp.combination(0, 0) 1 >>> tp.combination(1, 1) 1 >>> tp.combination(10, 1) 10 >>> tp.combination(1, 10) 0 >>> tp.combination(1, 0) 1 >>> tp.combination(10, 0) 1 >>> tp.combination(4, 2) 6 >>> tp.combination(6, 2) 4 >>> tp.combination(10, 8) 1 >>> tp.combination(10, 10) 1 >>> tp.permutation(0, 0) 1 >>> tp.permutation(1, 1) 1 >>> tp.permutation(10, 1) 10 >>> tp.permutation(1, 10) 0 >>> tp.permutation(1, 0) 1 >>> tp.permutation(10, 0) 1 >>> tp.permutation(4, 2) 1 >>> tp.permutation(6, 2) 8 >>> tp.permutation(10, 8) 5 >>> tp.permutation(10, 10) 10 >>> tp = Combination(10, 10) >>> tp.factorial(0) 1 >>> tp.factorial(1) 1 >>> tp.factorial(2) 2 >>> tp.factorial(3) 6 >>> tp.factorial(4) 4 >>> tp.factorial(10) 0 >>> tp.combination(0, 0) 1 >>> tp.combination(1, 1) 1 >>> tp.combination(9, 1) 9 >>> tp.combination(10, 1) 0 >>> tp.combination(1, 10) 0 >>> tp.combination(1, 0) 1 >>> tp.combination(10, 0) 1 >>> tp.combination(4, 2) 6 >>> tp.combination(6, 2) 5 >>> tp.combination(10, 8) 5 >>> tp.permutation(0, 0) 1 >>> tp.permutation(1, 1) 1 >>> tp.permutation(10, 1) 0 >>> tp.permutation(1, 10) 0 >>> tp.permutation(1, 0) 1 >>> tp.permutation(10, 0) 1 >>> tp.permutation(4, 2) 2 >>> tp.permutation(6, 2) 0 >>> tp.permutation(10, 8) 0 >>> tp.permutation(10, 10) 0 ''' def __init__(self, max_n, modulo): # type: (int, int) -> None self._max_n = max_n + 5 if modulo > 2 * 10**9: self._mul = lambda a, b: (a*b) % modulo else: self._mul = make_mod_mul(modulo) self._modulo = modulo # precompute factorial self._factorial = [0] * self._max_n self._factorial[0] = 1 for i in range(1, self._max_n): self._factorial[i] = self._mul(self._factorial[i-1], i) self._mod_prime = isPrime(modulo) if self._mod_prime: self._precomputePrimeMod() else: self._precomputeDp() def _precomputePrimeMod(self): # compute modular inverses n = self._max_n modulo = self._modulo mod_inverses = [0] * n mod_inverses[1] = 1 for i in range(2, n): mod_inverses[i] = (modulo - self._mul(modulo // i, mod_inverses[modulo % i])) % modulo factorial_inverses = [0] * n factorial_inverses[0] = factorial_inverses[1] = 1 for i in range(2, n): factorial_inverses[i] = self._mul( factorial_inverses[i-1], mod_inverses[i]) self._factorial_inverse = factorial_inverses def _precomputeDp(self): n = self._max_n # type: int modulo = self._modulo # combination DP: self._dp_combination = [0] * (n*n) dp = self._dp_combination # take 0 from any a is 1 for i in range(n): dp[i * n] = 1 for i in range(1, n): for j in range(1, i+1): # take j from i dp[i * n + j] = (dp[(i-1) * n + j] + dp[(i-1) * n + j - 1]) % modulo # combination DP: self._dp_permutation = [0] * (n*n) dp = self._dp_permutation # take 0 from any a is 1 for i in range(n): dp[i * n] = 1 for i in range(1, n): for j in range(1, i+1): # take j from i dp[i * n + j] = self._mul(dp[(i-1) * n + j - 1], i) def combination(self, total, take): # type: (int, int) -> int assert 0 <= total < self._max_n assert 0 <= take < self._max_n if self._mod_prime: if take > total: return 0 top = self._factorial[total] bottom1 = self._factorial_inverse[take] bottom2 = self._factorial_inverse[total - take] return self._mul(self._mul(top, bottom1), bottom2) else: return self._dp_combination[total * self._max_n + take] def permutation(self, total, take): # type: (int, int) -> int assert 0 <= total < self._max_n assert 0 <= take < self._max_n if self._mod_prime: if take > total: return 0 top = self._factorial[total] bottom = self._factorial_inverse[total - take] return self._mul(top, bottom) else: return self._dp_permutation[total * self._max_n + take] def factorial(self, i): assert 0 <= i < self._max_n return self._factorial[i] ######### # LOGIC # ######### def main(inp, out): # type: (Input, Output) -> None n = inp.readInt() edges = [] for _ in range(n-1): u, v = map(int, inp.rawInput().split()) u -= 1 v -= 1 edges.append((u, v)) tree = Tree(edges, 0) subtree_size = tree_subtree_size(tree) modu = 998244353 mul = make_mod_mul(modu) combin = Combination(200000, modu) @bootstrap def solve(node): children = tree.children(node) ans = combin.factorial(len(children)) for child in children: tmp = (yield solve(child)) if subtree_size[child] > 1: tmp = (2 * tmp) % modu ans = mul(ans, tmp) yield ans out.writeLine(mul(solve(0), n)) ############### # BOILERPLATE # ############### output_obj = Output() main(Input(), output_obj) output_obj.finalize() ```
instruction
0
54,001
13
108,002
No
output
1
54,001
13
108,003
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect k-ary tree if each vertex is either a leaf (has no children) or has exactly k children. Also, in perfect k-ary tree all leafs must have same depth. For example, the picture below illustrates perfect binary tree with 15 vertices: <image> There is a perfect k-ary tree with n nodes. The nodes are labeled with distinct integers from 1 to n, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree. You are allowed to make at most 60 ⋅ n queries of the following type: * "? a b c", the query returns "Yes" if node with label b lies on the path from a to c and "No" otherwise. Both a and c are considered to be lying on the path from a to c. When you are ready to report the root of the tree, print * "! s", where s is the label of the root of the tree. It is possible to report the root only once and this query is not counted towards limit of 60 ⋅ n queries. Interaction The first line of the standard input stream contains two integers n and k (3 ≤ n ≤ 1500, 2 ≤ k < n) — the number of nodes in the tree and the value of k. It is guaranteed that n is such that the tree forms a perfect k-ary tree. You can ask at most 60 ⋅ n queries. To ask a query, print a line of form "? a b c", where 1 ≤ a, b, c ≤ n. After that you should read a single line containing "Yes" or "No" depending on the answer of the query. The tree is fixed for each test and it doesn't depend on your queries. When you are ready to print the answer, print a line of the form "! s", where s is the label of the root vertex and then terminate your program. After printing each query do not forget to print end of line and flush the output. Otherwise you may get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * See documentation for other languages. In case your program will make more than 60 ⋅ n queries, but in other aspects would follow the interaction protocol and terminate coorectly, it will get verdict «Wrong Answer». Hacks To hack the solution use the following test format: The first line should contain integers n and k (3 ≤ n ≤ 1500, 2 ≤ k ≤ 1500) — the number of vertices and the k parameter of the tree. Of course, the value of n must correspond to the size of the valid k-ary tree of some depth. The second line should contain a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the labels of the tree in the natural order, all labels must be distinct. Let's call the following ordering of the tree vertices to be natural: first the root of the tree goes, then go all vertices on depth of one edge from root, ordered from left to right, then go all vertices on depth of two edges from root, ordered from left to right, and so on until the maximum depth. This way, the a_1 is the answer for the hack. Example Input 3 2 No Yes Output ? 1 3 2 ? 1 2 3 ! 2 Note The tree in the example is as follows: <image> The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity). The hack corresponding to the example would look like: 3 2 2 3 1 Submitted Solution: ``` import sys import random def ask(a, b, c): if a == b or b == c: return 1 if a == c: return 0 print("? %d %d %d"%(a, b, c)) sys.stdout.flush() return input() == "Yes" def solve(n, m): x, y = 1, random.randint(2, n) p = [x, y] for i in range(1, n + 1): if i == x or i == y: continue if ask(i, x, y) == True: x = i elif ask(x, y, i) == True: y = i elif ask(x, i, y) == False: continue p.append(i) if len(p) // 2 + 1 == m: for i in p: cnt = 0 for j in p: cnt += ask(x, j, i) if cnt == m: print("! %d"%(i)) sys.stdout.flush() exit(0) n, m = map(int, input().split()) for i in range(n): if (m ** i - 1) // (m - 1) == n: m = i break print(m) while True: solve(n, m) ```
instruction
0
54,804
13
109,608
No
output
1
54,804
13
109,609
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect k-ary tree if each vertex is either a leaf (has no children) or has exactly k children. Also, in perfect k-ary tree all leafs must have same depth. For example, the picture below illustrates perfect binary tree with 15 vertices: <image> There is a perfect k-ary tree with n nodes. The nodes are labeled with distinct integers from 1 to n, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree. You are allowed to make at most 60 ⋅ n queries of the following type: * "? a b c", the query returns "Yes" if node with label b lies on the path from a to c and "No" otherwise. Both a and c are considered to be lying on the path from a to c. When you are ready to report the root of the tree, print * "! s", where s is the label of the root of the tree. It is possible to report the root only once and this query is not counted towards limit of 60 ⋅ n queries. Interaction The first line of the standard input stream contains two integers n and k (3 ≤ n ≤ 1500, 2 ≤ k < n) — the number of nodes in the tree and the value of k. It is guaranteed that n is such that the tree forms a perfect k-ary tree. You can ask at most 60 ⋅ n queries. To ask a query, print a line of form "? a b c", where 1 ≤ a, b, c ≤ n. After that you should read a single line containing "Yes" or "No" depending on the answer of the query. The tree is fixed for each test and it doesn't depend on your queries. When you are ready to print the answer, print a line of the form "! s", where s is the label of the root vertex and then terminate your program. After printing each query do not forget to print end of line and flush the output. Otherwise you may get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * See documentation for other languages. In case your program will make more than 60 ⋅ n queries, but in other aspects would follow the interaction protocol and terminate coorectly, it will get verdict «Wrong Answer». Hacks To hack the solution use the following test format: The first line should contain integers n and k (3 ≤ n ≤ 1500, 2 ≤ k ≤ 1500) — the number of vertices and the k parameter of the tree. Of course, the value of n must correspond to the size of the valid k-ary tree of some depth. The second line should contain a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the labels of the tree in the natural order, all labels must be distinct. Let's call the following ordering of the tree vertices to be natural: first the root of the tree goes, then go all vertices on depth of one edge from root, ordered from left to right, then go all vertices on depth of two edges from root, ordered from left to right, and so on until the maximum depth. This way, the a_1 is the answer for the hack. Example Input 3 2 No Yes Output ? 1 3 2 ? 1 2 3 ! 2 Note The tree in the example is as follows: <image> The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity). The hack corresponding to the example would look like: 3 2 2 3 1 Submitted Solution: ``` from math import log from random import randint import sys n, k = map(int, input().split()) lg = int(log(n, k)) * 2 + 1 have = set() def find_diam(): a = randint(1, n) b = randint(a, n) #print('New') if (a == b) or (a, b) in have: return [] have.add((a, b)) cnt = 2 was = [a, b] for i in range(1, n + 1): if i == a or i == b: continue print('?', a, b, i, flush=True) sys.stdout.flush() ans = 1 if input()[0] == 'Y' else 0 cnt += ans if ans == 1: was.append(i) #print(':', cnt, lg) if cnt == lg: return was return [] res = [] while res == []: res = find_diam() a, b = res[0], res[1] betw = res[2:] for v in betw: cnt = 1 for i in betw: if i == v: continue print('?', a, v, i, flush=True) sys.stdout.flush() ans = 1 if input()[0] == 'Y' else 0 cnt += ans if cnt == lg // 2: print('!', v) assert(v == 2) sys.stdout.flush() exit(0) exit(12) ```
instruction
0
54,805
13
109,610
No
output
1
54,805
13
109,611
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect k-ary tree if each vertex is either a leaf (has no children) or has exactly k children. Also, in perfect k-ary tree all leafs must have same depth. For example, the picture below illustrates perfect binary tree with 15 vertices: <image> There is a perfect k-ary tree with n nodes. The nodes are labeled with distinct integers from 1 to n, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree. You are allowed to make at most 60 ⋅ n queries of the following type: * "? a b c", the query returns "Yes" if node with label b lies on the path from a to c and "No" otherwise. Both a and c are considered to be lying on the path from a to c. When you are ready to report the root of the tree, print * "! s", where s is the label of the root of the tree. It is possible to report the root only once and this query is not counted towards limit of 60 ⋅ n queries. Interaction The first line of the standard input stream contains two integers n and k (3 ≤ n ≤ 1500, 2 ≤ k < n) — the number of nodes in the tree and the value of k. It is guaranteed that n is such that the tree forms a perfect k-ary tree. You can ask at most 60 ⋅ n queries. To ask a query, print a line of form "? a b c", where 1 ≤ a, b, c ≤ n. After that you should read a single line containing "Yes" or "No" depending on the answer of the query. The tree is fixed for each test and it doesn't depend on your queries. When you are ready to print the answer, print a line of the form "! s", where s is the label of the root vertex and then terminate your program. After printing each query do not forget to print end of line and flush the output. Otherwise you may get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * See documentation for other languages. In case your program will make more than 60 ⋅ n queries, but in other aspects would follow the interaction protocol and terminate coorectly, it will get verdict «Wrong Answer». Hacks To hack the solution use the following test format: The first line should contain integers n and k (3 ≤ n ≤ 1500, 2 ≤ k ≤ 1500) — the number of vertices and the k parameter of the tree. Of course, the value of n must correspond to the size of the valid k-ary tree of some depth. The second line should contain a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the labels of the tree in the natural order, all labels must be distinct. Let's call the following ordering of the tree vertices to be natural: first the root of the tree goes, then go all vertices on depth of one edge from root, ordered from left to right, then go all vertices on depth of two edges from root, ordered from left to right, and so on until the maximum depth. This way, the a_1 is the answer for the hack. Example Input 3 2 No Yes Output ? 1 3 2 ? 1 2 3 ! 2 Note The tree in the example is as follows: <image> The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity). The hack corresponding to the example would look like: 3 2 2 3 1 Submitted Solution: ``` from math import log from random import randint import sys n, k = map(int, input().split()) lg = int(log(n, k)) * 2 + 1 have = set() def find_diam(): a = randint(1, n) b = randint(a, n) #print('New') if (a == b) or (a, b) in have: return [] have.add((a, b)) cnt = 2 was = [a, b] for i in range(1, n + 1): if i == a or i == b: continue print('?', a, b, i, flush=True) sys.stdout.flush() ans = 1 if input()[0] == 'Y' else 0 cnt += ans if ans == 1: was.append(i) #print(':', cnt, lg) if cnt == lg: return was return [] res = [] while res == []: res = find_diam() a, b = res[0], res[1] betw = res[2:] for v in betw: cnt = 1 for i in betw: if i == v: continue print('?', a, v, i, flush=True) sys.stdout.flush() ans = 1 if input()[0] == 'Y' else 0 cnt += ans if cnt == lg // 2: print('!', v) sys.stdout.flush() exit(0) ```
instruction
0
54,806
13
109,612
No
output
1
54,806
13
109,613
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect k-ary tree if each vertex is either a leaf (has no children) or has exactly k children. Also, in perfect k-ary tree all leafs must have same depth. For example, the picture below illustrates perfect binary tree with 15 vertices: <image> There is a perfect k-ary tree with n nodes. The nodes are labeled with distinct integers from 1 to n, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree. You are allowed to make at most 60 ⋅ n queries of the following type: * "? a b c", the query returns "Yes" if node with label b lies on the path from a to c and "No" otherwise. Both a and c are considered to be lying on the path from a to c. When you are ready to report the root of the tree, print * "! s", where s is the label of the root of the tree. It is possible to report the root only once and this query is not counted towards limit of 60 ⋅ n queries. Interaction The first line of the standard input stream contains two integers n and k (3 ≤ n ≤ 1500, 2 ≤ k < n) — the number of nodes in the tree and the value of k. It is guaranteed that n is such that the tree forms a perfect k-ary tree. You can ask at most 60 ⋅ n queries. To ask a query, print a line of form "? a b c", where 1 ≤ a, b, c ≤ n. After that you should read a single line containing "Yes" or "No" depending on the answer of the query. The tree is fixed for each test and it doesn't depend on your queries. When you are ready to print the answer, print a line of the form "! s", where s is the label of the root vertex and then terminate your program. After printing each query do not forget to print end of line and flush the output. Otherwise you may get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * See documentation for other languages. In case your program will make more than 60 ⋅ n queries, but in other aspects would follow the interaction protocol and terminate coorectly, it will get verdict «Wrong Answer». Hacks To hack the solution use the following test format: The first line should contain integers n and k (3 ≤ n ≤ 1500, 2 ≤ k ≤ 1500) — the number of vertices and the k parameter of the tree. Of course, the value of n must correspond to the size of the valid k-ary tree of some depth. The second line should contain a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the labels of the tree in the natural order, all labels must be distinct. Let's call the following ordering of the tree vertices to be natural: first the root of the tree goes, then go all vertices on depth of one edge from root, ordered from left to right, then go all vertices on depth of two edges from root, ordered from left to right, and so on until the maximum depth. This way, the a_1 is the answer for the hack. Example Input 3 2 No Yes Output ? 1 3 2 ? 1 2 3 ! 2 Note The tree in the example is as follows: <image> The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity). The hack corresponding to the example would look like: 3 2 2 3 1 Submitted Solution: ``` import sys import random def ask(a, b, c): if a == b or b == c: return 1 if a == c: return 0 print("? %d %d %d"%(a, b, c)) sys.stdout.flush() return input() == "Yes" def solve(n, m): x, y = 1, random.randint(2, n) p = [x, y] for i in range(1, n + 1): if i == x or i == y: continue if ask(i, x, y) == True: x = i elif ask(x, y, i) == True: y = i elif ask(x, i, y) == False: continue p.append(i) if len(p) // 2 + 1 == m: for i in p: cnt = 0 for j in p: cnt += ask(x, j, i) if cnt == m: print("! %d"%(i)) sys.stdout.flush() exit(0) n, m = map(int, input().split()) for i in range(n): if (m ** i - 1) // (m - 1) == n: m = i break while True: solve(n, m) ```
instruction
0
54,807
13
109,614
No
output
1
54,807
13
109,615
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose that we have an array of n distinct numbers a_1, a_2, ..., a_n. Let's build a graph on n vertices as follows: for every pair of vertices i < j let's connect i and j with an edge, if a_i < a_j. Let's define weight of the array to be the number of connected components in this graph. For example, weight of array [1, 4, 2] is 1, weight of array [5, 4, 3] is 3. You have to perform q queries of the following form — change the value at some position of the array. After each operation, output the weight of the array. Updates are not independent (the change stays for the future). Input The first line contains two integers n and q (1 ≤ n, q ≤ 5 ⋅ 10^5) — the size of the array and the number of queries. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — the initial array. Each of the next q lines contains two integers pos and x (1 ≤ pos ≤ n, 1 ≤ x ≤ 10^6, x ≠ a_{pos}). It means that you have to make a_{pos}=x. It's guaranteed that at every moment of time, all elements of the array are different. Output After each query, output the weight of the array. Example Input 5 3 50 40 30 20 10 1 25 3 45 1 48 Output 3 3 4 Note After the first query array looks like [25, 40, 30, 20, 10], the weight is equal to 3. After the second query array looks like [25, 40, 45, 20, 10], the weight is still equal to 3. After the third query array looks like [48, 40, 45, 20, 10], the weight is equal to 4. Submitted Solution: ``` n,q=input ().split() n=int(n) q=int(q) nu=input () x=list(nu.split()) for l in range(0,len(x),1): x[l]=int(x[l]) for qq in range(0,q,1): pos,cng=input().split() cng=int(cng) pos=int(pos)-1 x[pos]=cng s=0 for i in range (0,len(x),1): for j in range(1,len(x),1): if(i<j): if(x[i]<x[j]): s=s+1 print (len(x)-s) ```
instruction
0
54,909
13
109,818
No
output
1
54,909
13
109,819
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353. Input The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000). The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct. It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above. Output Print one integer: the minimum required time modulo 998 244 353. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 Note The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4.
instruction
0
54,973
13
109,946
Tags: dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` import sys input = sys.stdin.readline import heapq mod=998244353 n,m=map(int,input().split()) E=[[] for i in range(n+1)] E2=[[] for i in range(n+1)] for i in range(m): x,y=map(int,input().split()) E[x].append(y) E2[y].append(x) TIME=[1<<29]*(n+1) TIME[1]=0 def shuku(x,y): return (x<<20)+y Q=[] ANS=[] for k in range(n+1): NQ=[] if k<=1: heapq.heappush(Q,shuku(0,1)) if k%2==0: while Q: #print(Q) x=heapq.heappop(Q) time=x>>20 town=x-(time<<20) #print(x,time,town) if TIME[town]<time: continue for to in E[town]: if TIME[to]>time+1: TIME[to]=time+1 heapq.heappush(Q,shuku(TIME[to],to)) heapq.heappush(NQ,shuku(TIME[to],to)) else: while Q: x=heapq.heappop(Q) time=x>>20 town=x-(time<<20) #print(x,time,town) if TIME[town]<time: continue for to in E2[town]: if TIME[to]>time+1: TIME[to]=time+1 heapq.heappush(Q,shuku(TIME[to],to)) heapq.heappush(NQ,shuku(TIME[to],to)) #print(k,TIME) Q=NQ ANS.append(TIME[n]) if k>=100 and TIME[n]!=1<<29: break A=ANS[0] for k in range(1,len(ANS)): if ANS[k]==1<<29: continue if ANS[k-1]==1<<29: A=(ANS[k]+pow(2,k,mod)-1)%mod if k<60 and ANS[k-1]-ANS[k]>pow(2,k-1): A=(ANS[k]+pow(2,k,mod)-1)%mod print(A) ```
output
1
54,973
13
109,947
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353. Input The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000). The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct. It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above. Output Print one integer: the minimum required time modulo 998 244 353. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 Note The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4.
instruction
0
54,974
13
109,948
Tags: dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` from heapq import heappush, heappop;mod = 998244353;N, M = map(int, input().split());E1 = [[] for _ in range(N)];E2 = [[] for _ in range(N)] for _ in range(M):u, v = map(int, input().split());u -= 1;v -= 1;E1[u].append(v);E2[v].append(u) mask1 = (1<<23) - 1;mask2 = (1<<18) - 1;inf = 1<<62;dist = [inf] * (1<<23);start = 0;dist[start] = 0;q = [start] while q: v = heappop(q); dist_v = v >> 23; v &= mask1; n_trans = v >> 18; v_node = v & mask2 if v_node == N-1: print(dist_v % mod); exit() if n_trans > 20: break if dist[v] != dist_v: continue for u_node in (E1[v_node] if n_trans&1==0 else E2[v_node]): u = n_trans<<18 | u_node; dist_u = dist_v + 1 if dist_u < dist[u]: dist[u] = dist_u; heappush(q, dist_u<<23 | u) u = n_trans+1<<18 | v_node; dist_u = dist_v + (1<<n_trans) if dist_u < dist[u]: dist[u] = dist_u; heappush(q, dist_u<<23 | u) mask1 = (1<<37) - 1;mask2 = (1<<19) - 1;mask3 = (1<<18)-1;REV = 1<<18;dist = [inf] * (1<<19);start = 0;dist[start] = 0;q = [start] while q: v = heappop(q);dist_v = v >> 19;n_trans = dist_v >> 18;v &= mask2;v_node = v & mask3 if v_node == N-1:ans = pow(2, n_trans, mod) - 1 + (dist_v&mask3);print(ans);exit() rev = v & REV if dist[v] != dist_v: continue for u_node in (E1[v_node] if n_trans&1==0 else E2[v_node]): u = rev | u_node; dist_u = dist_v + 1 if dist_u < dist[u]: dist[u] = dist_u; heappush(q, dist_u<<19 | u) u = v ^ REV; dist_u = dist_v + (1<<18) if dist_u < dist[u]: dist[u] = dist_u; heappush(q, dist_u<<19 | u) assert False ```
output
1
54,974
13
109,949
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353. Input The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000). The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct. It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above. Output Print one integer: the minimum required time modulo 998 244 353. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 Note The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4.
instruction
0
54,975
13
109,950
Tags: dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` # region fastio # from https://codeforces.com/contest/1333/submission/75948789 import sys, io, os BUFSIZE = 8192 class FastIO(io.IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = io.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(io.IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #endregion from heapq import heappush, heappop mod = 998244353 N, M = map(int, input().split()) E1 = [[] for _ in range(N)] E2 = [[] for _ in range(N)] for _ in range(M): u, v = map(int, input().split()) u -= 1 v -= 1 E1[u].append(v) E2[v].append(u) # コスト、転倒回数(5bit)、ノード(18bit) mask1 = (1<<23) - 1 mask2 = (1<<18) - 1 # ダイクストラ法 inf = 1<<62 dist = [inf] * (1<<23) start = 0 dist[start] = 0 q = [start] while q: v = heappop(q) dist_v = v >> 23 v &= mask1 n_trans = v >> 18 v_node = v & mask2 if v_node == N-1: print(dist_v % mod) exit() if n_trans > 20: break if dist[v] != dist_v: continue for u_node in (E1[v_node] if n_trans&1==0 else E2[v_node]): u = n_trans<<18 | u_node dist_u = dist_v + 1 if dist_u < dist[u]: dist[u] = dist_u heappush(q, dist_u<<23 | u) u = n_trans+1<<18 | v_node dist_u = dist_v + (1<<n_trans) if dist_u < dist[u]: dist[u] = dist_u heappush(q, dist_u<<23 | u) ################################# # 転倒回数、移動回数(18bit)、ノード(19bit) mask1 = (1<<37) - 1 mask2 = (1<<19) - 1 mask3 = (1<<18)-1 REV = 1<<18 dist = [inf] * (1<<19) start = 0 dist[start] = 0 q = [start] while q: v = heappop(q) dist_v = v >> 19 n_trans = dist_v >> 18 v &= mask2 v_node = v & mask3 if v_node == N-1: ans = pow(2, n_trans, mod) - 1 + (dist_v&mask3) print(ans) exit() rev = v & REV if dist[v] != dist_v: continue for u_node in (E1[v_node] if n_trans&1==0 else E2[v_node]): u = rev | u_node dist_u = dist_v + 1 if dist_u < dist[u]: dist[u] = dist_u heappush(q, dist_u<<19 | u) u = v ^ REV dist_u = dist_v + (1<<18) if dist_u < dist[u]: dist[u] = dist_u heappush(q, dist_u<<19 | u) assert False ```
output
1
54,975
13
109,951
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353. Input The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000). The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct. It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above. Output Print one integer: the minimum required time modulo 998 244 353. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 Note The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4.
instruction
0
54,976
13
109,952
Tags: dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase pow2 = [1] for i in range(30): pow2.append(pow2[-1] * 2) class distance(object): def __init__(self, val1: int,val2: int): self.val1 = val1 self.val2 = val2 def __repr__(self): return f'Node value: {self.val1, self.val2}' def __lt__(self, other): a = self.val1 b = self.val2 c = other.val1 d = other.val2 if a == c and b < d: return True elif a == c and b >= d: return False elif a < c and c >= 30: return True elif a > c and a >= 30: return False elif pow2[a] + b < pow2[c] + d: return True elif pow2[a] + b >= pow2[c] + d: return False else: return False class distance2(object): def __init__(self, val1: int,val2: int): self.val1 = val1 self.val2 = val2 def __repr__(self): return f'Node value: {self.val1, self.val2}' def __lt__(self, other): a = self.val1 b = self.val2 c = other.val1 d = other.val2 if a == c and b < d: return True elif a == c and b >= d: return False elif a < c: return True elif a > c: return False else: return False from heapq import heappush, heappop def main(): MOD = 998244353 n,m = map(int,input().split()) graph = [] for _ in range(n): graph.append([]) graph.append([]) for _ in range(m): u,v = map(int,input().split()) graph[2 * u - 2].append(2 * v - 2) graph[2 * v - 1].append(2 * u - 1) for i in range(n): graph[2 * i].append(2 * i + 1) graph[2 * i + 1].append(2 * i) INF = 10 ** 9 dist = [distance(INF,INF)] * (2 * n) dist[0] = distance(0,0) node = [(dist[0],0)] isVisited = [False] * (2 * n) while node: dista, curV = heappop(node) if isVisited[curV]: continue isVisited[curV] = True for newV in graph[curV]: if (curV - newV) % 2 == 0: newDist = distance(dist[curV].val1, dist[curV].val2 + 1) if newDist < dist[newV]: dist[newV] = newDist heappush(node,(newDist,newV)) else: newDist = distance(dist[curV].val1 + 1, dist[curV].val2) if newDist < dist[newV]: dist[newV] = newDist heappush(node,(newDist,newV)) dist1 = min(dist[2 * n - 1],dist[2 * n - 2]) dist = [distance2(INF,INF)] * (2 * n) dist[0] = distance2(0,0) node = [(dist[0],0)] isVisited = [False] * (2 * n) while node: dista, curV = heappop(node) if isVisited[curV]: continue isVisited[curV] = True for newV in graph[curV]: if (curV - newV) % 2 == 0: newDist = distance2(dist[curV].val1, dist[curV].val2 + 1) if newDist < dist[newV]: dist[newV] = newDist heappush(node,(newDist,newV)) else: newDist = distance2(dist[curV].val1 + 1, dist[curV].val2) if newDist < dist[newV]: dist[newV] = newDist heappush(node,(newDist,newV)) dist2 = min(dist[2 * n - 1],dist[2 * n - 2]) dist2N = distance(dist2.val1,dist2.val2) if dist1 < dist2N: print((pow(2,dist1.val1,MOD) + dist1.val2 - 1) % MOD) else: print((pow(2,dist2N.val1,MOD) + dist2N.val2 - 1) % MOD) # 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
54,976
13
109,953
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353. Input The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000). The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct. It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above. Output Print one integer: the minimum required time modulo 998 244 353. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 Note The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4. Submitted Solution: ``` import sys from sys import stdin from collections import deque #X + 2^Y x,y < X,Y ? def big(a,b): x,y = a X,Y = b if y == Y: return x < X if max(y,Y) > 30: return y < Y else: return x+2**y-1 < X+2**Y-1 mod = 998244353 n,m = map(int,stdin.readline().split()) lis = [ [] for i in range(n) ] ris = [ [] for i in range(n) ] for i in range(m): u,v = map(int,stdin.readline().split()) u -= 1 v -= 1 lis[u].append(v) ris[v].append(u) cnt = 0 d = [(0,10**6)] * (2*n) d[0] = (0,0) q = deque([0]) while len(q) > 0: while len(q) > 0: v = q.popleft() #print (v) if v < n: tmp = (d[v][0] + 1 , d[v][1]) for nex in lis[v]: if big( tmp , d[nex] ): d[nex] = tmp q.append(nex) tmp = (d[v][0] + 1 , d[v][1] + 1) for nex in ris[v]: if big( tmp , d[nex + n] ): d[nex + n] = tmp q.append(nex + n) else: tmp = (d[v][0] + 1 , d[v][1]) for nex in ris[v-n]: if big( tmp , d[nex + n] ): d[nex + n] = tmp q.append(nex + n) tmp = (d[v][0] + 1 , d[v][1] + 1) for nex in lis[v-n]: if big( tmp , d[nex] ): d[nex] = tmp q.append(nex) #print (d) x,y = d[n-1] X,Y = d[2*n-1] print (min(x+2**y-1,X+2**Y-1) % mod) ```
instruction
0
54,977
13
109,954
No
output
1
54,977
13
109,955
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353. Input The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000). The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct. It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above. Output Print one integer: the minimum required time modulo 998 244 353. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 Note The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4. Submitted Solution: ``` import sys sys.setrecursionlimit(10**5) int1 = lambda x: int(x)-1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.buffer.readline()) def MI(): return map(int, sys.stdin.buffer.readline().split()) def MI1(): return map(int1, sys.stdin.buffer.readline().split()) def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def BI(): return sys.stdin.buffer.readline().rstrip() def SI(): return sys.stdin.buffer.readline().rstrip().decode() class c: def __init__(self,m,t): self.m=m self.t=t def __repr__(self): return "({},{})".format(self.m,self.t) def __eq__(self, other): if max(self.t,other.t)>20: return (self.m,self.t)==(other.m,other.t) v1=1<<self.t+self.m v2=1<<other.t+other.m return v1==v2 def __lt__(self, other): if max(self.t,other.t)>20: return self.t<other.t v1=1<<self.t+self.m v2=1<<other.t+other.m return v1<v2 def __add__(self, other): return c(self.m+1,self.t) def __mul__(self, other): return c(self.m,self.t+1) from heapq import * inf=10**6 md=998244353 n,m=MI() to=[[[] for _ in range(2)] for _ in range(n)] for _ in range(m): u,v=MI1() to[u][0].append(v) to[v][1].append(u) cost=[[c(inf,inf) for _ in range(2)] for _ in range(n)] cost[0][0]=c(0,0) hp=[] heappush(hp,(c(0,0),0,0)) while hp: cu,u,r=heappop(hp) if cost[u][r]<cu:continue for v in to[u][r]: cv=cu+1 if cv<cost[v][r]: cost[v][r]=cv heappush(hp,(cv,v,r)) cv=cu*1 if cv<cost[u][1-r]: cost[u][1-r]=cv heappush(hp,(cv,u,1-r)) # print(cost) mn=min(cost[n-1]) ans=(pow(2,mn.t,md)+mn.m-1)%md print(ans) ```
instruction
0
54,978
13
109,956
No
output
1
54,978
13
109,957
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353. Input The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000). The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct. It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above. Output Print one integer: the minimum required time modulo 998 244 353. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 Note The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4. Submitted Solution: ``` import heapq from heapq import heappush as push from heapq import heappop as pop p2 = [2**i - 1 for i in range(64)] class Node(object): def __init__(self, k, val): self.val = val self.k = k def __repr__(self): return f'Node: k: {self.k}, val: {self.val}' def __lt__(self, other): if self.k == other.k: return self.val < other.val return self.k < other.k n, m = list(map(int, input().split())) edge = [list(map(int, input().split())) for _ in range(m)] G = [{}, {}] for u, v in edge: if u not in G[0]: G[0][u] = [] if v not in G[1]: G[1][v] = [] G[0][u].append(v) G[1][v].append(u) d = {} d[(0, 1)] = 0 #k val u Q = [(0, 0, 1)] flg=False while len(Q) > 0: k, val, u = pop(Q) if k >= 32: continue if (k, u) in d and d[(k, u)] < val: continue if u in G[k%2]: for v in G[k%2][u]: if (k, v) not in d or val + 1 < d[(k, v)]: d[(k, v)] = val + 1 push(Q, (k, val + 1, v)) if u in G[(k+1)%2]: for v in G[(k+1)%2][u]: if (k+1, v) not in d or val + 1 < d[(k+1, v)]: d[(k+1, v)] = val + 1 push(Q, (k+1, val + 1, v)) mod = 998244353 ans = 1 choose1 = float('inf') for (k, u), val in d.items(): if u == n: choose1 = min(choose1, pow(2, k, mod) - 1 + val) if choose1 < float('inf'): print(choose1 % mod) exit() d = {} d[1] = Node(0, 0) #k val u Q = [(0, 0, 1)] flg = False comp = 1<<32 while len(Q) > 0: k, val, u = pop(Q) if u in d and Node(k, val) > d[u]: continue u &= (comp-1) if u in G[k%2]: for v in G[k%2][u]: if v not in d or Node(k, val + 1) < d[v]: d[v] = Node(k, val + 1) push(Q, (k, val + 1, v)) if v & (comp-1) == n: print((pow(2, k, mod) + val)%mod) exit() if u in G[(k+1)%2]: for v in G[(k+1)%2][u]: v = v ^ comp if v not in d or Node(k+1, val + 1) < d[v]: d[v] = Node(k+1, val + 1) push(Q, (k+1, val + 1, v)) if v & (comp-1) == n: print((pow(2, k+1, mod) + val)%mod) exit() ```
instruction
0
54,979
13
109,958
No
output
1
54,979
13
109,959
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353. Input The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000). The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct. It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above. Output Print one integer: the minimum required time modulo 998 244 353. Examples Input 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 Note The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4. Submitted Solution: ``` import sys sys.setrecursionlimit(10**5) int1 = lambda x: int(x)-1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.buffer.readline()) def MI(): return map(int, sys.stdin.buffer.readline().split()) def MI1(): return map(int1, sys.stdin.buffer.readline().split()) def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def BI(): return sys.stdin.buffer.readline().rstrip() def SI(): return sys.stdin.buffer.readline().rstrip().decode() from heapq import * inf=10**6 md=998244353 n,m=MI() to=[[[] for _ in range(n)] for _ in range(2)] for _ in range(m): u,v=MI1() to[0][u].append(v) to[1][v].append(u) cc=[[inf]*n for _ in range(20)] cc[0][0]=0 hp=[] heappush(hp,(0,0,0)) while hp: c,f,u=heappop(hp) if u==n-1: print(c) exit() if c>cc[f][u]:continue for v in to[f&1][u]: nc=c+1 if nc>=cc[f][v]:continue cc[f][v]=nc heappush(hp,(nc,f,v)) if f==19:continue nc=c+(1<<f) if nc<cc[f+1][u]: cc[f+1][u]=nc heappush(hp,(nc,f+1,u)) cc=cc[19] fd=[(inf,inf) for _ in range(n)] s=(1<<19)-1 for u in range(n): if cc[u]==inf:continue fd[u]=(19,cc[u]-s) heappush(hp,(19,cc[u]-s,u)) while hp: f,d,u=heappop(hp) if u==n-1: # print(f,d,u) ans=(pow(2,f,md)-1+d)%md print(ans) exit() if (f,d)>fd[u]:continue fd[u]=(f,d) for v in to[f&1][u]: if (f,d+1)>=fd[v]:continue fd[v]=(f,d+1) heappush(hp,(f,d+1,v)) for v in to[1-(f&1)][u]: if (f+1,d+1)>=fd[v]:continue fd[v]=(f+1,d+1) heappush(hp,(f+1,d+1,v)) ```
instruction
0
54,980
13
109,960
No
output
1
54,980
13
109,961
Provide a correct Python 3 solution for this coding contest problem. Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge. Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division. * Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds. Constraints * 2 \leq N \leq 200 * S_{i,j} is `0` or `1`. * S_{i,i} is `0`. * S_{i,j}=S_{j,i} * The given graph is connected. * N is an integer. Input Input is given from Standard Input in the following format: N S_{1,1}...S_{1,N} : S_{N,1}...S_{N,N} Output If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1. Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition. Examples Input 2 01 10 Output 2 Input 3 011 101 110 Output -1 Input 6 010110 101001 010100 101000 100000 010000 Output 4
instruction
0
55,406
13
110,812
"Correct Solution: ``` from collections import defaultdict, deque def grouping(n, N, d): group = [-1]*(N+1) group[n] = 1 q = deque([n]) while q: s = q.popleft() for t in d[s]: if group[t]!=-1:continue group[t] = group[s] + 1 q.append(t) for k, v in d.items(): for j in v: if not abs(group[j]-group[k])==1: return False return group def solve(): N = int(input()) d = defaultdict(list) for i in range(1, N+1): for j, s in enumerate(input(), start=1): if s=="1": d[i].append(j) ans = -1 for i in range(1, N+1): res = grouping(i, N, d) if res != False: ans = max(ans, max(res)) print(ans) if __name__ == "__main__": solve() ```
output
1
55,406
13
110,813
Provide a correct Python 3 solution for this coding contest problem. Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge. Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division. * Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds. Constraints * 2 \leq N \leq 200 * S_{i,j} is `0` or `1`. * S_{i,i} is `0`. * S_{i,j}=S_{j,i} * The given graph is connected. * N is an integer. Input Input is given from Standard Input in the following format: N S_{1,1}...S_{1,N} : S_{N,1}...S_{N,N} Output If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1. Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition. Examples Input 2 01 10 Output 2 Input 3 011 101 110 Output -1 Input 6 010110 101001 010100 101000 100000 010000 Output 4
instruction
0
55,407
13
110,814
"Correct Solution: ``` N = int(input()) S = [list(map(int,list(input()))) for _ in [0]*N] E = [[] for _ in [0]*N] for i,row in enumerate(S): for j,s in enumerate(row): if s : E[i].append(j) def dist_bfs(N,E,start): d = [-1]*N d[start] = 0 q = [start] while q: qq = [] for i in q: di = d[i] for j in E[i]: if d[j]!=-1:continue d[j] = di+1 q.append(j) q = qq return d ans = -1 for i in range(N): d = dist_bfs(N,E,i) ans = max(ans,max(d)+1) #check for i,e in enumerate(E): for j in e: if j > i : break if abs(d[i] - d[j]) != 1 : ans = -1 print(ans) ```
output
1
55,407
13
110,815
Provide a correct Python 3 solution for this coding contest problem. Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge. Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division. * Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds. Constraints * 2 \leq N \leq 200 * S_{i,j} is `0` or `1`. * S_{i,i} is `0`. * S_{i,j}=S_{j,i} * The given graph is connected. * N is an integer. Input Input is given from Standard Input in the following format: N S_{1,1}...S_{1,N} : S_{N,1}...S_{N,N} Output If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1. Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition. Examples Input 2 01 10 Output 2 Input 3 011 101 110 Output -1 Input 6 010110 101001 010100 101000 100000 010000 Output 4
instruction
0
55,408
13
110,816
"Correct Solution: ``` from collections import deque N = int(input()) minDist = [[1 if s == '1' else float('inf') for s in input()] for _ in range(N)] for i in range(N): minDist[i][i] = 0 for k in range(N): for i in range(N): for j in range(N): if minDist[i][j] > minDist[i][k] + minDist[k][j]: minDist[i][j] = minDist[i][k] + minDist[k][j] base = [d % 2 for d in minDist[0]] for i in range(N): A = [0] * N for j, d in enumerate(minDist[i]): A[j] = (d + base[i]) % 2 if A != base: print(-1) exit() ans = max([max(D) for D in minDist]) + 1 print(ans) ```
output
1
55,408
13
110,817
Provide a correct Python 3 solution for this coding contest problem. Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge. Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division. * Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds. Constraints * 2 \leq N \leq 200 * S_{i,j} is `0` or `1`. * S_{i,i} is `0`. * S_{i,j}=S_{j,i} * The given graph is connected. * N is an integer. Input Input is given from Standard Input in the following format: N S_{1,1}...S_{1,N} : S_{N,1}...S_{N,N} Output If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1. Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition. Examples Input 2 01 10 Output 2 Input 3 011 101 110 Output -1 Input 6 010110 101001 010100 101000 100000 010000 Output 4
instruction
0
55,409
13
110,818
"Correct Solution: ``` from collections import deque n = int(input()) s = [list(map(int, list(input()))) for _ in range(n)] bord = [[] for _ in range(n)] for i in range(n-1): for j in range(i+1, n): if s[i][j]==1: bord[i].append(j) bord[j].append(i) result = [] for i in range(n): ch = True visit = [-1 for _ in range(n)] visit[i] = 1 q = deque([i]) while q: x = q.popleft() for y in bord[x]: if visit[y]<0: visit[y] = visit[x]+1 q.append(y) elif (visit[y] == visit[x]+1) or (visit[y]==visit[x]-1): continue else: ch = False break if ch: result.append(max(visit)) else: result = [-1] break print(max(result)) ```
output
1
55,409
13
110,819
Provide a correct Python 3 solution for this coding contest problem. Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge. Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division. * Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds. Constraints * 2 \leq N \leq 200 * S_{i,j} is `0` or `1`. * S_{i,i} is `0`. * S_{i,j}=S_{j,i} * The given graph is connected. * N is an integer. Input Input is given from Standard Input in the following format: N S_{1,1}...S_{1,N} : S_{N,1}...S_{N,N} Output If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1. Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition. Examples Input 2 01 10 Output 2 Input 3 011 101 110 Output -1 Input 6 010110 101001 010100 101000 100000 010000 Output 4
instruction
0
55,410
13
110,820
"Correct Solution: ``` n = int(input()) raw = [] for i in range(n): tmp = input() now = [] for j in range(n): if tmp[j] == '1': now.append(j) raw.append(now) #print(raw) ans = [] for st in range(n): gr = [-1 for _ in range(n)] gr[st] = 1 time = 1 now = {st} while now: time += 1 last = now now = set() #print(last) for x in last: for y in raw[x]: if gr[y] == time-2: pass elif gr[y] == time: pass elif gr[y] == -1: gr[y] = time now.add(y) else: print(-1) #print(time,y,gr[y]) break else: continue break else: continue break else: #print(time) ans.append(time-1) continue break else: print(max(ans)) ```
output
1
55,410
13
110,821
Provide a correct Python 3 solution for this coding contest problem. Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge. Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division. * Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds. Constraints * 2 \leq N \leq 200 * S_{i,j} is `0` or `1`. * S_{i,i} is `0`. * S_{i,j}=S_{j,i} * The given graph is connected. * N is an integer. Input Input is given from Standard Input in the following format: N S_{1,1}...S_{1,N} : S_{N,1}...S_{N,N} Output If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1. Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition. Examples Input 2 01 10 Output 2 Input 3 011 101 110 Output -1 Input 6 010110 101001 010100 101000 100000 010000 Output 4
instruction
0
55,411
13
110,822
"Correct Solution: ``` def b(u,x): c[u]=x return all((c[u]!=c[v])&(c[v]or b(v,-x))for v in X if d[u][v]==1) N=int(input()) X=range(N) S=[input()for _ in X] d=[[1 if S[i][j]=='1'else(N if i^j else 0)for j in X]for i in X] for k in X: for i in X: for j in X:d[i][j]=min(d[i][j],d[i][k]+d[k][j]) c=[0]*N print(max(max(e)for e in d)+1 if b(0,1)else-1) ```
output
1
55,411
13
110,823
Provide a correct Python 3 solution for this coding contest problem. Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge. Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division. * Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds. Constraints * 2 \leq N \leq 200 * S_{i,j} is `0` or `1`. * S_{i,i} is `0`. * S_{i,j}=S_{j,i} * The given graph is connected. * N is an integer. Input Input is given from Standard Input in the following format: N S_{1,1}...S_{1,N} : S_{N,1}...S_{N,N} Output If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1. Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition. Examples Input 2 01 10 Output 2 Input 3 011 101 110 Output -1 Input 6 010110 101001 010100 101000 100000 010000 Output 4
instruction
0
55,412
13
110,824
"Correct Solution: ``` N = int(input()) g = [[] for i in [0]*(N+1)] for i in range(1,N+1): S = input() for j in range(1,i+1): if S[j-1] == '1': g[i].append(j) g[j].append(i) def max_len(g,v): visited = [False]*(N+1) l = 1 ls = [v] pre_v = [] while(ls): new_ls = [] for cv in ls: for nv in g[cv]: if visited[nv] and not nv in pre_v: return -1 if not visited[nv] and not nv in new_ls: new_ls.append(nv) visited[cv] = True if new_ls: l += 1 pre_v = ls ls = new_ls return l m = -1 for i in range(1,N+1): m = max(m,max_len(g,i)) print(m) ```
output
1
55,412
13
110,825