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. This is an interactive problem. You're given a tree consisting of n nodes, rooted at node 1. A tree is a connected graph with no cycles. We chose a hidden node x. In order to find this node, you can ask queries of two types: * d u (1 ≤ u ≤ n). We will answer with the distance between nodes u and x. The distance between two nodes is the number of edges in the shortest path between them. * s u (1 ≤ u ≤ n). We will answer with the second node on the path from u to x. However, there's a plot twist. If u is not an ancestor of x, you'll receive "Wrong answer" verdict! Node a is called an ancestor of node b if a ≠ b and the shortest path from node 1 to node b passes through node a. Note that in this problem a node is not an ancestor of itself. Can you find x in no more than 36 queries? The hidden node is fixed in each test beforehand and does not depend on your queries. Input The first line contains the integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output To print the answer, print "! x" (without quotes). Interaction To ask a question, print it in one of the formats above: * d u (1 ≤ u ≤ n), or * s u (1 ≤ u ≤ n). After each question, you should read the answer: either the distance or the second vertex on the path, as mentioned in the legend. If we answer with -1 instead of a valid answer, that means you exceeded the number of queries, made an invalid query, or violated the condition in the second type of queries. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream. After printing a query, do not forget to output end of line and flush the output. Otherwise, you will 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 the documentation for other languages. Hacks: The first line should contain two integers n and x (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ x ≤ n). Each of the next n-1 lines should contain two integers u and v (1 ≤ u,v ≤ n) that mean there is an edge between nodes u and v. The edges must form a tree. Example Input 5 1 2 1 3 3 4 3 5 3 5 Output d 2 s 3 ! 5 Note In the first example, the hidden node is node 5. <image> We first ask about the distance between node x and node 2. The answer is 3, so node x is either 4 or 5. We then ask about the second node in the path from node 3 to node x. Note here that node 3 is an ancestor of node 5. We receive node 5 as the answer. Finally, we report that the hidden node is node 5. Submitted Solution: ``` import os, sys, shutil, glob, re import time, calendar from datetime import datetime, timezone import hashlib, zipfile, zlib from math import * from operator import itemgetter from functools import wraps, cmp_to_key, reduce, lru_cache from itertools import count, combinations, permutations from collections import namedtuple, defaultdict, Counter, deque from queue import Queue from bisect import bisect_left, bisect_right class CustomException(Exception): pass if os.getenv('SJDEAK'): # sys.stdin = open(os.path.expanduser('./in.txt')) # sys.stdout = open(os.path.expanduser('./out.txt'), 'w') debug = print else: debug = lambda *args, **kwargs: None def sendInteractiveCommand(cmd): print(cmd) sys.stdout.flush() return input() def findHidden(now): cmdRes = int(sendInteractiveCommand(f'd {now}')) if cmdRes == 0: return now if len(graph[now]) == 1: return findHidden(graph[now][0]) else: child = int(sendInteractiveCommand(f's {now}')) return findHidden(child) if __name__ == '__main__': N = int(input()) graph = defaultdict(list) for i in range(N-1): u,v = list(map(int, input().split())) graph[u].append(v) ans = findHidden(1) print('! {}'.format(ans)) ```
instruction
0
48,009
13
96,018
No
output
1
48,009
13
96,019
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1.
instruction
0
48,135
13
96,270
Tags: constructive algorithms, data structures, graphs, hashing Correct Solution: ``` import sys input = sys.stdin.readline n, m = map(int, input().split()) same, both = 0, 0 edges = {} for _ in range(m): x = input().split() if x[0] == '+': k, i, j, c = x edges[i, j] = c if (j, i) in edges: both += 1 same += edges[j, i] == c elif x[0] == '-': k, i, j = x if (j, i) in edges: both -= 1 same -= edges[i, j] == edges[j, i] del edges[i, j] else: i = int(x[1]) if not i % 2: print("YES" if same else "NO") else: print("YES" if both else "NO") ```
output
1
48,135
13
96,271
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1.
instruction
0
48,136
13
96,272
Tags: constructive algorithms, data structures, graphs, hashing Correct Solution: ``` from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # 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") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def A(n):return [0]*n def AI(n,x): return [x]*n def G(n): return [[] for i in range(n)] def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): 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 mod=10**9+7 farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa fact(x,mod) ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa.reverse() def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1)) if a==0:return b//c*(n+1) if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2 m=(a*n+b)//c return n*m-floorsum(c,c-b-1,a,m-1) def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class ST: def __init__(self,arr):#n!=0 n=len(arr) mx=n.bit_length()#取不到 self.st=[[0]*mx for i in range(n)] for i in range(n): self.st[i][0]=arr[i] for j in range(1,mx): for i in range(n-(1<<j)+1): self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1]) def query(self,l,r): if l>r:return -inf s=(r+1-l).bit_length()-1 return max(self.st[l][s],self.st[r-(1<<s)+1][s]) ''' class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]>self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)]''' class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return flag def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue seen.add(u) for v,w in graph[u]: if v not in d or d[v]>d[u]+w: d[v]=d[u]+w heappush(heap,(d[v],v)) return d def bell(s,g):#bellman-Ford dis=AI(n,inf) dis[s]=0 for i in range(n-1): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change=A(n) for i in range(n): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change[v]=1 return dis def lcm(a,b): return a*b//gcd(a,b) def lis(nums): res=[] for k in nums: i=bisect.bisect_left(res,k) if i==len(res): res.append(k) else: res[i]=k return len(res) def RP(nums):#逆序对 n = len(nums) s=set(nums) d={} for i,k in enumerate(sorted(s),1): d[k]=i bi=BIT([0]*(len(s)+1)) ans=0 for i in range(n-1,-1,-1): ans+=bi.query(d[nums[i]]-1) bi.update(d[nums[i]],1) return ans class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None def nb(i,j,n,m): for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]: if 0<=ni<n and 0<=nj<m: yield ni,nj def topo(n): q=deque() res=[] for i in range(1,n+1): if ind[i]==0: q.append(i) res.append(i) while q: u=q.popleft() for v in g[u]: ind[v]-=1 if ind[v]==0: q.append(v) res.append(v) return res @bootstrap def gdfs(r,p): if len(g[r])==1 and p!=-1: yield None for ch in g[r]: if ch!=p: yield gdfs(ch,r) yield None t=1 for i in range(t): n,m=RL() g=defaultdict(dict) same=edge=0 for i in range(m): q=input().split() if q[0]=='+': u,v,c=int(q[1]),int(q[2]),q[3] g[u][v]=c if u in g[v]: if g[v][u]==c: same+=1 edge+=1 elif q[0]=='-': u,v=int(q[1]),int(q[2]) if u in g[v]: if g[v][u]==g[u][v]: same-=1 edge-=1 del g[u][v] else: k=int(q[1]) if k&1: if edge: print("YES") else: print("NO") else: if same: print("YES") else: print("NO") ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thr ead(target=main) t.start() t.join() ''' ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thread(target=main) t.start() t.join() ''' ```
output
1
48,136
13
96,273
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1.
instruction
0
48,137
13
96,274
Tags: constructive algorithms, data structures, graphs, hashing Correct Solution: ``` n, m = map(int,input().split()) rev, same = 0, 0 now = {} a = [set() for _ in range(n+1)] for i in range(m): b = input().split() x = b[0] if x == '+': u, v, w = int(b[1]), int(b[2]), b[3] a[u].add(v) now[(u,v)] = w if (v,u) in now: rev += 1 if now[(v,u)] == w: same += 1 elif x == '-': u, v = int(b[1]), int(b[2]) if (v,u) in now: rev -= 1 if now[(v,u)] == now[(u,v)]: same -= 1 a[u].remove(v) del now[(u,v)] else: k = int(b[1]) if k & 1: ans = "YES" if same or rev else "NO" else: ans = "YES" if same else "NO" print(ans) ```
output
1
48,137
13
96,275
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1.
instruction
0
48,138
13
96,276
Tags: constructive algorithms, data structures, graphs, hashing Correct Solution: ``` """ #If FastIO not needed, use this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os, sys, heapq as h, time from io import BytesIO, IOBase from types import GeneratorType from bisect import bisect_left, bisect_right from collections import defaultdict as dd, deque as dq, Counter as dc import math, string BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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") def getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def isInt(s): return '0' <= s[0] <= '9' MOD = 10**9 + 7 """ If K is odd, we need a back and forward pair of any description between two nodes U and V If K is even, we need a back and forward pair that is identical """ def solve(): N, M = getInts() graph = [dd(lambda: dd(int)) for _ in range(N)] sing_ = 0 back_ = 0 for _ in range(M): S = getStrs() if S[0] == '+': u, v = [int(s)-1 for s in S[1:3]] c = S[3] graph[u][v] = c d = graph[v][u] if not d: d = '0' if c == d: sing_ += 1 elif d != '0': back_ += 1 elif S[0] == '-': u, v = [int(s)-1 for s in S[1:3]] c = graph[u][v] d = graph[v][u] if not d: d = '0' if c == d: sing_ -= 1 elif d != '0': back_ -= 1 graph[u][v] = '0' else: k = int(S[1]) if k % 2 == 0: print("YES" if sing_ > 0 else "NO") else: print("YES" if back_+sing_ > 0 else "NO") sys.stdout.flush() return solve() ```
output
1
48,138
13
96,277
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1.
instruction
0
48,139
13
96,278
Tags: constructive algorithms, data structures, graphs, hashing Correct Solution: ``` import sys n, m = map(int, sys.stdin.readline().split()) D = {} edges2 = set() edges1 = set() for i in range(m): s, *A = sys.stdin.readline().split() if s == '+': u, v, c = int(A[0]), int(A[1]), A[2] D[(u, v)] = c if (v, u) in D and D[(v, u)] == c: edges2.add(tuple(sorted((u, v)))) if tuple(sorted((u, v))) in edges1: edges1.remove(tuple(sorted((u, v)))) elif (v, u) in D: edges1.add(tuple(sorted((u, v)))) if tuple(sorted((u, v))) in edges2: edges2.remove(tuple(sorted((u, v)))) if s == '-': u, v = int(A[0]), int(A[1]) D.pop((u, v), None) if tuple(sorted((u, v))) in edges1: edges1.remove(tuple(sorted((u, v)))) if tuple(sorted((u, v))) in edges2: edges2.remove(tuple(sorted((u, v)))) if s == '?': k = int(A[0]) if k % 2 == 0: sys.stdout.write('YES' if edges2 else 'NO') else: sys.stdout.write('YES' if edges1 or edges2 else 'NO') sys.stdout.write('\n') ```
output
1
48,139
13
96,279
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1.
instruction
0
48,140
13
96,280
Tags: constructive algorithms, data structures, graphs, hashing Correct Solution: ``` """ #If FastIO not needed, use this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os, sys, heapq as h, time from io import BytesIO, IOBase from types import GeneratorType from bisect import bisect_left, bisect_right from collections import defaultdict as dd, deque as dq, Counter as dc import math, string BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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") def getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def isInt(s): return '0' <= s[0] <= '9' MOD = 10**9 + 7 """ If K is odd, we need a back and forward pair of any description between two nodes U and V If K is even, we need a back and forward pair that is identical """ def solve(): N, M = getInts() graph = [dd(lambda: dd(int)) for _ in range(N)] sing_ = 0 back_ = 0 base = (ord('a')-1) for _ in range(M): S = getStrs() if S[0] == '+': u, v = [int(s)-1 for s in S[1:3]] c = ord(S[3])-base graph[u][v] = c d = graph[v][u] if not d: d = 0 if c == d: sing_ += 1 elif d != 0: back_ += 1 elif S[0] == '-': u, v = [int(s)-1 for s in S[1:3]] c = graph[u][v] d = graph[v][u] if not d: d = 0 if c == d: sing_ -= 1 elif d != 0: back_ -= 1 graph[u][v] = 0 else: k = int(S[1]) if k % 2 == 0: print("YES" if sing_ > 0 else "NO") else: print("YES" if back_+sing_ > 0 else "NO") return solve() ```
output
1
48,140
13
96,281
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1.
instruction
0
48,141
13
96,282
Tags: constructive algorithms, data structures, graphs, hashing Correct Solution: ``` import sys input = sys.stdin.readline n, m = map(int, input().split()) bothpathnum = 0 equalpathnum = 0 edge = dict() ans = [] for querynum in range(m): inpstr = input() if inpstr[0] == '+': u, v, c = inpstr[2:].split() u, v, c = int(u), int(v), ord(c) if v*n + u in edge and edge[v*n + u] != 0: bothpathnum += 1 if edge[v*n + u] == c: equalpathnum += 1 edge[u*n + v] = c elif inpstr[0] == '-': u, v = map(int, inpstr[2:].split()) if v*n + u in edge and edge[v*n + u] != 0: bothpathnum -= 1 if edge[v*n + u] == edge[u*n + v]: equalpathnum -= 1 edge[u*n + v] = 0 elif inpstr[0] == '?': k = int(inpstr[2:]) if k%2 == 0: if equalpathnum > 0: ans.append("YES") else: ans.append("NO") else: if bothpathnum > 0: ans.append("YES") else: ans.append("NO") print(*ans, sep='\n') ```
output
1
48,141
13
96,283
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1.
instruction
0
48,142
13
96,284
Tags: constructive algorithms, data structures, graphs, hashing Correct Solution: ``` """ #If FastIO not needed, use this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os, sys from io import BytesIO, IOBase from collections import defaultdict as dd import math, string BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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") def getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def isInt(s): return '0' <= s[0] <= '9' """ If K is odd, we need a back and forward pair of any description between two nodes U and V If K is even, we need a back and forward pair that is identical """ def solve(): N, M = getInts() graph = [dd(lambda: dd(int)) for _ in range(N)] sing_ = 0 back_ = 0 for _ in range(M): S = getStrs() if S[0] == '+': u, v = [int(s)-1 for s in S[1:3]] c = S[3] graph[u][v] = c d = graph[v][u] if not d: d = '0' if c == d: sing_ += 1 elif d != '0': back_ += 1 elif S[0] == '-': u, v = [int(s)-1 for s in S[1:3]] c = graph[u][v] d = graph[v][u] if not d: d = '0' if c == d: sing_ -= 1 elif d != '0': back_ -= 1 graph[u][v] = '0' else: k = int(S[1]) if k % 2 == 0: print("YES" if sing_ > 0 else "NO") else: print("YES" if back_+sing_ > 0 else "NO") return solve() ```
output
1
48,142
13
96,285
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 consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1. Submitted Solution: ``` def solve(): n, m = map(int, input().split());e = dict();same = 0;diff = 0;res = [] for i in range(m): a = input().split();c = a[0] if c == '+': u = int(a[1]);v = int(a[2]);c = a[3];z = e.get((v,u),None) if z == c: same += 1 elif z is not None: diff += 1 e[(u,v)] = c elif c == '-': u = int(a[1]);v = int(a[2]);c = e[(u,v)];del e[(u,v)];z = e.get((v,u),None) if z == c: same -= 1 elif z is not None: diff -= 1 else: c = int(a[1]) if c % 2 == 1: res.append('YES' if diff + same > 0 else 'NO') else: res.append('YES' if same > 0 else 'NO') print('\n'.join(res)) solve() ```
instruction
0
48,143
13
96,286
Yes
output
1
48,143
13
96,287
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 consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1. Submitted Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def floor_sum(n: int, m: int, a: int, b: int) -> int: ans = 0 if a >= m: ans += (n - 1) * n * (a // m) // 2 a %= m if b >= m: ans += n * (b // m) b %= m y_max = (a * n + b) // m x_max = y_max * m - b if y_max == 0: return ans ans += (n - (x_max + a - 1) // a) * y_max ans += floor_sum(y_max, a, m, (a - x_max % a) % a) return ans def xorfactorial(num):#排他的論理和の階乗 if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq inf = float("inf") que = [] d = [inf] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n): self.BIT=[0]*(n+1) self.num=n def query(self,idx): res_sum = 0 while idx > 0: res_sum += self.BIT[idx] idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): while idx <= self.num: self.BIT[idx] += x idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class Matrix(): mod=10**9+7 def set_mod(m): Matrix.mod=m def __init__(self,L): self.row=len(L) self.column=len(L[0]) self._matrix=L for i in range(self.row): for j in range(self.column): self._matrix[i][j]%=Matrix.mod def __getitem__(self,item): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item return self._matrix[i][j] def __setitem__(self,item,val): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item self._matrix[i][j]=val def __add__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]+other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __sub__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matrix[i][j]-other._matrix[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __mul__(self,other): if type(other)!=int: if self.column!=other.row: raise SizeError("sizes of matrixes are different") res=[[0 for j in range(other.column)] for i in range(self.row)] for i in range(self.row): for j in range(other.column): temp=0 for k in range(self.column): temp+=self._matrix[i][k]*other._matrix[k][j] res[i][j]=temp%Matrix.mod return Matrix(res) else: n=other res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)] return Matrix(res) def __pow__(self,m): if self.column!=self.row: raise MatrixPowError("the size of row must be the same as that of column") n=self.row res=Matrix([[int(i==j) for i in range(n)] for j in range(n)]) while m: if m%2==1: res=res*self self=self*self m//=2 return res def __str__(self): res=[] for i in range(self.row): for j in range(self.column): res.append(str(self._matrix[i][j])) res.append(" ") res.append("\n") res=res[:len(res)-1] return "".join(res) class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 class DualSegmentTree: def __init__(self, n, segfunc, ide_ele): self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num def update(self,l,r,x): l += self.num r += self.num while l < r: if l & 1: self.tree[l] = self.segfunc(self.tree[l],x) l += 1 if r & 1: self.tree[r-1] = self.segfunc(self.tree[r-1],x) l >>= 1 r >>= 1 def __getitem__(self,idx): idx += self.num res = self.ide_ele while idx: res = self.segfunc(res,self.tree[idx]) idx>>=1 return res class LazySegmentTree(): __slots__ = ["merge","merge_unit","operate","merge_operate","operate_unit","n","data","lazy"] def __init__(self,n,init,merge,merge_unit,operate,merge_operate,operate_unit): self.merge=merge self.merge_unit=merge_unit self.operate=operate self.merge_operate=merge_operate self.operate_unit=operate_unit self.n=(n-1).bit_length() self.data=[merge_unit for i in range(1<<(self.n+1))] self.lazy=[operate_unit for i in range(1<<(self.n+1))] if init: for i in range(n): self.data[2**self.n+i]=init[i] for i in range(2**self.n-1,0,-1): self.data[i]=self.merge(self.data[2*i],self.data[2*i+1]) def propagate(self,v): ope = self.lazy[v] if ope == self.operate_unit: return self.lazy[v]=self.operate_unit self.data[(v<<1)]=self.operate(self.data[(v<<1)],ope) self.data[(v<<1)+1]=self.operate(self.data[(v<<1)+1],ope) self.lazy[v<<1]=self.merge_operate(self.lazy[(v<<1)],ope) self.lazy[(v<<1)+1]=self.merge_operate(self.lazy[(v<<1)+1],ope) def propagate_above(self,i): m=i.bit_length()-1 for bit in range(m,0,-1): v=i>>bit self.propagate(v) def remerge_above(self,i): while i: c = self.merge(self.data[i],self.data[i^1]) i>>=1 self.data[i]=self.operate(c,self.lazy[i]) def update(self,l,r,x): l+=1<<self.n r+=1<<self.n l0=l//(l&-l) r0=r//(r&-r)-1 self.propagate_above(l0) self.propagate_above(r0) while l<r: if l&1: self.data[l]=self.operate(self.data[l],x) self.lazy[l]=self.merge_operate(self.lazy[l],x) l+=1 if r&1: self.data[r-1]=self.operate(self.data[r-1],x) self.lazy[r-1]=self.merge_operate(self.lazy[r-1],x) l>>=1 r>>=1 self.remerge_above(l0) self.remerge_above(r0) def query(self,l,r): l+=1<<self.n r+=1<<self.n l0=l//(l&-l) r0=r//(r&-r)-1 self.propagate_above(l0) self.propagate_above(r0) res=self.merge_unit while l<r: if l&1: res=self.merge(res,self.data[l]) l+=1 if r&1: res=self.merge(res,self.data[r-1]) l>>=1 r>>=1 return res def bisect_l(self,l,r,x): l += 1<<self.n r += 1<<self.n l0=l//(l&-l) r0=r//(r&-r)-1 self.propagate_above(l0) self.propagate_above(r0) Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.data[l][0] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.data[r-1][0] <=x: Rmin = r-1 l >>= 1 r >>= 1 res = -1 if Lmin != -1: pos = Lmin while pos<self.num: self.propagate(pos) if self.data[2 * pos][0] <=x: pos = 2 * pos else: pos = 2 * pos +1 res = pos-self.num if Rmin != -1: pos = Rmin while pos<self.num: self.propagate(pos) if self.data[2 * pos][0] <=x: pos = 2 * pos else: pos = 2 * pos +1 if res==-1: res = pos-self.num else: res = min(res,pos-self.num) return res def floor_sum(n: int, m: int, a: int, b: int) -> int: ans = 0 if a >= m: ans += (n - 1) * n * (a // m) // 2 a %= m if b >= m: ans += n * (b // m) b %= m y_max = (a * n + b) // m x_max = y_max * m - b if y_max == 0: return ans ans += (n - (x_max + a - 1) // a) * y_max ans += floor_sum(y_max, a, m, (a - x_max % a) % a) return ans def _inv_gcd(a,b): a %= b if a == 0: return (b, 0) # Contracts: # [1] s - m0 * a = 0 (mod b) # [2] t - m1 * a = 0 (mod b) # [3] s * |m1| + t * |m0| <= b s = b t = a m0 = 0 m1 = 1 while t: u = s // t s -= t * u m0 -= m1 * u # |m1 * u| <= |m1| * s <= b # [3]: # (s - t * u) * |m1| + t * |m0 - m1 * u| # <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u) # = s * |m1| + t * |m0| <= b s, t = t, s m0, m1 = m1, m0 # by [3]: |m0| <= b/g # by g != b: |m0| < b/g if m0 < 0: m0 += b // s return (s, m0) def crt(r,m): assert len(r) == len(m) n = len(r) # Contracts: 0 <= r0 < m0 r0 = 0 m0 = 1 for i in range(n): assert 1 <= m[i] r1 = r[i] % m[i] m1 = m[i] if m0 < m1: r0, r1 = r1, r0 m0, m1 = m1, m0 if m0 % m1 == 0: if r0 % m1 != r1: return (0, 0) continue # assume: m0 > m1, lcm(m0, m1) >= 2 * max(m0, m1) # im = inv(u0) (mod u1) (0 <= im < u1) g, im = _inv_gcd(m0, m1) u1 = m1 // g # |r1 - r0| < (m0 + m1) <= lcm(m0, m1) if (r1 - r0) % g: return (0, 0) # u1 * u1 <= m1 * m1 / g / g <= m0 * m1 / g = lcm(m0, m1) x = (r1 - r0) // g % u1 * im % u1 r0 += x * m0 m0 *= u1 # -> lcm(m0, m1) if r0 < 0: r0 += m0 return (r0, m0) import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import log,gcd input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) n,m = mi() dic = {} odd = 0 even = 0 for _ in range(m): query = input().split() if len(query)==2: k = int(query[1]) if k%2 and odd: print("YES") elif not k%2 and even: print("YES") else: print("NO") else: u,v = map(int,query[1:3]) if query[0]=="+": if (min(u,v),max(u,v)) not in dic: dic[min(u,v),max(u,v)] = [None,None] dic[min(u,v),max(u,v)][int(u<v)] = query[-1] U,V = min(u,v),max(u,v) if dic[U,V][0] and dic[U,V][1]: odd += 1 if dic[U,V][0] and dic[U,V][1] and dic[U,V][0]==dic[U,V][1]: even += 1 else: U,V = min(u,v),max(u,v) if dic[U,V][0] and dic[U,V][1]: odd -= 1 if dic[U,V][0] and dic[U,V][1] and dic[U,V][0]==dic[U,V][1]: even -= 1 dic[min(u,v),max(u,v)][int(u<v)] = None ```
instruction
0
48,144
13
96,288
Yes
output
1
48,144
13
96,289
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 consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1. Submitted Solution: ``` import sys from sys import stdin n,m = map(int,stdin.readline().split()) even = 0 odd = 0 lis = [ {} for i in range(n) ] #types = [ [ [0]*27 for i in range(27) ] for j in range(n) ] ans = [] for i in range(m): s = stdin.readline()[:-1] if s[0] == "+": ty,u,v,c = s.split() u,v = int(u),int(v) u -= 1 v -= 1 c = ord(c)-ord("a") lis[u][v] = c if u in lis[v]: if lis[v][u] == c: even += 1 odd += 1 elif s[0] == "-": ty,u,v= s.split() u,v = int(u),int(v) u -= 1 v -= 1 c = lis[u][v] del lis[u][v] if u in lis[v]: if lis[v][u] == c: even -= 1 odd -= 1 else: ty,k = s.split() k = int(k) if k % 2 == 0: if even > 0: ans.append("YES") else: ans.append("NO") else: if even == 0 and odd == 0: ans.append("NO") else: ans.append("YES") #print (even,odd) print ("\n".join(ans)) ```
instruction
0
48,145
13
96,290
Yes
output
1
48,145
13
96,291
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 consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1. Submitted Solution: ``` import sys from sys import stdin n, m = map(int, stdin.readline().split()) even = 0 odd = 0 arr = [{} for i in range(n)] ans = [] for i in range(m): s = stdin.readline()[:-1] if s[0] == "+": ty, u, v, c = s.split() u, v = int(u), int(v) u -= 1 v -= 1 c = ord(c) - ord("a") arr[u][v] = c if u in arr[v]: if arr[v][u] == c: even += 1 odd += 1 elif s[0] == "-": ty, u, v = s.split() u, v = int(u), int(v) u -= 1 v -= 1 c = arr[u][v] del arr[u][v] if u in arr[v]: if arr[v][u] == c: even -= 1 odd -= 1 else: ty, k = s.split() k = int(k) if k % 2 == 0: if even > 0: ans.append("YES") else: ans.append("NO") else: if even == 0 and odd == 0: ans.append("NO") else: ans.append("YES") # print (even,odd) print("\n".join(ans)) ```
instruction
0
48,146
13
96,292
Yes
output
1
48,146
13
96,293
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 consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1. Submitted Solution: ``` import io import os import sys #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline input = sys.stdin.readline def solve(): n, m = map(int, input().split()) double_edges = 0 same_double_edges = 0 g = [{} for _ in range(n)] for _ in range(m): t, *par = input().strip().split() if t == "+": u, v, c = par u = int(u) v = int(v) u -= 1 v -= 1 if u in g[v]: if v not in g[u]: double_edges += 1 if g[v][u] == c: same_double_edges += 1 g[u][v] = c elif t == "-": u, v = map(int, par) u -= 1 v -= 1 if u in g[v]: double_edges -= 1 if g[v][u] == g[u][v]: same_double_edges -= 1 del g[u][v] else: k = int(par[0]) if k%2 == 0: print("YES" if same_double_edges else "NO") else: print("YES" if double_edges else "NO") t = 1 for _ in range(t): solve() ```
instruction
0
48,147
13
96,294
No
output
1
48,147
13
96,295
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 consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1. Submitted Solution: ``` import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n,m = map(int,input().split()) print(n,m) matrix = {} pair = {} for r in range(m): s = input().split() print(s[0]) print(s[0]=='+') print(s[0]==ord('+')) print(s[0]=='') if s[0]=='+': matrix[(int(s[1]),int(s[2]))] = s[3] if (int(s[2]),int(s[1])) in matrix and matrix[(int(s[1]),int(s[2]))]==matrix[(int(s[2]),int(s[1]))]: num1 = min(int(s[1]),int(s[2])) num2 = max(int(s[1]),int(s[2])) pair[(num1,num2)] = 1 elif s[0] == '-': del matrix[(int(s[1]),int(s[2]))] num1 = min(int(s[1]),int(s[2])) num2 = max(int(s[1]),int(s[2])) if (num1,num2) in pair: del pair[(num1,num2)] else: k = int(s[1]) if k%2==1: print("YES") else: if len(pair)>0: print("YES") else: print("NO") ```
instruction
0
48,148
13
96,296
No
output
1
48,148
13
96,297
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 consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1. Submitted Solution: ``` s = input() print('YES' if ('1111111' in s or '0000000' in s) else 'NO') ```
instruction
0
48,149
13
96,298
No
output
1
48,149
13
96,299
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 consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment; * "- u v" — erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment; * "? k" — find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 → v_2 → ... → v_k and v_k → v_{k - 1} → ... → v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of queries. The next m lines contain queries — one per line. Each query is one of three types: * "+ u v c" (1 ≤ u, v ≤ n; u ≠ v; c is a lowercase Latin letter); * "- u v" (1 ≤ u, v ≤ n; u ≠ v); * "? k" (2 ≤ k ≤ 10^5). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. Output For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise. Example Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES Note In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1. In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters. In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1. Submitted Solution: ``` import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n,m = map(int,input().split()) print(n,m) matrix = {} pair = {} for r in range(m): s = input().split() print(s[0]) if s[0]=='+': matrix[(int(s[1]),int(s[2]))] = s[3] if (int(s[2]),int(s[1])) in matrix and matrix[(int(s[1]),int(s[2]))]==matrix[(int(s[2]),int(s[1]))]: num1 = min(int(s[1]),int(s[2])) num2 = max(int(s[1]),int(s[2])) pair[(num1,num2)] = 1 elif s[0] == '-': del matrix[(int(s[1]),int(s[2]))] num1 = min(int(s[1]),int(s[2])) num2 = max(int(s[1]),int(s[2])) if (num1,num2) in pair: del pair[(num1,num2)] else: k = int(s[1]) if k%2==1: print("YES") else: if len(pair)>0: print("YES") else: print("NO") ```
instruction
0
48,150
13
96,300
No
output
1
48,150
13
96,301
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7
instruction
0
48,283
13
96,566
Tags: dfs and similar, trees Correct Solution: ``` import sys lines = sys.stdin.readlines() n = int(lines[0].strip()) edges = {} for i in range(1,n): (u, v) = map(int, lines[i].strip().split(" ")) if u not in edges: edges[u] = [] if v not in edges: edges[v] = [] edges[u].append(v) edges[v].append(u) fst = list(map(int, lines[n].strip().split(" "))) goals = list(map(int, lines[n+1].strip().split(" "))) curr = [0 for _ in range(n)] for i in range(n): goals[i] ^= fst[i] for i in range(1, n+1): if i not in edges: edges[i] = [] parent = {} seen = set([1]) stack = [1] while stack: node = stack.pop() for adj in edges[node]: if adj not in seen: seen.add(adj) stack.append(adj) parent[adj] = node cnt = 0 stack = [1] flip = [] seen = set([1]) while stack: node = stack.pop() if node not in parent or parent[node] not in parent: if goals[node-1] != curr[node-1]: cnt += 1 flip.append(node) curr[node-1] = goals[node-1] else: grandpa = parent[parent[node]] if goals[node-1] != curr[grandpa-1]: cnt += 1 flip.append(node) curr[node-1] = goals[node-1] for adj in edges[node]: if adj not in seen: stack.append(adj); seen.add(adj) print(cnt) for node in flip: print(node) ```
output
1
48,283
13
96,567
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7
instruction
0
48,284
13
96,568
Tags: dfs and similar, trees Correct Solution: ``` n = int(input()) p = [[] for i in range(n + 1)] for i in range(n - 1): a, b = map(int, input().split()) p[a].append(b) p[b].append(a) u, v = ' ' + input()[:: 2], ' ' + input()[:: 2] s, q = [(1, 0, 0, 0)], [] while s: a, k, i, j = s.pop() if k: if i != (u[a] != v[a]): q.append(a) i = 1 - i else: if j != (u[a] != v[a]): q.append(a) j = 1 - j k = 1 - k for b in p[a]: p[b].remove(a) s.append((b, k, i, j)) print(len(q)) print('\n'.join(map(str, q))) ```
output
1
48,284
13
96,569
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7
instruction
0
48,285
13
96,570
Tags: dfs and similar, trees Correct Solution: ``` # Made By Mostafa_Khaled bot = True n = int(input()) p = [[] for i in range(n + 1)] for i in range(n - 1): a, b = map(int, input().split()) p[a].append(b) p[b].append(a) u, v = ' ' + input()[:: 2], ' ' + input()[:: 2] s, q = [(1, 0, 0, 0)], [] while s: a, k, i, j = s.pop() if k: if i != (u[a] != v[a]): q.append(a) i = 1 - i else: if j != (u[a] != v[a]): q.append(a) j = 1 - j k = 1 - k for b in p[a]: p[b].remove(a) s.append((b, k, i, j)) print(len(q)) print('\n'.join(map(str, q))) # Made By Mostafa_Khaled ```
output
1
48,285
13
96,571
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7
instruction
0
48,286
13
96,572
Tags: dfs and similar, trees Correct Solution: ``` from collections import defaultdict, deque from typing import Any, List, Tuple def solve( n: int, adj: List[List[int]], init: List[int], goal: List[int] ) -> List[int]: g = defaultdict(list) # type: Any for u, v in adj: g[u].append(v) g[v].append(u) visited = [0] * n q = deque([[1, 0, 0, 0]]) ops = [] while q: curr, height, even_ops, odd_ops = q.popleft() visited[curr - 1] = 1 if height % 2 == 0: if init[curr - 1] ^ [0, 1][even_ops % 2] != goal[curr - 1]: even_ops += 1 ops.append(curr) elif height % 2 == 1: if init[curr - 1] ^ [0, 1][odd_ops % 2] != goal[curr - 1]: odd_ops += 1 ops.append(curr) for neighbor in g[curr]: if not visited[neighbor - 1]: q.append([neighbor, height + 1, even_ops, odd_ops]) return ops n = int(input()) adj = [list(map(int, input().split())) for _ in range(n-1)] init = list(map(int, input().split())) goal = list(map(int, input().split())) ans = solve(n, adj, init, goal) print(len(ans)) for x in ans: print(x) ```
output
1
48,286
13
96,573
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7
instruction
0
48,287
13
96,574
Tags: dfs and similar, trees Correct Solution: ``` #Getting out of comfort zone is the first step of revolution import sys import threading for test in range(1): n = int(input()) global adj adj = list([] for i in range(n+1)) for i in range(n-1): a,b = map(int,input().split()) adj[a].append(b) adj[b].append(a) cur = [0] + list(map(int,input().split())) tobe = [0] + list(map(int,input().split())) ans = 0 op = [] def dfs(node,par=-1,par_changes=0,gpar_changes=0): if gpar_changes%2: cur[node] ^=1 if cur[node] != tobe[node]: cur[node]^=1 global ans ans+=1 global op op.append(node) gpar_changes += 1 for child in adj[node]: if child == par:continue dfs(child,node,gpar_changes,par_changes) def main(): dfs(1) print(ans) for i in op:print(i) if __name__=="__main__": sys.setrecursionlimit(10**6) threading.stack_size(10**8) t = threading.Thread(target=main) t.start() t.join() ```
output
1
48,287
13
96,575
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7
instruction
0
48,288
13
96,576
Tags: dfs and similar, trees Correct Solution: ``` n=int(input()) L=[[] for i in range(n)] for i in range(n-1) : a,b=map(int,input().split()) L[a-1].append(b-1) L[b-1].append(a-1) l=list(map(int,input().split())) l1=list(map(int,input().split())) W=[] for i in range(n) : W.append(abs(l[i]-l1[i])) was=[0 for i in range(n)] q=[[0,0,0]] ans=[] while q : e=q[0] was[e[0]]=1 if e[1]!=W[e[0]] : ans.append(e[0]+1) e[1]=1-e[1] for x in L[e[0]] : if was[x]==0 : q.append([x,e[2],e[1]]) del q[0] print(len(ans)) print('\n'.join(map(str,ans))) ```
output
1
48,288
13
96,577
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7
instruction
0
48,289
13
96,578
Tags: dfs and similar, trees Correct Solution: ``` # 429A __author__ = 'artyom' def read_int(): return int(input()) def read_int_ary(): return map(int, input().split()) n = read_int() g = [[] for x in range(n + 1)] for i in range(n - 1): u, v = read_int_ary() g[u].append(v) g[v].append(u) init = [0] + list(read_int_ary()) goal = [0] + list(read_int_ary()) s = [] # def solve(graph, level, state, node, parent=-1): # t = level % 2 # st = list(state) # if init[node] ^ st[t] == goal[node]: # s.append(node) # st[t] = 1 - st[t] # for child in graph[node]: # if child != parent: # solve(graph, level + 1, st, child, node) def solve(graph, start): stack = [(start, -1, [1, 1], 0)] while stack: params = stack.pop(-1) node = params[0] parent = params[1] st = list(params[2]) sign = params[3] if init[node] ^ st[sign] == goal[node]: s.append(node) st[sign] ^= 1 sign ^= 1 for child in graph[node]: if child != parent: stack.append((child, node, st, sign)) solve(g, 1) print(len(s)) for v in s: print(v) ```
output
1
48,289
13
96,579
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7
instruction
0
48,290
13
96,580
Tags: dfs and similar, trees Correct Solution: ``` import sys import math from collections import defaultdict MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): sys.stdout.write() pass class dfsData: def __init__(self): self.total = 0 def dfsHelper(adjList, start, goal, cur, explored, xor, data): if start[cur] != goal[cur]: data.total += 1 xor = (xor + 1) % 2 for ele in adjList[cur]: if ele not in explored: explored[ele] = True dfs(adjList, start, goal, ele, explored, xor, data) def dfs(adjList, start, goal): explored = dict() explored[1] = True # root data = dfsData() dfsHelper(adjList, start, goal, 1, explored, 0, data) return data.total def iterdfs(adjList, init, goal): stack = [] start = (1, 0, 0) # node, xorstate, xor2down stack.append(start) explored = {} explored[start] = True total = 0 flip = [] while stack: curNode, xor, nxtXor = stack.pop() if (init[curNode] + xor) % 2 != goal[curNode]: # print(curNode, init[curNode], xor, goal[curNode], "hi") total += 1 xor = (xor + 1) % 2 flip.append(curNode) for ele in adjList[curNode]: if ele not in explored: explored[ele] = True stack.append((ele, nxtXor, xor)) return total, flip def solve(adjList, start, goal): """working assumption: it's always better to go down the tree""" return iterdfs(adjList, start, goal) def readinput(): edges = getInt() adjList = defaultdict(list) for _ in range(edges - 1): a, b = getInts() adjList[a].append(b) adjList[b].append(a) start = [0] + list(getInts()) goal = [0] + list(getInts()) t, f = solve(adjList, start, goal) print(t) for ele in f: print(ele) readinput() ```
output
1
48,290
13
96,581
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7 Submitted Solution: ``` import sys read = lambda t=int: list(map(t,sys.stdin.readline().split())) n, = read() graph = [[] for _ in range(n)] for _ in range(n-1): a,b = read() graph[a-1].append(b-1) graph[b-1].append(a-1) initial = read() goal = read() ansList = [] def dfs(node, par, odd, even, level): if level == 0: if initial[node]^even != goal[node]: ansList.append(node) even^=1 if level == 1: if initial[node]^odd != goal[node]: ansList.append(node) odd^=1 for item in graph[node]: if item!=par: yield(item, node, odd, even, level^1) stack = [(0,-1,0,0,0)] while stack: for item in dfs(*stack.pop()): stack.append(item) print(len(ansList)) for ele in ansList: print(ele+1) ```
instruction
0
48,292
13
96,584
Yes
output
1
48,292
13
96,585
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22
instruction
0
48,783
13
97,566
"Correct Solution: ``` # -*- coding: utf-8 -*- import random import sys import os class Tree: def __init__(self): self.root = None def __str__(self): if self.root == None: return None else: return "TODO" def print_inorder(self): self.inorder_list = [] self.__inorder(self.root) return self.inorder_list def __inorder(self, node): """ :param node: Node :return: """ if node is None: return else: self.__inorder(node.left) self.inorder_list.append(node.key) self.__inorder(node.right) def print_preorder(self): self.preorder_list = [] self.__preorder(self.root) return self.preorder_list def __preorder(self, node): """ :param node: Node :return: """ if node is None: return else: self.preorder_list.append(node.key) self.__preorder(node.left) self.__preorder(node.right) def insert(self, node): """ :param node: Node :return: """ if self.root is None: self.root = node else: x = self.root parent_candidate = x while x is not None: parent_candidate = x if x.key > node.key: x = x.left else: x = x.right # child to parent link x = node x.parent = parent_candidate # parent to child link if x.key < x.parent.key: x.parent.left = x else: x.parent.right = x def find(self, value): """ :param value: :rtype: Node :return: """ x = self.root while x is not None and x.key != value: if x.key > value: x = x.left else: x = x.right return x def delete(self, value): found_node = self.find(value) if found_node is None: print("value is nothing") else: # has no child if found_node.is_leaf(): # delete link from parent # print(found_node.parent.left.key) # print(found_node.key) if found_node.parent.left is not None and found_node.parent.left.key == found_node.key: found_node.parent.left = None else: found_node.parent.right = None else: # has one child if found_node.has_one_child(): one_child = found_node.get_one_child() # change link to parent one_child.parent = found_node.parent # chagne link from parent if found_node.parent.left == found_node: found_node.parent.left = one_child else: found_node.parent.right = one_child # has two child else: next_section_point = found_node.get_next_section_point() # ?¬???????????????????????????????????????????????¬?????????????????????? p217 # ???????????? key = next_section_point.key self.delete(next_section_point.key) found_node.key = key class Node: def __init__(self, key): self.parent = None # type: Node self.left = None # type: Node self.right = None # type: Node self.key = key # type: int def has_one_child(self): if self.left is None and self.right is not None: return True elif self.left is not None and self.right is None: return True else: return False def get_one_child(self): if not self.has_one_child(): return None else: if self.left is not None: return self.left else: return self.right def get_next_section_point(self): """?¬??????????????????????""" # ????????????????????´??? if self.right is not None: return self.right.get_minimum() # ???????????????????????´???????¬???????????????´????????? else: # ? return self.parent def is_leaf(self): if self.left is None and self.right is None: return True else: return False def get_minimum(self): if self.left is None: return self else: return self.left.get_minimum() tree = Tree() s = input() n = int(s) for _ in range(n): s = input() if 'insert' in s: value = int(s.split(" ")[-1]) node = Node(value) tree.insert(node) if 'print' in s: in_list = tree.print_inorder() in_list = map(str, in_list) print(' ' + ' '.join(in_list)) pre_list = tree.print_preorder() pre_list = map(str, pre_list) print(' ' + ' '.join(pre_list)) if 'find' in s: value = int(s.split(" ")[-1]) node = tree.find(value) if node is None: print('no') else: print('yes') if 'delete' in s: value = int(s.split(" ")[-1]) tree.delete(value) ```
output
1
48,783
13
97,567
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22
instruction
0
48,784
13
97,568
"Correct Solution: ``` #http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_8_A #???????????? 15??? 8A???????????? def insert(root, insert_node): focus_node = root parent = None while not focus_node == None: parent = focus_node if focus_node["data"] > insert_node["data"]: focus_node = focus_node["left"] else: focus_node = focus_node["right"] if parent["data"] > insert_node["data"]: parent["left"] = insert_node insert_node["parent"] = parent else: parent["right"] = insert_node insert_node["parent"] = parent def get_preorder(node): if node == None: return [] r = [] r.append(str(node["data"])) r.extend(get_preorder(node["left"])) r.extend(get_preorder(node["right"])) return r def get_inorder(node): if node == None: return [] r = [] r.extend(get_inorder(node["left"])) r.append(str(node["data"])) r.extend(get_inorder(node["right"])) return r def delete_tree(root, target): delete_node = find_tree(root, target) parent = delete_node["parent"] if parent["left"] == delete_node: parent_direction = "left" else: parent_direction = "right" while True: if delete_node["left"] == None and delete_node["right"] == None: parent[parent_direction] = None break elif delete_node["left"] and delete_node["right"]: p = get_inorder(root) next_num = int(p[p.index(str(delete_node["data"])) + 1]) tmp_delete_node = find_tree(root, next_num) delete_node["data"] = next_num delete_node = tmp_delete_node parent = delete_node["parent"] if parent == None: parent_direction = None elif parent["left"] == delete_node: parent_direction = "left" else: parent_direction = "right" else: if delete_node["left"]: parent[parent_direction] = delete_node["left"] delete_node["left"]["parent"] = parent else: parent[parent_direction] = delete_node["right"] delete_node["right"]["parent"] = parent break def find_tree(root, target): focus_node = root while not focus_node == None: if focus_node["data"] == target: return focus_node elif focus_node["data"] < target: focus_node = focus_node["right"] else: focus_node = focus_node["left"] return None def print_tree(root): print(" " + " ".join(get_inorder(root))) print(" " + " ".join(get_preorder(root))) def main(): n_line = int(input()) input_list = [input() for i in range(n_line)] root = {"left":None, "right": None, "data":int(input_list[0].split()[1]), "parent": None} for line in input_list[1:]: if line == "print": print_tree(root) else: split_line = line.split() if split_line[0] == "insert": node = {"left":None, "right": None, "data":int(split_line[1]), "parent":None} insert(root, node) elif split_line[0] == "find": if find_tree(root, int(split_line[1])): print("yes") else: print("no") elif split_line[0] == "delete": delete_tree(root, int(split_line[1])) if __name__ == "__main__": main() ```
output
1
48,784
13
97,569
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22
instruction
0
48,785
13
97,570
"Correct Solution: ``` # coding: utf-8 class Node: def __init__(self, me, left, right): self.me = me self.left = left self.right = right self.parent = None class NodeTree: def __init__(self, root=None): self.root = root def insert(self,z): y = None x = self.root while x != None: y = x if z.me < x.me: x = x.left else: x = x.right z.parent = y if y == None: self.root = z elif z.me < y.me: y.left = z else: y.right = z def find(self, key): y = None x = self.root while True: if x.me == key: return x elif x.me > key: if x.left != None: x = x.left else: return None else: if x.right != None: x = x.right else: return None def delete(self, key): z = self.find(key) if z.left == None and z.right == None: if z.parent.left == z: z.parent.left = None else: z.parent.right = None elif z.left != None and z.right == None: if z.parent.left == z: z.parent.left = z.left z.left.parent = z.parent if z.parent.right == z: z.parent.right = z.left z.left.parent = z.parent elif z.left == None and z.right != None: if z.parent.left == z: z.parent.left = z.right z.right.parent = z.parent if z.parent.right == z: z.parent.right = z.right z.right.parent = z.parent else: #y = nextPos(z) # z.right.left.left....の最下層 y = z.right while y.left != None: y = y.left p = y.me self.delete(y.me) z.me = p def getPreorder(self, node, ans): ans.append(node) if node.left != None: self.getPreorder(node.left, ans) if node.right != None: self.getPreorder(node.right, ans) def getInorder(self, node, ans): if node.left != None: self.getInorder(node.left, ans) ans.append(node) if node.right != None: self.getInorder(node.right, ans) def printAns(ans): for a in ans: print(" " + str(a.me),end="") print() m = int(input().rstrip()) nt = NodeTree() for i in range(m): line = input().rstrip().split() if line[0] == "insert": nt.insert(Node(int(line[1]),None,None)) elif line[0] == "find": if nt.find(int(line[1])) != None: print("yes") else: print("no") elif line[0] == "delete": nt.delete(int(line[1])) else: ans = [] nt.getInorder(nt.root,ans) printAns(ans) ans = [] nt.getPreorder(nt.root,ans) printAns(ans) ```
output
1
48,785
13
97,571
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22
instruction
0
48,786
13
97,572
"Correct Solution: ``` class Node: def __init__(self, key): self.key = key self.right = None self.left = None class BST: root = None def insert(self, key): x = self.root y = None z = Node(key) while x != None: y = x if(z.key < y.key): x = x.left elif(y.key < z.key): x = x.right if y is None: # 初回 self.root = z else: # yがターゲットになっているので if z.key < y.key: y.left = z elif y.key < z.key: y.right = z def preorder(self, par): if par is not None: print(" {}".format(par.key), end="") self.preorder(par.left) self.preorder(par.right) def inorder(self, par): if par is not None: self.inorder(par.left) print(" {}".format(par.key), end="") self.inorder(par.right) def find(self, key): x = self.root y = None z = Node(key) flag = False while x is not None: y = x if(z.key < y.key): x = x.left elif(y.key < z.key): x = x.right else: flag = True break return flag def delete(self, key): if self.find(key): x = self.root y = None while x is not None: y = x if(key < y.key): x = x.left elif(y.key < key): x = x.right else: # rootが対象のノードの場合 break if(x.key == key): break # yが親、子のxがdeleteの対象 x_children = [c for c in [x.left, x.right] if c is not None] if len(x_children) == 0: # 親から子の情報を削除 for c in [y.left, y.right]: if c is not None and c.key == key: # yの左右どっちにcがあるのか同定してx_children[0]をぶちこむ which_side = [i for i, x in enumerate([y.left, y.right]) if x is not None and x.key == c.key][0] if which_side == 0: # 左側 y.left = None else: # 右側 y.right = None elif len(x_children) == 1: # 子の子を親の子にする(字面が妙な雰囲気) for c in [y.left, y.right]: if c is not None and c.key == key: # yの左右どっちにcがあるのか同定してx_children[0]をぶちこむ which_side = [i for i, x in enumerate([y.left, y.right]) if x is not None and x.key == c.key][0] if which_side == 0: # 左側 y.left = x_children[0] else: # 右側 y.right = x_children[0] else: # print("ふたこぶ") # print("key: {}".format(key)) # 削除予定の子から左側のうち最大のものをとってきて、削除予定のやつを削除したのちそこに入れる # とやったらなぜか右側の最小値で出すのが想定される解らしい どっちでもあってんだろが min_child = x.right # 一つ上の親を保持 par = x while True: if min_child.left is None: break par = min_child min_child = min_child.left # print("min_childの親が知りたい {}".format(par.key)) if(par.key == key): # 初っ端で終了した(下る世代の数が1) pass else: par.left = None min_child.right = x.right # 大本の削除対象のxの親であるyの左右どちらがxであるか同定し更新 x_side = [i for i, s in enumerate([y.left, y.right]) if s is not None and s.key == x.key][0] # それを直接min_childとする if x_side == 0: # 左 y.left = min_child else: # 右 y.right = min_child min_child.left = x.left # print("---------------------------") n = int(input()) bst = BST() for _ in range(n): query = input().split() if query[0] == "insert": bst.insert(int(query[1])) elif query[0] == "find": print("yes" if bst.find(int(query[1])) else "no") elif query[0] == "print": # 中間巡回順, 先行巡回順 root = bst.root bst.inorder(root) print() bst.preorder(root) print() elif query[0] == "delete": bst.delete(int(query[1])) ```
output
1
48,786
13
97,573
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22
instruction
0
48,787
13
97,574
"Correct Solution: ``` # 二分探索 データの削除から クラス定義を用いて class Node: def __init__(self, key): self.key = key self.parent = None self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, key): root_node = self.root insert_node = Node(key) parent_node = None while root_node: parent_node = root_node if insert_node.key < root_node.key: root_node = root_node.left else: root_node = root_node.right insert_node.parent = parent_node if parent_node == None: self.root = insert_node elif insert_node.key < parent_node.key: parent_node.left = insert_node else: parent_node.right = insert_node def find(self, key): node = self.root while node: if node.key == key: return node elif node.key < key: node = node.right else: node = node.left return None def delete(self, key): node = self.find(key) if node == None: return if node.left and node.right: next_node = node.right while next_node.left: next_node = next_node.left node.key = next_node.key node = next_node if node.left: node.left.parent = node.parent if node.parent.left == node: node.parent.left = node.left else: node.parent.right = node.left elif node.right: node.right.parent = node.parent if node.parent.left == node: node.parent.left = node.right else: node.parent.right = node.right else: if node.parent.left == node: node.parent.left = None else: node.parent.right = None def show_inorder(self, node): if node == None: return self.show_inorder(node.left) print(' ' + str(node.key), end = '') self.show_inorder(node.right) def show_preorder(self, node): if node == None: return print(' ' + str(node.key), end = '') self.show_preorder(node.left) self.show_preorder(node.right) tree = BinarySearchTree() n = int(input()) for i in range(n): command = input().split() if command[0] == 'insert': tree.insert(int(command[1])) elif command[0] == 'find': a = tree.find(int(command[1])) if a != None: print('yes') else: print('no') elif command[0] == 'delete': tree.delete(int(command[1])) elif command[0] == 'print': tree.show_inorder(tree.root) print() tree.show_preorder(tree.root) print() ```
output
1
48,787
13
97,575
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22
instruction
0
48,788
13
97,576
"Correct Solution: ``` import sys class Node: __slots__ = ['key', 'left', 'right'] def __init__(self, key): self.key = key self.left = self.right = None root = None def delete(target): def remove_node(p, c, a): if p.left == c: p.left = a else: p.right = a p, c = None, root while c.key != target: p, c = c, c.left if target < c.key else c.right if c.left is None: remove_node(p, c, c.right) elif c.right is None: remove_node(p, c, c.left) elif c.right.left is None: c.right.left = c.left remove_node(p, c, c.right) else: g = c.right while g.left.left: g = g.left c.key = g.left.key g.left = g.left.right def find(target): result = root while result and target != result.key: result = result.left if target < result.key else result.right if result is None: return False else: return True def insert(key): global root y = None # xの親 x = root while x: y = x x = x.left if key < x.key else x.right if y is None: # Tが空の場合 root = Node(key) elif key < y.key: y.left = Node(key) else: y.right = Node(key) def in_order(node): if node is None: return '' return in_order(node.left) + f' {node.key}' + in_order(node.right) def pre_order(node): if node is None: return '' return f' {node.key}' + pre_order(node.left) + pre_order(node.right) input() for e in sys.stdin: if e[0] == 'i': insert(int(e[7:])) elif e[0] == 'd': delete(int(e[7:])) elif e[0] == 'f': print('yes' if find(int(e[5:])) else 'no') else: print(in_order(root)) print(pre_order(root)) ```
output
1
48,788
13
97,577
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22
instruction
0
48,789
13
97,578
"Correct Solution: ``` import sys readline = sys.stdin.readline from copy import deepcopy, copy class Node: __slots__ = ['value', 'left', 'right'] def __init__(self, value=None): self.value = value self.left = None self.right = None class BinTree: __slots__ = ['_tree', 'result'] def __init__(self): self._tree = None def insert(self, value): p = None c = self._tree while c is not None: p = c if value < c.value: c = c.left else: c = c.right if p is None: self._tree = Node(value) elif value < p.value: p.left = Node(value) else: p.right = Node(value) def find(self, value): c = self._tree while c is not None: if value == c.value: return True elif value < c.value: c = c.left else: c = c.right return False def delete(self, value): parent = None current = self._tree while current.value != value: parent = current if current is None: return elif value < current.value: current = current.left else: current = current.right if current.left is None and current.right is None: if parent.left is current: parent.left = None else: parent.right = None elif current.left is None: if parent.left is current: parent.left = current.right else: parent.right = current.right elif current.right is None: if parent.left is current: parent.left = current.left else: parent.right = current.left else: next_node_parent = current next_node = current.right while next_node.left is not None: next_node_parent = next_node next_node = next_node.left if next_node.right is None: if next_node_parent.left is next_node: next_node_parent.left = None else: next_node_parent.right = None else: if next_node_parent.left is next_node: next_node_parent.left = next_node.right else: next_node_parent.right = next_node.right current.value = next_node.value def preoder_walk(self): self.result = [] def preoder(node): if node is not None: self.result.append(node.value) preoder(node.left) preoder(node.right) preoder(self._tree) print(" " + " ".join(map(str, self.result))) def inorder_walk(self): self.result = [] def inorder(node): if node is not None: inorder(node.left) self.result.append(node.value) inorder(node.right) inorder(self._tree) print(" " + " ".join(map(str, self.result))) n = int(input()) tree = BinTree() for _ in range(n): com = readline().split() if com[0] == "insert": tree.insert(int(com[1])) elif com[0] == "find": print("yes" if tree.find(int(com[1])) else "no") elif com[0] == "delete": tree.delete(int(com[1])) else: tree.inorder_walk() tree.preoder_walk() ```
output
1
48,789
13
97,579
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22
instruction
0
48,790
13
97,580
"Correct Solution: ``` import sys # def input(): # return sys.stdin.readline()[:-1] # n = int(input()) # A = [input() for i in range(n)] class Node(): __slots__ = ['key', 'left', 'right','parent'] def __init__(self, key): self.key = key self.left = None self.right = None self.parent = None def insert(key): global root x = root # x is current node y = None # parent of x while x: y = x # set parent if key < x.key: x = x.left # move to left child else: x = x.right #move to right child if root is None: root = Node(key) elif key < y.key: # set z as left child of y y.left = Node(key) y.left.parent = y else: y.right = Node(key) # set z as right child of y y.right.parent = y def find(key): global root x = root while x: if key==x.key: print('yes') return elif key < x.key: x = x.left else: x = x.right print('no') def minimum(x): while x.left: x = x.left return x def successor(x): if x.right: return minimum(x.right) y = x.parent while (y) and (x==y.right): x = y y = y.parent return y def delete(key): global root # find z z = None x = root while x: if key==x.key: z = x break elif key < x.key: x = x.left else: x = x.right if z is None: return # determin y if (z.left==None) or (z.right==None): y = z else: y = successor(z) if y.left: x = y.left else: x = y.right if x: x.parent = y.parent if y.parent is None: root = x elif y==y.parent.left: y.parent.left = x else: y.parent.right = x if y!=z: z.key = y.key def inorder(inorder_list, node): if node.left is not None: inorder(inorder_list, node.left) inorder_list.append(str(node.key)) if node.right is not None: inorder(inorder_list, node.right) return inorder_list def preorder(preorder_list, node): preorder_list.append(str(node.key)) if node.left is not None: preorder(preorder_list, node.left) if node.right is not None: preorder(preorder_list, node.right) return preorder_list root = None input() for o in sys.stdin: if o[0]=='i': insert(int(o[7:])) elif o[0]=='f': find(int(o[5:])) elif o[0]=='d': delete(int(o[7:])) else: x = root inorder_list = inorder([], x) print(' '+' '.join(inorder_list)) preorder_list = preorder([], x) print(' '+' '.join(preorder_list)) ```
output
1
48,790
13
97,581
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 Submitted Solution: ``` import sys class Node: __slots__ = ['key', 'left', 'right'] def __init__(self, key): self.key = key self.left = self.right = None root = None def insert(key): global root x, y = root, None while x is not None: x, y = x.left if key < x.key else x.right, x if y is None: root = Node(key) elif key < y.key: y.left = Node(key) else: y.right = Node(key) def find(target): result = root while result and target != result.key: result = result.left if target < result.key else result.right return result is None def delete(target): def remove_node(p, c, a): if p.left == c: p.left = a else: p.right = a p, c = None, root while c.key != target: p, c = c, c.left if target < c.key else c.right if c.left is None: remove_node(p, c, c.right) elif c.right is None: remove_node(p, c, c.left) elif c.right.left is None: c.right.left = c.left remove_node(p, c, c.right) else: g = c.right while g.left.left is not None: g = g.left c.key = g.left.key g.left = g.left.right def inorder(node): return inorder(node.left) + f' {node.key}' + inorder(node.right) if node else '' def preorder(node): return f' {node.key}' + preorder(node.left) + preorder(node.right) if node else '' input() for e in sys.stdin: if e[0] == 'i': insert(int(e[7:])) elif e[0] == 'd': delete(int(e[7:])) elif e[0] == 'f': print(['yes','no'][find(int(e[5:]))]) else: print(inorder(root)); print(preorder(root)) ```
instruction
0
48,791
13
97,582
Yes
output
1
48,791
13
97,583
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 Submitted Solution: ``` class Tree: def __init__(self): self.root = None def insert(self, key): z = Node(key) y = None # x?????????????´????????????° # z???parent???????´? x = self.root while x: y = x if z.key < x.key: x = x.left else: x = x.right z.parent = y # z??????????????´??????????´? if y is None: self.root = z elif z.key < y.key: y.left = z else: y.right = z def find(self, key): x = self.root while x and key != x.key: if key < x.key: x = x.left else: x = x.right return x def getSuccessor(self, x): if x.right is not None: return self.getMinimum(x.right) y = x.parent while y and x == y.right: x = y y = y.parent return y def getMinimum(self, x): while x.left is not None: x = x.left return x def delete(self, key): #??????????±????y???????´? z = self.find(key) if z.left is None or z.right is None: y = z else: y = self.getSuccessor(z) # y??????x???????????? if y.left is not None: x = y.left else: x = y.right if x is not None: x.parent = y.parent if y.parent is None: self.root = x elif y == y.parent.left: y.parent.left = x else: y.parent.right = x if y != z: z.key = y.key def show(self): print(" ", end="") print(*list(map(str, self.root.inwalk()))) print(" ", end="") print(*list(map(str, self.root.prewalk()))) class Node: def __init__(self, key): self.key = key self.parent = self.left = self.right = None def prewalk(self): nodeList = [self.key] if self.left: nodeList += self.left.prewalk() if self.right: nodeList += self.right.prewalk() return nodeList def inwalk(self): nodeList = [] if self.left: nodeList += self.left.inwalk() nodeList += [self.key] if self.right: nodeList += self.right.inwalk() return nodeList tree = Tree() n = int(input()) for i in range(n): cmd = list(input().split()) if cmd[0] == 'insert': tree.insert(int(cmd[1])) elif cmd[0] == 'find': if tree.find(int(cmd[1])): print("yes") else: print("no") elif cmd[0] == 'print': tree.show() elif cmd[0] == 'delete': tree.delete(int(cmd[1])) ```
instruction
0
48,792
13
97,584
Yes
output
1
48,792
13
97,585
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 Submitted Solution: ``` class Node: def __init__(self, num): self.key = num self.p = None self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, z): y = None x = self.root while x != None: y = x if z.key < x.key: x = x.left else: x = x.right z.p = y if y is None: self.root = z elif z.key < y.key: y.left = z else: y.right = z def find(self, key): node = self.root while node: if node.key == key: return node if key < node.key: node = node.left else: node = node.right return None def find_minimum(self, node): while node.left: node = node.left return node def delete(self, node): if node.left and node.right: m = self.find_minimum(node.right) node.key = m.key self.delete(m) elif node.left: self.update(node, node.left) elif node.right: self.update(node, node.right) else: self.update(node, None) def update(self, node, new_node): if node.key < node.p.key: node.p.left = new_node else: node.p.right = new_node if new_node: new_node.p = node.p def print_inorder(node): if node is None: return print_inorder(node.left) print(" {}".format(node.key), end="") print_inorder(node.right) def print_preorder(node): if node is None: return print(" {}".format(node.key), end="") print_preorder(node.left) print_preorder(node.right) T = BinarySearchTree() for i in range(int(input())): params = input().split() if params[0] == "insert": T.insert(Node(int(params[1]))) elif params[0] == "find": if T.find(int(params[1])): print("yes") else: print("no") elif params[0] == "delete": node = T.find(int(params[1])) if node: T.delete(node) elif params[0] == "print": print_inorder(T.root) print("") print_preorder(T.root) print("") ```
instruction
0
48,793
13
97,586
Yes
output
1
48,793
13
97,587
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ input: 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print output: found + in_order + pre_order yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 """ import sys class Node(object): __slots__ = ('data', 'left', 'right') def __init__(self, data): self.data = data self.left, self.right = None, None def insert(self, data): """ Insert data according to BST rules """ if data < self.data: if not self.left: self.left = Node(data) else: self.left.insert(data) # insert duplicate value to right else: if not self.right: self.right = Node(data) else: self.right.insert(data) return self.data def find(self, data, parent=None): """ Find node with given data, tree walk as insert goes """ if data < self.data: if not self.left: return None, None return self.left.find(data=data, parent=self) elif data > self.data: if not self.right: return None, None return self.right.find(data=data, parent=self) else: return self, parent def children_count(self): """ For choosing node deleting strategy """ cnt = 0 if self.left: cnt += 1 if self.right: cnt += 1 return cnt def delete(self, data): """ delete node with given data """ node, parent = self.find(data) if node: children_count = node.children_count() if not children_count: # delete reference to parent if parent.left is node: parent.left = None else: parent.right = None del node elif children_count == 1: # node's son becomes parents' son if node.left: n = node.left else: n = node.right if parent: if parent.left is node: parent.left = n else: parent.right = n del node else: # current node has two real children(as a partial root) # while the real successor couldn't have two real children successor = node.right while successor.left: successor = successor.left copy_data = successor.data self.delete(copy_data) node.data = copy_data def pre_order(node): if node: print('', node.data, end='') pre_order(node.left) pre_order(node.right) return None def in_order(node): if node: in_order(node.left) print('', node.data, end='') in_order(node.right) return None def in_order_yield(node): if node.left: yield from in_order_yield(node.left) yield node.data if node.right: yield from in_order_yield(node.right) def pre_order_yield(node): yield node.data for n in [node.left, node.right]: if n: yield from pre_order_yield(n) def action(_command, _content): # start all action from tree_root -- insert, find, delete, print if _command.startswith('in'): tree_root.insert(int(_content)) elif _command.startswith('fi'): if tree_root.find(int(_content)) == (None, None): print('no') else: print('yes') elif _command.startswith('de'): tree_root.delete(int(_content)) # print tree walk else: # in_order(tree_root) # print('') # pre_order(tree_root) # print('') print('', *in_order_yield(tree_root)) print('', *pre_order_yield(tree_root)) return None if __name__ == '__main__': _input = sys.stdin.readlines() array_length = int(_input[0]) command_list = list(map(lambda x: x.split(), _input[1:])) # assert len(command_list) == array_length flag, tree_root = False, None allowed_commands = ('insert', 'print', 'delete', 'find') for each in command_list: command, content = each[0], each[-1] if command not in allowed_commands: raise SystemExit('Illegal command!') # init the whole tree if not flag: if not command.startswith('in'): raise SystemExit('Please insert tree root first.') flag, tree_root = True, Node(data=int(content)) continue action(command, content) ```
instruction
0
48,794
13
97,588
Yes
output
1
48,794
13
97,589
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 Submitted Solution: ``` import sys class Node: __slots__ = ['key', 'left', 'right'] def __init__(self, key): self.key = key self.left = self.right = None root = None def insert(key): global root x, y = root, None while x is not None: x, y = x.left if key < x.key else x.right, x if y is None: root = Node(key) elif key < y.key: y.left = Node(key) else: y.right = Node(key) def find(target): result = root while result and target != result.key: result = result.left if target < result.key else result.right return result is None def delete(target): def remove_node(p, c, a): if p.left == c: p.left = a else: p.right = a p, c = None, root while c.key != target: p, c = c, c.left if target < c.key else c.right if c.left is None: remove_node(p, c, c.right) elif c.right is None: remove_node(p, c, c.left) elif c.right.left is None: c.right.left = c.left remove_node(p, c, c.right) else: g = c.right.left while g.left is not None: g = g.left c.key = g.key g = g.right def inorder(node): return inorder(node.left) + f' {node.key}' + inorder(node.right) if node else '' def preorder(node): return f' {node.key}' + preorder(node.left) + preorder(node.right) if node else '' input() for e in sys.stdin: if e[0] == 'i': insert(int(e[7:])) elif e[0] == 'd': delete(int(e[7:])) elif e[0] == 'f': print(['yes','no'][find(int(e[5:]))]) else: print(inorder(root)); print(preorder(root)) ```
instruction
0
48,795
13
97,590
No
output
1
48,795
13
97,591
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 Submitted Solution: ``` #http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_8_A #???????????? 15??? 8A???????????? def insert(root, insert_node): focus_node = root parent = None while not focus_node == None: parent = focus_node if focus_node["data"] > insert_node["data"]: focus_node = focus_node["left"] else: focus_node = focus_node["right"] if parent["data"] > insert_node["data"]: parent["left"] = insert_node insert_node["parent"] = parent else: parent["right"] = insert_node insert_node["parent"] = parent def get_preorder(node): if node == None: return [] r = [] r.append(str(node["data"])) r.extend(get_preorder(node["left"])) r.extend(get_preorder(node["right"])) return r def get_inorder(node): if node == None: return [] r = [] r.extend(get_inorder(node["left"])) r.append(str(node["data"])) r.extend(get_inorder(node["right"])) return r def delete_tree(root, target): delete_node = None focus_node = root parent = None node_direction = "" while focus_node: if target == focus_node["data"]: delete_node = focus_node break elif focus_node["data"] < target: parent = focus_node node_direction = "right" focus_node = focus_node["right"] else: parent = focus_node node_direction = "left" focus_node = focus_node["left"] if delete_node == None: return while True: if delete_node["left"] == None and delete_node["right"] == None: parent[node_direction] = None break elif delete_node["left"] and delete_node["right"]: p = get_inorder(root) next_num = int(p[p.index(str(delete_node["data"])) + 1]) delete_node["data"] = next_num delete_node = find_tree(root, next_num) parent = delete_node["parent"] if parent == None: node_direction = None elif parent["left"] == delete_node: node_direction = "left" else: node_direction = "right" else: if delete_node["left"]: parent[node_direction] = delete_node["left"] delete_node["left"]["parent"] = parent else: parent[node_direction] = delete_node["right"] delete_node["right"]["parent"] = parent break def find_tree(root, target): focus_node = root while not focus_node == None: if focus_node["data"] == target: return focus_node elif focus_node["data"] < target: focus_node = focus_node["right"] else: focus_node = focus_node["left"] return None def print_tree(root): print(" " + " ".join(get_inorder(root))) print(" " + " ".join(get_preorder(root))) def main(): n_line = int(input()) input_list = [input() for i in range(n_line)] root = {"left":None, "right": None, "data":int(input_list[0].split()[1]), "parent": None} for line in input_list[1:]: if line == "print": print_tree(root) else: split_line = line.split() if split_line[0] == "insert": node = {"left":None, "right": None, "data":int(split_line[1]), "parent":None} insert(root, node) elif split_line[0] == "find": if find_tree(root, int(split_line[1])): print("yes") else: print("no") elif split_line[0] == "delete": delete_tree(root, int(split_line[1])) if __name__ == "__main__": main() ```
instruction
0
48,796
13
97,592
No
output
1
48,796
13
97,593
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 Submitted Solution: ``` import sys NIL = -1 class Node: def __init__(self, key): self.key = key self.parent = NIL self.left = NIL self.right = NIL class Tree: def __init__(self): self.root = NIL def insert(self, z): y = NIL x = self.root while x != NIL: y = x if z.key < x.key: x = x.left else: x = x.right z.parent = y if y == NIL: self.root = z elif z.key < y.key: y.left = z else: y.right = z def find(self, value, node): if node == NIL: return False elif node.key == value: return True elif value < node.key: # print('go to left') return self.find(value, node=node.left) else: # print('go to right') return self.find(value, node=node.right) def delete(self, value, node): if node == NIL: return None elif value < node.key: self.delete(value, node.left) elif value > node.key: self.delete(value, node.right) else: check = (node.left != NIL) + (node.right != NIL) if check == 0: if node.parent.left.key == value: node.parent.left = NIL else: node.parent.right = NIL elif check == 1: if node.left != NIL: child = node.left else: child = node.right if node.parent.left.key == value: node.parent.left = child child.parent = node.parent else: node.parent.right = child child.parent = node.parent else: node = node.right self.delete(node.key, node.right) def inorder_walk(self, node): if node == NIL: return None if node.left != NIL: self.inorder_walk(node=node.left) print(' ' + str(node.key), end='') if node.right != NIL: self.inorder_walk(node=node.right) def preorder_walk(self, node): if node == NIL: return None print(' ' + str(node.key), end='') if node.left != NIL: self.preorder_walk(node=node.left) if node.right != NIL: self.preorder_walk(node=node.right) def show(self): self.inorder_walk(self.root) print() self.preorder_walk(self.root) print() n = int(sys.stdin.readline()) T = Tree() for i in range(n): line = sys.stdin.readline().split() if len(line) == 1: T.show() elif line[0] == 'insert': key = int(line[1]) T.insert(Node(key)) elif line[0] == 'find': key = int(line[1]) print('yes' if T.find(key, T.root) else 'no') else: key = int(line[1]) T.delete(key, T.root) ```
instruction
0
48,797
13
97,594
No
output
1
48,797
13
97,595
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases: 1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$). 2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent. 3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key Example Input 18 insert 8 insert 2 insert 3 insert 7 insert 22 insert 1 find 1 find 2 find 3 find 4 find 5 find 6 find 7 find 8 print delete 3 delete 7 print Output yes yes yes no no no yes yes 1 2 3 7 8 22 8 2 1 3 7 22 1 2 8 22 8 2 1 22 Submitted Solution: ``` from io import StringIO class BinaryTree: class Node: def __init__(self, key): self.key = key self.left = None self.right = None self.parent = None def __init__(self): self.root = None self.output = StringIO() def insert(self, key): if self.root is None: self.root = self.Node(key) else: root = self.root temp = None while True: temp = root if key > root.key: root = root.right if root is None: temp.right = self.Node(key) n = temp.right n.parent = temp break else: root = root.left if root is None: temp.left = self.Node(key) n = temp.left n.parent = temp break def ini_print_inorder(self): self.output = StringIO() self.print_inorder(self.root) return self.output.getvalue() def ini_print_preorder(self): self.output = StringIO() self.print_preorder(self.root) return self.output.getvalue() def print_inorder(self, node): if node is not None: self.print_inorder(node.left) print(node.key, end = " ", file = self.output) self.print_inorder(node.right) def print_preorder(self, node): if node is not None: print(node.key, end = " ", file = self.output) self.print_preorder(node.left) self.print_preorder(node.right) def test_insert(self, keys): for k in keys: self.insert(k) def ini_find(self, key): print(self.find(key)) def find(self, key): root = self.root while root is not None: if key == root.key: return "yes" elif key < root.key: root = root.left else: root = root.right return "no" def delete(self, key): root = self.root temp = root act = "" while root is not None: if key == root.key: # print(root.key, root.left, root.right, root.parent) rest = None if root.left is None: new_leaf = root.right elif root.right is None: new_leaf = root.left else: new_leaf = root.left rest = root.right if act != "": setattr(temp, act, new_leaf) else: self.root = new_leaf if rest is not None: temp = getattr(temp, act) setattr(temp, act, rest) return else: temp = root if key < root.key: root = root.left act = "left" else: root = root.right act = "right" b = BinaryTree() length = int(input()) for _ in range(length): comm = input() if comm[0] == "i": com, num = comm.split(" ") b.insert(int(num)) elif comm[0] == "p": print(" ", end = "") print((b.ini_print_inorder())[:-1]) print(" ", end = "") print(b.ini_print_preorder()[:-1]) elif comm[0] == "f": com, num = comm.split(" ") b.ini_find(int(num)) else: com, num = comm.split(" ") b.delete(int(num)) ```
instruction
0
48,798
13
97,596
No
output
1
48,798
13
97,597
Provide tags and a correct Python 3 solution for this coding contest problem. You have an integer n. Let's define following tree generation as McDic's generation: 1. Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. 2. Select a non-root vertex v from that binary tree. 3. Remove v from tree and make new edges between v's parent and v's direct children. If v has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree. Input The first line contains integer n (2 ≤ n ≤ 17). The i-th of the next 2^{n} - 3 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ 2^{n} - 2) — meaning there is an edge between a_{i} and b_{i}. It is guaranteed that the given edges form a tree. Output Print two lines. In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print 0. In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything. Examples Input 4 1 2 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 Output 1 3 Input 2 1 2 Output 2 1 2 Input 3 1 2 2 3 3 4 4 5 5 6 Output 0 Note In the first example, 3 is the only possible answer. <image> In the second example, there are 2 possible answers. <image> In the third example, the tree can't be generated by McDic's generation.
instruction
0
48,927
13
97,854
Tags: constructive algorithms, implementation, trees Correct Solution: ``` #!/usr/bin/python3 import array import math import os import sys DEBUG = 'DEBUG' in os.environ def inp(): return sys.stdin.readline().rstrip() def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) def solve(N, M, G): if N == 2: return [0, 1] degv = [set() for _ in range(5)] for i in range(M): d = len(G[i]) if d == 0 or d >= 5: return [] degv[d].add(i) layer_vcount = 1 << (N - 1) vs = degv[1] levels = [0] * M ans = [] for level in range(1, N): #dprint('level', level, [x for x in levels]) #dprint('vs', vs) #dprint('layer_vcount', layer_vcount) if len(vs) not in (layer_vcount - 1, layer_vcount): return [] if len(vs) == layer_vcount - 1: if ans: return [] if level == 1: sp_deg_off = -1 else: sp_deg_off = 1 else: sp_deg_off = 0 #dprint('sp_deg_off', sp_deg_off) ndeg = 3 if level < N - 1 else 2 us = set() ss = set() for v in vs: #dprint('v', v) levels[v] = level p = None for u in G[v]: if levels[u] == 0: if p is not None: return [] p = u break #dprint(' p', p) if p is None: return [] deg = len(G[p]) #dprint(' deg', deg) if deg == ndeg: us.add(p) elif deg == ndeg + sp_deg_off: ss.add(p) elif sp_deg_off == 0 and deg == ndeg + 1: ss.add(p) else: return [] #dprint('us', us) #dprint('ss', ss) if sp_deg_off != 0: if len(ss) != 1: return [] (sp,) = list(ss) ans = [sp] us.add(sp) if sp_deg_off == 0: if level == N - 2: if ss: return [] if not ans: li = list(us) li.sort() return li if len(ss) > 1: return [] vs = us layer_vcount >>= 1 return ans def main(): N = int(inp()) M = (1 << N) - 2 G = [[] for _ in range(M)] for _ in range(M - 1): a, b = [int(e) - 1 for e in inp().split()] G[a].append(b) G[b].append(a) ans = solve(N, M, G) print(len(ans)) if ans: print(*[v + 1 for v in ans]) if __name__ == '__main__': main() ```
output
1
48,927
13
97,855
Provide tags and a correct Python 3 solution for this coding contest problem. You have an integer n. Let's define following tree generation as McDic's generation: 1. Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. 2. Select a non-root vertex v from that binary tree. 3. Remove v from tree and make new edges between v's parent and v's direct children. If v has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree. Input The first line contains integer n (2 ≤ n ≤ 17). The i-th of the next 2^{n} - 3 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ 2^{n} - 2) — meaning there is an edge between a_{i} and b_{i}. It is guaranteed that the given edges form a tree. Output Print two lines. In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print 0. In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything. Examples Input 4 1 2 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 Output 1 3 Input 2 1 2 Output 2 1 2 Input 3 1 2 2 3 3 4 4 5 5 6 Output 0 Note In the first example, 3 is the only possible answer. <image> In the second example, there are 2 possible answers. <image> In the third example, the tree can't be generated by McDic's generation.
instruction
0
48,928
13
97,856
Tags: constructive algorithms, implementation, trees Correct Solution: ``` #!/usr/bin/python3 import array import math import os import sys DEBUG = 'DEBUG' in os.environ def inp(): return sys.stdin.readline().rstrip() def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) def solve(N, M, G): if N == 2: return [0, 1] degv = [set() for _ in range(5)] for i in range(M): d = len(G[i]) if d == 0 or d >= 5: return [] degv[d].add(i) layer_vcount = 1 << (N - 1) vs = degv[1] levels = bytearray(M) ans = [] for level in range(1, N): #dprint('level', level, [x for x in levels]) #dprint('vs', vs) #dprint('layer_vcount', layer_vcount) if len(vs) not in (layer_vcount - 1, layer_vcount): return [] if len(vs) == layer_vcount - 1: if ans: return [] if level == 1: sp_deg_off = -1 else: sp_deg_off = 1 else: sp_deg_off = 0 #dprint('sp_deg_off', sp_deg_off) ndeg = 3 if level < N - 1 else 2 us = set() ss = set() for v in vs: #dprint('v', v) levels[v] = level p = None for u in G[v]: if levels[u] == 0: if p is not None: return [] p = u break #dprint(' p', p) if p is None: return [] deg = len(G[p]) #dprint(' deg', deg) if deg == ndeg: us.add(p) elif deg == ndeg + sp_deg_off: ss.add(p) elif sp_deg_off == 0 and deg == ndeg + 1: ss.add(p) else: return [] #dprint('us', us) #dprint('ss', ss) if sp_deg_off != 0: if len(ss) != 1: return [] (sp,) = list(ss) ans = [sp] us.add(sp) if sp_deg_off == 0: if level == N - 2: if ss: return [] if not ans: li = list(us) li.sort() return li if len(ss) > 1: return [] vs = us layer_vcount >>= 1 return ans def main(): N = int(inp()) M = (1 << N) - 2 G = [[] for _ in range(M)] for _ in range(M - 1): a, b = [int(e) - 1 for e in inp().split()] G[a].append(b) G[b].append(a) ans = solve(N, M, G) print(len(ans)) if ans: print(*[v + 1 for v in ans]) if __name__ == '__main__': main() ```
output
1
48,928
13
97,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have an integer n. Let's define following tree generation as McDic's generation: 1. Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. 2. Select a non-root vertex v from that binary tree. 3. Remove v from tree and make new edges between v's parent and v's direct children. If v has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree. Input The first line contains integer n (2 ≤ n ≤ 17). The i-th of the next 2^{n} - 3 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ 2^{n} - 2) — meaning there is an edge between a_{i} and b_{i}. It is guaranteed that the given edges form a tree. Output Print two lines. In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print 0. In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything. Examples Input 4 1 2 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 Output 1 3 Input 2 1 2 Output 2 1 2 Input 3 1 2 2 3 3 4 4 5 5 6 Output 0 Note In the first example, 3 is the only possible answer. <image> In the second example, there are 2 possible answers. <image> In the third example, the tree can't be generated by McDic's generation. Submitted Solution: ``` def dfsUtil(u,visited,depth): visited[u] = True try: for v in g[u]: depth[v] = depth[u]+1 dfsUtil(v,visited,depth) except KeyError: return def DFS(root): visited = [False]*N depth = [1]*N dfsUtil(root,visited,depth) for i in range (N): num = len(g[i]) if (depth[i]==n-1 and num==1) or (depth[i]<n-1 and num==3): ans = i+1 break elif (depth[i]==n-1 and num not in ([1,2])) or (depth[i]<n-1 and num not in ([2,3])): ans = None break if ans == None: print("0") else: print("1\n",str(ans),sep="") n = int(input()) N = pow(2,n) - 2 g = dict() def addEdge(u,v): g.setdefault(u-1,list()).append(v-1) i,j = map(int,input().split()) addEdge(i,j) root = i-1 for i in range (N-2): u,v = map(int,input().split()) addEdge(u,v) if N==2: ans = "2\n"+"1 2" else: DFS(root) ```
instruction
0
48,929
13
97,858
No
output
1
48,929
13
97,859
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have an integer n. Let's define following tree generation as McDic's generation: 1. Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. 2. Select a non-root vertex v from that binary tree. 3. Remove v from tree and make new edges between v's parent and v's direct children. If v has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree. Input The first line contains integer n (2 ≤ n ≤ 17). The i-th of the next 2^{n} - 3 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ 2^{n} - 2) — meaning there is an edge between a_{i} and b_{i}. It is guaranteed that the given edges form a tree. Output Print two lines. In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print 0. In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything. Examples Input 4 1 2 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 Output 1 3 Input 2 1 2 Output 2 1 2 Input 3 1 2 2 3 3 4 4 5 5 6 Output 0 Note In the first example, 3 is the only possible answer. <image> In the second example, there are 2 possible answers. <image> In the third example, the tree can't be generated by McDic's generation. Submitted Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() from collections import deque n = int(input()) N = 2**n-2 M = N-1 X = [[] for i in range(N*3)] for i in range(M): x, y = map(int, input().split()) X[x-1].append(y-1) X[y-1].append(x-1) def BFS(n, E, i0=0, mid = 0): Q = deque([i0]) D = [-1] * n D[i0] = 0 while Q: x = Q.popleft() for c in X[x]: if D[c] == -1: D[c] = D[x] + 1 Q.append(c) ma = -1 mai = -1 for i in range(N): if D[i] > ma: ma = D[i] mai = i if mid: for i in range(N): if D[i] == mid: return i return (ma, mai) aa = BFS(N, X, 0)[1] di, bb = BFS(N, X, aa) cc = BFS(N, X, aa, di//2) # Root print(aa, bb, cc, di) P = [-1] * N Q = [cc] D = [0] * N while Q: i = Q.pop() for a in X[i][::-1]: if a != P[i]: P[a] = i D[a] = D[i] + 1 X[a].remove(i) Q.append(a) # print("X =", X) # print("P =", P) # print("D =", D) c3 = 0 i3 = -1 if n == 2: print(2) print(1, 2) else: if max(D) != n-1: print(0) else: for i in range(N): if len(X[i]) == 3: c3 += 1 i3 = i if c3 == 1: print(1) print(i3+1) else: print(0) ```
instruction
0
48,930
13
97,860
No
output
1
48,930
13
97,861
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have an integer n. Let's define following tree generation as McDic's generation: 1. Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. 2. Select a non-root vertex v from that binary tree. 3. Remove v from tree and make new edges between v's parent and v's direct children. If v has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree. Input The first line contains integer n (2 ≤ n ≤ 17). The i-th of the next 2^{n} - 3 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ 2^{n} - 2) — meaning there is an edge between a_{i} and b_{i}. It is guaranteed that the given edges form a tree. Output Print two lines. In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print 0. In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything. Examples Input 4 1 2 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 Output 1 3 Input 2 1 2 Output 2 1 2 Input 3 1 2 2 3 3 4 4 5 5 6 Output 0 Note In the first example, 3 is the only possible answer. <image> In the second example, there are 2 possible answers. <image> In the third example, the tree can't be generated by McDic's generation. Submitted Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() from collections import deque n = int(input()) if n == 2: print(2) print(1, 2) else: N = 2**n-2 M = N-1 X = [[] for i in range(N)] for i in range(M): x, y = map(int, input().split()) X[x-1].append(y-1) X[y-1].append(x-1) def BFS(n, E, i0=0, mid = 0): Q = deque([i0]) D = [-1] * n D[i0] = 0 while Q: x = Q.popleft() for c in X[x]: if D[c] == -1: D[c] = D[x] + 1 Q.append(c) ma = -1 mai = -1 for i in range(N): if D[i] > ma: ma = D[i] mai = i if mid: for i in range(N): if D[i] == mid: return i return (ma, mai) aa = BFS(N, X, 0)[1] di, bb = BFS(N, X, aa) cc = BFS(N, X, aa, di//2) # Root # print(aa, bb, cc, di) P = [-1] * N Q = [cc] D = [0] * N while Q: i = Q.pop() for a in X[i][::-1]: if a != P[i]: P[a] = i D[a] = D[i] + 1 X[a].remove(i) Q.append(a) # print("X =", X) # print("P =", P) # print("D =", D) c3 = 0 i3 = -1 c1 = 0 i1 = -1 c4 = 0 if max(D) != n-1: print(0) else: for i in range(N): if len(X[i]) == 1: c1 += 1 i1 = i if len(X[i]) == 3: c3 += 1 i3 = i if len(X[i]) >= 4: c4 += 1 if c4 or (c1+c3) >= 2 or (c1+c3) == 0: print(0) if c1: print(1) print(i1+1) if c3: print(1) print(i3+1) ```
instruction
0
48,931
13
97,862
No
output
1
48,931
13
97,863
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have an integer n. Let's define following tree generation as McDic's generation: 1. Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. 2. Select a non-root vertex v from that binary tree. 3. Remove v from tree and make new edges between v's parent and v's direct children. If v has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree. Input The first line contains integer n (2 ≤ n ≤ 17). The i-th of the next 2^{n} - 3 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ 2^{n} - 2) — meaning there is an edge between a_{i} and b_{i}. It is guaranteed that the given edges form a tree. Output Print two lines. In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print 0. In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything. Examples Input 4 1 2 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 Output 1 3 Input 2 1 2 Output 2 1 2 Input 3 1 2 2 3 3 4 4 5 5 6 Output 0 Note In the first example, 3 is the only possible answer. <image> In the second example, there are 2 possible answers. <image> In the third example, the tree can't be generated by McDic's generation. Submitted Solution: ``` def dfsUtil(u,visited,depth): visited[u] = True try: for v in g[u]: depth[v] = depth[u]+1 dfsUtil(v,visited,depth) except KeyError: return def DFS(root): visited = [False]*N depth = [1]*N dfsUtil(root,visited,depth) for i in range (N): num = len(g[i]) if (depth[i]==n-1 and num==1) or (depth[i]<n-1 and num==3): ans = i+1 break elif (depth[i]==n-1 and num not in ([1,2])) or (depth[i]<n-1 and num not in ([2,3])): ans = None break if ans == None: print("0") else: print("1\n",str(ans),sep="") n = int(input()) N = pow(2,n) - 2 g = dict() def addEdge(u,v): g.setdefault(u-1,list()).append(v-1) i,j = map(int,input().split()) addEdge(i,j) root = i-1 for i in range (N-2): u,v = map(int,input().split()) addEdge(u,v) if N==2: ans = "2\n"+"1 2" print(ans) else: DFS(root) ```
instruction
0
48,932
13
97,864
No
output
1
48,932
13
97,865
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\right⌋). Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make ∑_{v ∈ leaves} w(root, v) ≤ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≤ n ≤ 10^5; 1 ≤ S ≤ 10^{16}) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as three integers v_i, u_i and w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^6), where v_i and u_i are vertices the edge i connects and w_i is the weight of this edge. It is guaranteed that the sum of n does not exceed 10^5 (∑ n ≤ 10^5). Output For each test case, print the answer: the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most S. Example Input 3 3 20 2 1 8 3 1 7 5 50 1 3 100 1 5 10 2 3 123 5 4 55 2 100 1 2 409 Output 0 8 3
instruction
0
49,003
13
98,006
Tags: data structures, dfs and similar, greedy, trees Correct Solution: ``` """ NTC here """ #!/usr/bin/env python import os import sys from io import BytesIO, IOBase # from functools import lru_cache # sys.setrecursionlimit(10**6) # recusive with optimization from types import GeneratorType def bootstrap(f, stack=[]): 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 def dfs(adj, S=1): N = len(adj) parent = [False]*N dp = [0]*N # dp[i] = number of leaves in i th vertex edge_value = [] # store [w, number of leaves] @bootstrap def dfs_run(S): # print(S, end='->') ch = 0 leaves = 0 for v, w in adj[S]: if parent[v]==False: ch = 1 parent[v] = True lv = yield dfs_run(v) edge_value.append([w, lv]) leaves += lv # print(S, end='->') if ch==0: # leaf node dp[S] = 1 else: dp[S] = leaves yield dp[S] parent[S] = True dfs_run(S) # print(dp, edge_value) return edge_value # def dfs(adj, start=1): # n = len(adj) # visited = [False]*n # srt = [start] # parent = [-1]*n # dp = [0]*n # # dp[i] = number of leaves in i th vertex # edge_value = {} # # store [w, number of leaves] # while srt: # v = srt.pop() # # print(dp) # # print(v, end="->") # if visited[v]: # if parent[v] != -1: # S, w = parent[v] # dp[S] += dp[v] # if (v, S) not in edge_value: # edge_value[(v, S)] = [w, 0] # edge_value[(v, S)][1] += dp[v] # dp[v] = 0 # continue # visited[v] = True # if parent[v] != -1: # srt.append(parent[v][0]) # count_child = 0 # for u, w in adj[v]: # if not visited[u]: # count_child = 1 # parent[u] = [v, w] # srt.append(u) # if count_child==0: # # leaf node # dp[v] = 1 # if parent[v] != -1: # S, w = parent[v] # dp[S] += dp[v] # if (v, S) not in edge_value: # edge_value[(v, S)] = [w, 0] # edge_value[(v, S)][1] += dp[v] # dp[v] = 0 # # print(edge_value) # return list(edge_value.values()) import heapq as hq def main(): T = iin() while T: T-=1 n, S = lin() adj = [[] for i in range(n+1)] for _ in range(n-1): i, j, w = lin() adj[i].append([j, w]) adj[j].append([i, w]) edge_val = dfs(adj) # print('\n*******************************') Q = 0 ans = [] for w, num in edge_val: x = w while x: ans.append(x*num - (x//2)*num) x//=2 ans.sort() sm = sum([w*num for w, num in edge_val]) while sm>S and ans: val = ans.pop() sm -= val Q += 1 print(Q) # edge_val = [ [(w//2)*num-w*num, w, num] for w, num in edge_val] # hq.heapify(edge_val) # Q = 0 # while sm>S: # val, w, num = hq.heappop(edge_val) # # print(val, w, num) # sm = sm - (w*num) + ((w//2)*num) # w //= 2 # if w>0: # hq.heappush(edge_val, [(w//2)*num-w*num, w, num]) # Q += 1 # print(Q) # 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") def iin(): return int(input()) def lin(): return list(map(int, input().split())) # endregion if __name__ == "__main__": main() ```
output
1
49,003
13
98,007
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\right⌋). Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make ∑_{v ∈ leaves} w(root, v) ≤ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≤ n ≤ 10^5; 1 ≤ S ≤ 10^{16}) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as three integers v_i, u_i and w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^6), where v_i and u_i are vertices the edge i connects and w_i is the weight of this edge. It is guaranteed that the sum of n does not exceed 10^5 (∑ n ≤ 10^5). Output For each test case, print the answer: the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most S. Example Input 3 3 20 2 1 8 3 1 7 5 50 1 3 100 1 5 10 2 3 123 5 4 55 2 100 1 2 409 Output 0 8 3
instruction
0
49,004
13
98,008
Tags: data structures, dfs and similar, greedy, trees Correct Solution: ``` import sys import heapq input=sys.stdin.readline t = int(input()) for _ in range(t): n,s = list(map(int,input().split())) E = [] N = [[] for _ in range(n)] V = [] P = [-1 for _ in range(n)] E = {} for i in range(n-1): a,b,c = list(map(int,input().split())) a -= 1 b -= 1 N[a].append(b) N[b].append(a) E[(a,b)] = c E[(b,a)] = c visited = [False] * n visited[0] = True tp_sorted = [0] stack = [0] NN = [[] for _ in range(n)] while stack: v = stack.pop() for nxt_v in N[v]: if visited[nxt_v]: continue visited[nxt_v] = True NN[v].append(nxt_v) P[nxt_v] = v stack.append(nxt_v) tp_sorted.append(nxt_v) T = [1 for _ in range(n)] tp_sorted = tp_sorted[::-1] for v in tp_sorted: if len(NN[v])>0: temp = 0 for nxt_v in NN[v]: temp += T[nxt_v] T[v] = temp visited = [False] * n visited[0] = True stack = [0] nums = [] tot = 0 while stack: v = stack.pop() for nxt_v in N[v]: if visited[nxt_v]: continue visited[nxt_v] = True stack.append(nxt_v) temp = E[(v,nxt_v)] * T[nxt_v] jjj= E[(v,nxt_v)] // 2 gain = temp - (jjj*T[nxt_v]) tot += temp nums.append((-gain, E[(v,nxt_v)], T[nxt_v])) heapq.heapify(nums) c = 0 while tot>s: gain, xx, yy = heapq.heappop(nums) if s==1: tot -= (xx*yy) while xx>0: xx = xx // 2 c += 1 else: tot += gain xx = xx//2 gg = ((xx//2) * yy) - xx*yy heapq.heappush(nums, (gg,xx,yy)) c+=1 if s==1 and tot==0: c -= 1 print(c) ```
output
1
49,004
13
98,009