message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 66,579 | 13 | 133,158 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
#import io,os
#input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n = int(input())
neigh = [[] for i in range(n)]
for i in range(n-1):
u,v = map(int,input().split())
neigh[v-1].append(u-1)
neigh[u-1].append(v-1)
for i in range(n):
if len(neigh[i])==1:
root = i
break
queue = deque()
visited = [False]*n
visited[root] = True
queue.append([root,0])
leafneigh = {}
maximum = n-1
odd = 0
even = 0
while queue:
[index,d] = queue.popleft()
if len(neigh[index])==1:
if neigh[index][0] not in leafneigh:
leafneigh[neigh[index][0]]= d
if d%2==0: odd += 1
else: even += 1
else: maximum -= 1
for ele in neigh[index]:
if visited[ele]: continue
visited[ele] = True
queue.append([ele,d+1])
if min(odd,even)==0: minimum = 1
else: minimum = 3
#print(leafneigh)
#print(odd)
#print(even)
print(minimum,maximum)
``` | output | 1 | 66,579 | 13 | 133,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
n=int(input())
G={}
for i in range(n-1):
a,b=map(int,input().split())
try:
G[a].append(b)
except:
G[a]=[b]
try:
G[b].append(a)
except:
G[b]=[a]
leaves=[]
for i in G.keys():
if (len(G[i])==1):
leaves.append(i)
else:
sv=i
val=[-1 for i in range(n+1)]
Q=[sv]
val[sv]=0
tp=0
while(len(Q)!=0):
a=Q.pop()
iv=val[a]
tc=-1
for i in G[a]:
if (val[i]==-1):
val[i]=iv+1
if (len(G[i])==1):
tc=tc+1
else:
Q.append(i)
tp=tp+max(tc,0)
v=val[leaves[0]]
flag=0
for i in range(1,len(leaves)):
if (abs(val[leaves[i]]-v)%2!=0):
flag=1
break
if (flag==0):
print(1,end=" ")
else:
print(3,end=" ")
print(n-tp-1)
``` | instruction | 0 | 66,580 | 13 | 133,160 |
Yes | output | 1 | 66,580 | 13 | 133,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
# Fast IO (only use in integer input)
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
connectionList = []
for _ in range(n):
connectionList.append([])
for _ in range(n-1):
p,q = map(int,input().split())
connectionList[p-1].append(q-1)
connectionList[q-1].append(p-1)
leavesList = []
for i in range(n):
if len(connectionList[i]) == 1:
leavesList.append(i)
distance = [-1] * n
distance[0] = 0
dfsStack = [(0,0)]
while dfsStack:
elem,distanceCur = dfsStack.pop()
for v in connectionList[elem]:
if distance[v] == -1:
dfsStack.append((v,distanceCur + 1))
distance[v] = distanceCur + 1
mainDist = distance[leavesList[0]]
minAns = 1
for elem in leavesList:
if (distance[elem] - mainDist) % 2 != 0:
minAns = 3
break
oneUpLeaveList = []
for elem in leavesList:
oneUpLeaveList.append(connectionList[elem][0])
oneUpLeaveList.sort()
uniqueElement = 0
for i in range(len(oneUpLeaveList)):
if i == 0 or oneUpLeaveList[i-1] != oneUpLeaveList[i]:
uniqueElement += 1
maxAns = n - 1 - (len(oneUpLeaveList) - uniqueElement)
print(str(minAns) + " " + str(maxAns))
``` | instruction | 0 | 66,581 | 13 | 133,162 |
Yes | output | 1 | 66,581 | 13 | 133,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
import sys
# try:
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
# except:
# pass
input = sys.stdin.readline
def DFS(i):
visited = {i:True}
stack = [(i,0)]
while len(stack)!=0:
tail,depth = stack.pop(-1)
flag = True
for each in neigh[tail]:
if each not in visited:
visited[each] = True
flag = False
stack.append((each,depth+1))
if flag:
leafDepth.append(depth)
n = int(input())
neigh = [[] for i in range(n)]
l = []
for i in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
neigh[a].append(b)
neigh[b].append(a)
l.append((a,b))
#Max
edges = set()
for a, b in l:
if len(neigh[a]) == 1:
a = -1
if len(neigh[b]) == 1:
b = -1
if a > b:
a, b = b, a
edges.add((a,b))
MAX = len(edges)
#Min
leafDepth = []
DFS(0)
if (len(neigh[0])==1):
MIN = 1 if all([True if i%2==0 else False for i in leafDepth]) else 3
else:
MIN = 1 if all([True if i%2==0 else False for i in leafDepth]) or all([True if i%2==1 else False for i in leafDepth]) else 3
#Out
print(MIN, MAX)
``` | instruction | 0 | 66,582 | 13 | 133,164 |
Yes | output | 1 | 66,582 | 13 | 133,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
import collections
from collections import defaultdict
import sys
input=sys.stdin.readline
n=int(input())
graph=defaultdict(list)
for i in range(n-1):
a,b=map(int,input().split())
graph[a].append(b)
graph[b].append(a)
count=0
leavepar=[0]*(n+1)
leave=[]
for i in graph:
if len(graph[i])==1:
leave.append(i)
leavepar[graph[i][0]]+=1
if leavepar[graph[i][0]]>=2:
count+=1
def bfs(graph, root):
visited=set()
dist=[0]*(n+1)
queue=collections.deque([root])
visited.add(root)
while queue:
vertex=queue.popleft()
for neighbour in graph[vertex]:
if neighbour not in visited:
dist[neighbour]=dist[vertex]+1
visited.add(neighbour)
queue.append(neighbour)
return(dist)
ret=bfs(graph,1)
ans=1
even,odd=False,False
for i in leave:
if ret[i]%2==1:
odd=True
if ret[i]%2==0:
even=True
if even==True and odd==True:
ans=3
break
sys.stdout.write(str(ans)+' '+str(n-count-1)+'\n')
``` | instruction | 0 | 66,583 | 13 | 133,166 |
Yes | output | 1 | 66,583 | 13 | 133,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
import sys
sys.setrecursionlimit(11000)
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
def go():
n = int(input())
if n==2:
return '1 1'
# n,l,r = map(int, input().split())
# a = list(map(int, input().split()))
e = {i: set() for i in range(1, n + 1)}
rank = [0] * (n + 1)
root=-1
for _ in range(n - 1):
a, b = map(int, input().split())
e[a].add(b)
e[b].add(a)
rank[a] += 1
rank[b] += 1
if rank[a]>1:
root=a
if rank[b]>1:
root=b
mx = n-1
for a in range(1,n):
cnt=sum(rank[b]==1 for b in e[a])
mx-=max(0,cnt-1)
ev,od = False,False
que=[root]
i=0
dep = [0]*(n+1)
done = {root}
while i<len(que):
v = que[i]
if len(e[v])==1:
if dep[v]%2==0:
ev=True
if dep[v]%2==1:
od=True
for w in e[v]:
if w not in done:
que.append(w)
dep[w]=dep[v]+1
done.add(w)
i+=1
if ev and od:
mn=3
else:
mn=1
return f'{mn} {mx}'
#
# hei = [-1]*(n+1)
# def dfs(v,par):
# if len(e[v])==1:
# hei[v]=0
# else:
# hei[v]=min(dfs(w,v) for w in e[v] if w!=par)+1
# return hei[v]
#
# dfs(root,-1)
# # print (hei)
#
# kolej = sorted((i for i in range(1,n+1) if rank[i]>1),key=hei.__getitem__)
# print (kolej)
#
# res=0
# for v in kolej:
# if rank[v]
#
# que = [i for i in range(1, n + 1) if rank[i] == 1]
# dep = [0 if rank[i] == 1 else -1 for i in range(0, n + 1)]
# index = 0
# while index < len(que):
# cur = que[index]
# curd = dep[cur]
# for b in e[cur]:
# if dep[b] < 0:
# dep[b] = curd + 1
# que.append(b)
# index += 1
# print(dep)
# kolej = sorted(range(1, n + 1), key=dep.__getitem__)
# x,s = map(int,input().split())
# t = int(input())
t = 1
ans = []
for _ in range(t):
# print(go())
ans.append(str(go()))
#
print('\n'.join(ans))
``` | instruction | 0 | 66,584 | 13 | 133,168 |
No | output | 1 | 66,584 | 13 | 133,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
import collections
n1 = input()
n = int(n1)
if n == 2:
print(1, 1)
exit()
edges = [set() for _ in range(n)]
flag = [False] * n
for i in range(n - 1):
x = input()
a, b = x.split(' ')
a, b = int(a), int(b)
edges[a-1].add(b-1)
edges[b-1].add(a-1)
ocnt = collections.deque()
for i in range(n):
if len(edges[i]) == 1:
ocnt.append(i)
flag[i] = True
l, fl, f2 = 1, len(ocnt), None
while ocnt:
l = len(ocnt)
for _ in range(l):
x = ocnt.popleft()
for j in edges[x]:
edges[j].remove(x)
if len(edges[j]) == 1 and not flag[j]:
ocnt.append(j)
flag[j] = True
if not f2:
f2 = len(ocnt)
lo = 1 if l == 1 else 3
hi = n - fl + f2 - 1
print(lo, hi)
``` | instruction | 0 | 66,585 | 13 | 133,170 |
No | output | 1 | 66,585 | 13 | 133,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
import random
def getVal(used):
x = random.randint(1,10**40)
while x in used:
x = random.randint(1,10**40)
return x
def solve(edges,n,leaf):
stack = [leaf]
dp = [0]*(n+1)
dp2 = [0]*(n+1)
one = True
visited = set()
used = set()
while stack:
curr = stack.pop()
if curr not in visited:
visited.add(curr)
if len(edges[curr]) == 1 and dp2[curr] != 0:
one = False
for kid in edges[curr]:
if kid not in visited:
dp2[kid] = dp2[curr]^1
stack.append(kid)
val = getVal(used)
if len(edges[kid]) == 1:
used.add(dp[curr])
dp[kid] = 0
else:
dp[kid] = dp[curr]^val
used.add(val)
if one:
min_val = 1
else:
min_val = 3
print(min_val,len(used))
def main():
n = int(input())
edges = {}
for i in range(1,n+1):
edges[i] = []
for i in range(n-1):
a,b = map(int,input().split())
edges[a].append(b)
edges[b].append(a)
if len(edges[a]) == 1:
leaf = a
elif len(edges[b]) == 1:
leaf = b
solve(edges,n,leaf)
main()
``` | instruction | 0 | 66,586 | 13 | 133,172 |
No | output | 1 | 66,586 | 13 | 133,173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
import collections
n1 = input()
n = int(n1)
if n == 2:
print(1, 1)
exit()
edges = [set() for _ in range(n)]
for i in range(n - 1):
x = input()
a, b = x.split(' ')
a, b = int(a), int(b)
edges[a-1].add(b-1)
edges[b-1].add(a-1)
ocnt = collections.deque()
for i in range(n):
if len(edges[i]) == 1:
ocnt.append(i)
l, fl, flag = 1, len(ocnt), True
nl = set()
while ocnt:
l = len(ocnt)
for _ in range(l):
x = ocnt.popleft()
for j in edges[x]:
edges[j].remove(x)
if len(edges[j]) == 1:
ocnt.append(j)
if flag:
nl.add(j)
flag = False
lo = 1 if l == 1 else 3
hi = n - fl + len(nl) - 1
print(lo, hi)
``` | instruction | 0 | 66,587 | 13 | 133,174 |
No | output | 1 | 66,587 | 13 | 133,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected graph consisting of n vertices and m edges. Your goal is to destroy all edges of the given graph.
You may choose any vertex as the starting one and begin walking from it along the edges. When you walk along an edge, you destroy it. Obviously, you cannot walk along an edge if it is destroyed.
You can perform the mode shift operation at most once during your walk, and this operation can only be performed when you are at some vertex (you cannot perform it while traversing an edge). After the mode shift, the edges you go through are deleted in the following way: the first edge after the mode shift is not destroyed, the second one is destroyed, the third one is not destroyed, the fourth one is destroyed, and so on. You cannot switch back to the original mode, and you don't have to perform this operation if you don't want to.
Can you destroy all the edges of the given graph?
Input
The first line contains two integers n and m (2 ≤ n ≤ 3000; n - 1 ≤ m ≤ min((n(n-1))/(2), 3000)) — the numbef of vertices and the number of edges in the graph.
Then m lines follow, each containing two integers x_i and y_i (1 ≤ x_i, y_i ≤ n; x_i ≠ y_i) — the endpoints of the i-th edge.
These edges form a connected undirected graph without multiple edges.
Output
If it's impossible to destroy all of the edges, print 0.
Otherwise, print the sequence of your actions as follows. First, print k — the number of actions (k ≤ 2m + 2). Then, print the sequence itself, consisting of k integers. The first integer should be the index of the starting vertex. Then, each of the next integers should be either the index of the next vertex in your traversal, or -1 if you use mode shift. You are allowed to use mode shift at most once.
If there are multiple answers, print any of them.
Examples
Input
3 3
1 2
2 3
3 1
Output
4
1 2 3 1
Input
4 3
1 2
2 3
4 2
Output
8
2 -1 1 2 3 2 4 2
Input
5 5
1 2
2 3
3 1
2 4
2 5
Output
9
2 3 1 2 -1 4 2 5 2
Input
5 5
1 2
2 3
3 1
2 4
4 5
Output
8
5 4 2 3 1 -1 2 1
Input
6 5
1 2
2 3
3 4
4 5
3 6
Output
0
Submitted Solution:
```
import sys
from bisect import bisect_left as l
r=range
def s(A,B):
S=set(A);b=len(B);C=[0]*(b+1)
for i in r(b-1,-1,-1):
if B[i] in S:C[i]+=1
C[i]+=C[i+1]
a=C[0];X=0
for i in r(b):
while X<len(A) and A[X]<=B[i]:X+=1
if X>0:a=max(a,l(B,B[i])-l(B,B[i]-X+1)+1+C[i+1])
return a
p=lambda:map(int,sys.stdin.buffer.readline().split())
for t in r(*p()):
p();A=[];X=[];B=[];Y=[]
for v in p():
if v<0:A+=[-v]
else:B+=[v]
for w in p():
if w<0:X+=[-w]
else:Y+=[w]
print(s(A[::-1],X[::-1])+s(B,Y))
``` | instruction | 0 | 66,672 | 13 | 133,344 |
No | output | 1 | 66,672 | 13 | 133,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected graph consisting of n vertices and m edges. Your goal is to destroy all edges of the given graph.
You may choose any vertex as the starting one and begin walking from it along the edges. When you walk along an edge, you destroy it. Obviously, you cannot walk along an edge if it is destroyed.
You can perform the mode shift operation at most once during your walk, and this operation can only be performed when you are at some vertex (you cannot perform it while traversing an edge). After the mode shift, the edges you go through are deleted in the following way: the first edge after the mode shift is not destroyed, the second one is destroyed, the third one is not destroyed, the fourth one is destroyed, and so on. You cannot switch back to the original mode, and you don't have to perform this operation if you don't want to.
Can you destroy all the edges of the given graph?
Input
The first line contains two integers n and m (2 ≤ n ≤ 3000; n - 1 ≤ m ≤ min((n(n-1))/(2), 3000)) — the numbef of vertices and the number of edges in the graph.
Then m lines follow, each containing two integers x_i and y_i (1 ≤ x_i, y_i ≤ n; x_i ≠ y_i) — the endpoints of the i-th edge.
These edges form a connected undirected graph without multiple edges.
Output
If it's impossible to destroy all of the edges, print 0.
Otherwise, print the sequence of your actions as follows. First, print k — the number of actions (k ≤ 2m + 2). Then, print the sequence itself, consisting of k integers. The first integer should be the index of the starting vertex. Then, each of the next integers should be either the index of the next vertex in your traversal, or -1 if you use mode shift. You are allowed to use mode shift at most once.
If there are multiple answers, print any of them.
Examples
Input
3 3
1 2
2 3
3 1
Output
4
1 2 3 1
Input
4 3
1 2
2 3
4 2
Output
8
2 -1 1 2 3 2 4 2
Input
5 5
1 2
2 3
3 1
2 4
2 5
Output
9
2 3 1 2 -1 4 2 5 2
Input
5 5
1 2
2 3
3 1
2 4
4 5
Output
8
5 4 2 3 1 -1 2 1
Input
6 5
1 2
2 3
3 4
4 5
3 6
Output
0
Submitted Solution:
```
def delet():
return None
``` | instruction | 0 | 66,673 | 13 | 133,346 |
No | output | 1 | 66,673 | 13 | 133,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected graph consisting of n vertices and m edges. Your goal is to destroy all edges of the given graph.
You may choose any vertex as the starting one and begin walking from it along the edges. When you walk along an edge, you destroy it. Obviously, you cannot walk along an edge if it is destroyed.
You can perform the mode shift operation at most once during your walk, and this operation can only be performed when you are at some vertex (you cannot perform it while traversing an edge). After the mode shift, the edges you go through are deleted in the following way: the first edge after the mode shift is not destroyed, the second one is destroyed, the third one is not destroyed, the fourth one is destroyed, and so on. You cannot switch back to the original mode, and you don't have to perform this operation if you don't want to.
Can you destroy all the edges of the given graph?
Input
The first line contains two integers n and m (2 ≤ n ≤ 3000; n - 1 ≤ m ≤ min((n(n-1))/(2), 3000)) — the numbef of vertices and the number of edges in the graph.
Then m lines follow, each containing two integers x_i and y_i (1 ≤ x_i, y_i ≤ n; x_i ≠ y_i) — the endpoints of the i-th edge.
These edges form a connected undirected graph without multiple edges.
Output
If it's impossible to destroy all of the edges, print 0.
Otherwise, print the sequence of your actions as follows. First, print k — the number of actions (k ≤ 2m + 2). Then, print the sequence itself, consisting of k integers. The first integer should be the index of the starting vertex. Then, each of the next integers should be either the index of the next vertex in your traversal, or -1 if you use mode shift. You are allowed to use mode shift at most once.
If there are multiple answers, print any of them.
Examples
Input
3 3
1 2
2 3
3 1
Output
4
1 2 3 1
Input
4 3
1 2
2 3
4 2
Output
8
2 -1 1 2 3 2 4 2
Input
5 5
1 2
2 3
3 1
2 4
2 5
Output
9
2 3 1 2 -1 4 2 5 2
Input
5 5
1 2
2 3
3 1
2 4
4 5
Output
8
5 4 2 3 1 -1 2 1
Input
6 5
1 2
2 3
3 4
4 5
3 6
Output
0
Submitted Solution:
```
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]
d = [int(i) for i in input().split()]
print(4)
print(1, 2, 3, 1)
``` | instruction | 0 | 66,674 | 13 | 133,348 |
No | output | 1 | 66,674 | 13 | 133,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected graph consisting of n vertices and m edges. Your goal is to destroy all edges of the given graph.
You may choose any vertex as the starting one and begin walking from it along the edges. When you walk along an edge, you destroy it. Obviously, you cannot walk along an edge if it is destroyed.
You can perform the mode shift operation at most once during your walk, and this operation can only be performed when you are at some vertex (you cannot perform it while traversing an edge). After the mode shift, the edges you go through are deleted in the following way: the first edge after the mode shift is not destroyed, the second one is destroyed, the third one is not destroyed, the fourth one is destroyed, and so on. You cannot switch back to the original mode, and you don't have to perform this operation if you don't want to.
Can you destroy all the edges of the given graph?
Input
The first line contains two integers n and m (2 ≤ n ≤ 3000; n - 1 ≤ m ≤ min((n(n-1))/(2), 3000)) — the numbef of vertices and the number of edges in the graph.
Then m lines follow, each containing two integers x_i and y_i (1 ≤ x_i, y_i ≤ n; x_i ≠ y_i) — the endpoints of the i-th edge.
These edges form a connected undirected graph without multiple edges.
Output
If it's impossible to destroy all of the edges, print 0.
Otherwise, print the sequence of your actions as follows. First, print k — the number of actions (k ≤ 2m + 2). Then, print the sequence itself, consisting of k integers. The first integer should be the index of the starting vertex. Then, each of the next integers should be either the index of the next vertex in your traversal, or -1 if you use mode shift. You are allowed to use mode shift at most once.
If there are multiple answers, print any of them.
Examples
Input
3 3
1 2
2 3
3 1
Output
4
1 2 3 1
Input
4 3
1 2
2 3
4 2
Output
8
2 -1 1 2 3 2 4 2
Input
5 5
1 2
2 3
3 1
2 4
2 5
Output
9
2 3 1 2 -1 4 2 5 2
Input
5 5
1 2
2 3
3 1
2 4
4 5
Output
8
5 4 2 3 1 -1 2 1
Input
6 5
1 2
2 3
3 4
4 5
3 6
Output
0
Submitted Solution:
```
print("ok")
``` | instruction | 0 | 66,675 | 13 | 133,350 |
No | output | 1 | 66,675 | 13 | 133,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0. | instruction | 0 | 66,889 | 13 | 133,778 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
def main():
n = int(input())
colors = input()[::2]
edges = [[[] for _ in range(n)] for _ in (0, 1)]
for _ in range(n - 1):
u, v = map(int, input().split())
u -= 1
v -= 1
e = edges[colors[u] != colors[v]]
e[u].append(v)
e[v].append(u)
dsu, e = [-1] * n, edges[0]
for u, v in enumerate(dsu):
if v == -1:
nxt, c = [u], colors[u]
while nxt:
cur, nxt = nxt, []
for v in cur:
dsu[v] = u
for v in e[v]:
if dsu[v] == -1:
nxt.append(v)
d = {u: [] for u, v in enumerate(dsu) if u == v}
for u, e in enumerate(edges[1]):
for v in e:
d[dsu[u]].append(dsu[v])
def bfs(x):
nxt, visited, t = [x], set(), 0
while nxt:
t += 1
cur, nxt = nxt, []
for x in cur:
visited.add(x)
for y in d[x]:
if y not in visited:
nxt.append(y)
return t, cur[0]
print(bfs(bfs(0)[1])[0] // 2)
if __name__ == '__main__':
main()
``` | output | 1 | 66,889 | 13 | 133,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0. | instruction | 0 | 66,890 | 13 | 133,780 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
from collections import defaultdict, deque
class DSU:
def __init__(self, n):
self.parents = [i for i in range(n)]
self.ranks = [0 for i in range(n)]
def find_parent(self, v):
if self.parents[v] == v:
return v
self.parents[v] = self.find_parent(self.parents[v])
return self.parents[v]
def join_sets(self, u, v):
u = self.find_parent(u)
v = self.find_parent(v)
if u != v:
if self.ranks[u] < self.ranks[v]:
u, v = v, u
self.parents[v] = u
if self.ranks[v] == self.ranks[u]:
self.ranks[u] += 1
n = int(input())
dsu = DSU(n)
colors = list(map(int, input().split(' ')))
vertices = []
for i in range(n-1):
u, v = map(lambda x: int(x)-1, input().split(' '))
if colors[u] == colors[v]:
dsu.join_sets(u, v)
vertices.append((u,v))
graph = defaultdict(list)
for u, v in vertices:
if colors[u] != colors[v]:
u = dsu.find_parent(u)
v = dsu.find_parent(v)
graph[u].append(v)
graph[v].append(u)
def bfs(u):
d = dict()
d[u] = 0
q = deque()
q.append(u)
while q:
u = q.pop()
for v in graph[u]:
if v not in d:
d[v] = d[u] + 1
q.append(v)
return d
if graph:
v = list(graph.keys())[0]
d = bfs(v)
u = v
for i in d:
if d[i] > d[u]:
u = i
d = bfs(u)
w = u
for i in d:
if d[i] > d[w]:
w = i
print((d[w]+1)//2)
else:
print(0)
``` | output | 1 | 66,890 | 13 | 133,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0. | instruction | 0 | 66,891 | 13 | 133,782 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import defaultdict, deque
sys.setrecursionlimit(1000000000)
def buildTree(root):
q = deque()
q.append((root, root))
vis = [0 for _ in range(n + 1)]
vis[root] = 1
while q:
v, fa = q.pop()
for x in preedge[v]:
if vis[x] != 1:
vis[x] = 1
if col[x] == col[fa]:
q.append((x, fa))
else:
edge[fa].append(x)
edge[x].append(fa)
q.append((x, x))
def getDeep(root):
vis = [0 for _ in range(n + 1)]
d = {}
q = deque()
q.append(root)
vis[root] = 1
d[root] = 0
while q:
u = q.pop()
for x in edge[u]:
if vis[x] == 0:
vis[x] = 1
d[x] = d[u] + 1
q.append(x)
return d
n = int(input())
precol = [int(_) for _ in input().split()]
preedge = [[] for _ in range(n + 1)]
for _ in range(n - 1):
x, y = [int(_) for _ in input().split()]
preedge[x].append(y)
preedge[y].append(x)
root = (n + 1) // 2
edge = [[] for _ in range(n + 1)]
col = [0 for _ in range(n + 1)]
for x in range(1, n + 1):
col[x] = precol[x - 1]
buildTree(root)
d = getDeep(root)
u = max(d.keys(),key=(lambda k:d[k]))
print((max(getDeep(u).values()) + 1 ) // 2)
``` | output | 1 | 66,891 | 13 | 133,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0. | instruction | 0 | 66,892 | 13 | 133,784 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
def main():
n = int(input())
colors = input()[::2]
dsu = list(range(n))
edges = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = map(int, input().split())
u -= 1
v -= 1
if colors[u] == colors[v]:
a, b = dsu[u], dsu[v]
while a != dsu[a]:
a = dsu[a]
while b != dsu[b]:
b = dsu[b]
if a < b:
dsu[b] = dsu[v] = a
else:
dsu[a] = dsu[u] = b
else:
edges[u].append(v)
for u, v in enumerate(dsu):
dsu[u] = dsu[v]
d = {u: [] for u, v in enumerate(dsu) if u == v}
for u, e in enumerate(edges):
for v in e:
d[dsu[u]].append(dsu[v])
d[dsu[v]].append(dsu[u])
def bfs(x):
nxt, visited, t = [x], set(), 0
while nxt:
t += 1
cur, nxt = nxt, []
for x in cur:
visited.add(x)
for y in d[x]:
if y not in visited:
nxt.append(y)
return t, cur[0]
print(bfs(bfs(0)[1])[0] // 2)
if __name__ == '__main__':
main()
``` | output | 1 | 66,892 | 13 | 133,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0. | instruction | 0 | 66,893 | 13 | 133,786 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
def main():
n = int(input())
colors = [c == '1' for c in input()[::2]]
dsu = list(range(n))
edges = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = map(int, input().split())
u -= 1
v -= 1
if colors[u] == colors[v]:
a, b = dsu[u], dsu[v]
while a != dsu[a]:
a = dsu[a]
while b != dsu[b]:
b = dsu[b]
if a < b:
dsu[b] = u
while v != a:
u = dsu[v]
dsu[v] = a
v = u
else:
dsu[a] = v
while u != b:
v = dsu[u]
dsu[u] = b
u = v
else:
edges[u].append(v)
edges[v].append(u)
for u, v in enumerate(dsu):
dsu[u] = dsu[v]
if not any(dsu):
print(0)
return
d = {u: set() for u, v in enumerate(dsu) if u == v}
for u, e in enumerate(edges):
u = dsu[u]
for v in e:
v = dsu[v]
d[u].add(v)
d[v].add(v)
def bfs(x):
nxt, visited, t = [x], set(), 0
while nxt:
t += 1
cur, nxt = nxt, []
for u in cur:
visited.add(u)
for v in d[u]:
if v not in visited:
nxt.append(v)
return t, cur[0]
print(bfs(bfs(0)[1])[0] // 2)
if __name__ == '__main__':
main()
``` | output | 1 | 66,893 | 13 | 133,787 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0. | instruction | 0 | 66,894 | 13 | 133,788 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
def main():
from collections import defaultdict
n, colors = int(input()), input()[::2]
dsu, edges, d = list(range(n)), [], defaultdict(list)
for _ in range(n - 1):
u, v = map(int, input().split())
u -= 1
v -= 1
if colors[u] == colors[v]:
a, b = dsu[u], dsu[v]
while a != dsu[a]:
a = dsu[a]
while b != dsu[b]:
b = dsu[b]
if a < b:
dsu[b] = dsu[v] = a
else:
dsu[a] = dsu[u] = b
else:
edges.append(u)
edges.append(v)
for u, v in enumerate(dsu):
dsu[u] = dsu[v]
while edges:
u, v = dsu[edges.pop()], dsu[edges.pop()]
d[u].append(v)
d[v].append(u)
def bfs(x):
nxt, avail, t = [x], [True] * n, 0
while nxt:
t += 1
cur, nxt = nxt, []
for y in cur:
avail[y] = False
for y in d[y]:
if avail[y]:
nxt.append(y)
return t if x else cur[0]
print(bfs(bfs(0)) // 2)
if __name__ == '__main__':
main()
``` | output | 1 | 66,894 | 13 | 133,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0. | instruction | 0 | 66,895 | 13 | 133,790 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
f = lambda: map(int, input().split())
s, n = 0, int(input())
g = [set() for i in range(n + 1)]
c = [0] + list(f())
d = [0] * (n + 1)
for j in range(n - 1):
a, b = f()
g[a].add(b)
g[b].add(a)
p = [q for q, t in enumerate(g) if len(t) == 1]
while p:
a = p.pop()
if not g[a]: break
b = g[a].pop()
g[b].remove(a)
if c[a] - c[b]: d[a] += 1
s = max(s, d[b] + d[a])
d[b] = max(d[b], d[a])
if len(g[b]) == 1: p.append(b)
print(s + 1 >> 1)
``` | output | 1 | 66,895 | 13 | 133,791 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0. | instruction | 0 | 66,896 | 13 | 133,792 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import defaultdict, deque
# sys.setrecursionlimit(1000000000)
def buildTree(root):
q = deque()
q.append((root, root))
vis = [0 for _ in range(n + 1)]
vis[root] = 1
while q:
v, fa = q.pop()
for x in preedge[v]:
if vis[x] != 1:
vis[x] = 1
if col[x] == col[fa]:
q.append((x, fa))
else:
edge[fa].append(x)
edge[x].append(fa)
q.append((x, x))
def getDeep(root):
vis = [0 for _ in range(n + 1)]
d = {}
q = deque()
q.append(root)
vis[root] = 1
d[root] = 0
while q:
u = q.pop()
for x in edge[u]:
if vis[x] == 0:
vis[x] = 1
d[x] = d[u] + 1
q.append(x)
return d
n = int(input())
precol = [int(_) for _ in input().split()]
preedge = [[] for _ in range(n + 1)]
for _ in range(n - 1):
x, y = [int(_) for _ in input().split()]
preedge[x].append(y)
preedge[y].append(x)
root = (n + 1) // 2
edge = [[] for _ in range(n + 1)]
col = [0 for _ in range(n + 1)]
for x in range(1, n + 1):
col[x] = precol[x - 1]
buildTree(root)
d = getDeep(root)
u = max(d.keys(),key=(lambda k:d[k]))
print((max(getDeep(u).values()) + 1 ) // 2)
``` | output | 1 | 66,896 | 13 | 133,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0.
Submitted Solution:
```
n = int(input())
*col, = map(int, input().split())
if sum(col)*2 > n:
col = [1-col[i] for i in range(n)]
if sum(col)%n == 0:
print(0)
exit()
g = [[] for i in range(n)]
for i in range(n-1):
a, b = map(int, input().split())
g[a-1].append(b-1)
g[b-1].append(a-1)
cnt = 0
for i in range(n):
if col[i] == 1 and len(g[i]) > 1:
cnt += 1
for j in g[i]:
g[j].remove(i)
g[i] = []
print(cnt+1)
``` | instruction | 0 | 66,897 | 13 | 133,794 |
No | output | 1 | 66,897 | 13 | 133,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0.
Submitted Solution:
```
def main():
n = int(input())
colors = [c == '1' for c in input()[::2]]
dsu = list(range(n))
edges = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = map(int, input().split())
u -= 1
v -= 1
edges[u].append(v)
edges[v].append(u)
if colors[u] == colors[v]:
a, b = dsu[u], dsu[v]
while a != dsu[a]:
a = dsu[a]
while b != dsu[b]:
b = dsu[b]
if a < b:
dsu[v] = u
dsu[b] = a
else:
dsu[u], v = v, u
dsu[a] = a = b
while v != a:
v, dsu[v] = dsu[v], a
if not any(dsu):
print(0)
return
for u, v in enumerate(dsu):
dsu[u] = [] if u == v else dsu[v]
for u, c, e in zip(range(n), colors, edges):
for v in e:
b = dsu[v]
if colors[v] != c:
dsu[u].append(v)
dsu[v].append(u)
def bfs(x):
nxt, visited, t = [x], set(), 0
while nxt:
t += 1
cur, nxt = nxt, []
for u in cur:
visited.add(u)
for v in dsu[u]:
if v not in visited:
nxt.append(v)
return t, cur[0]
print((bfs(bfs(0)[1])[0] + 1) // 2)
if __name__ == '__main__':
main()
``` | instruction | 0 | 66,898 | 13 | 133,796 |
No | output | 1 | 66,898 | 13 | 133,797 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0.
Submitted Solution:
```
class Node():
def __init__(self, c):
self.c = c
self.v = False
self.ch = []
def visit(node):
node.v = True
for child in node.ch:
if not child.v and child.c == node.c:
visit(child)
if __name__ == '__main__':
n = int(input())
nodes = [Node(int(c)) for c in input().split()]
for _ in range(n - 1):
u, v = [int(_) - 1 for _ in input().split()]
nodes[u].ch.append(nodes[v])
nodes[v].ch.append(nodes[u])
count = [0] * 2
for node in nodes:
if not node.v:
visit(node)
count[node.c] += 1
print(min(count))
``` | instruction | 0 | 66,899 | 13 | 133,798 |
No | output | 1 | 66,899 | 13 | 133,799 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree
<image>
and apply operation paint(3) to get the following:
<image>
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Output
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
Examples
Input
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
Output
2
Input
4
0 0 0 0
1 2
2 3
3 4
Output
0
Note
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0.
Submitted Solution:
```
class DSU:
def __init__(self, n):
self.parents = [i for i in range(n)]
self.ranks = [0 for i in range(n)]
def find_parent(self, v):
if self.parents[v] == v:
return v
self.parents[v] = self.find_parent(self.parents[v])
return self.parents[v]
def join_sets(self, u, v):
u = self.find_parent(u)
v = self.find_parent(v)
if u != v:
if self.ranks[u] < self.ranks[v]:
u, v = v, u
self.parents[v] = u
if self.ranks[v] == self.ranks[u]:
self.ranks[u] += 1
n = int(input())
dsu = DSU(n)
colors = list(map(int, input().split(' ')))
for i in range(n-1):
u, v = map(lambda x: int(x)-1, input().split(' '))
if colors[u] == colors[v]:
dsu.join_sets(u, v)
black = 0
white = 0
for i in range(n):
if dsu.parents[i] == i:
if colors[i] == 0:
black += 1
else:
white += 1
print(min(white, black))
``` | instruction | 0 | 66,900 | 13 | 133,800 |
No | output | 1 | 66,900 | 13 | 133,801 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times. | instruction | 0 | 66,953 | 13 | 133,906 |
Tags: dfs and similar, dp, graphs
Correct Solution:
```
import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int, input().split())
s = list(input())
graph = [[] for _ in range(n)]
degree = [0 for _ in range(n)]
dp = [[0 for _ in range(26)] for _ in range(n)]
for i in range(m):
a, b = map(lambda x: int(x) - 1, input().split())
graph[a].append(b)
degree[b] += 1
queue = deque()
for i in range(n):
if degree[i] == 0:
queue.append(i)
count = 0
while count < n and queue:
count += 1
node = queue.popleft()
dp[node][ord(s[node]) - 97] += 1
for i in graph[node]:
for j in range(26):
dp[i][j] = max(dp[i][j], dp[node][j])
degree[i] -= 1
if degree[i] == 0:
queue.append(i)
if count != n:
print(-1)
else:
result = 0
for i in dp:
result = max(result, max(i))
print(result)
``` | output | 1 | 66,953 | 13 | 133,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times. | instruction | 0 | 66,954 | 13 | 133,908 |
Tags: dfs and similar, dp, graphs
Correct Solution:
```
from os import path
import sys,time
mod = int(1e9 + 7)
# import re
from math import ceil, floor,gcd,log,log2 ,factorial,sqrt
from collections import defaultdict ,Counter , OrderedDict , deque
from itertools import combinations ,accumulate
# from string import ascii_lowercase ,ascii_uppercase
from bisect import *
from functools import reduce
from operator import mul
star = lambda x: print(' '.join(map(str, x)))
grid = lambda r :[lint() for i in range(r)]
stpr = lambda x : sys.stdout.write(f'{x}' + '\n')
INF = float('inf')
if (path.exists('input.txt')):
sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
import sys
from sys import stdin, stdout
from collections import *
from math import gcd, floor, ceil
from copy import deepcopy
def st(): return list(stdin.readline().strip())
def inp():
return int(stdin.readline())
def inlt():
return list(map(int, stdin.readline().split()))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return map(int, stdin.readline().split())
def pr(n): return stdout.write(str(n)+"\n")
def check(a):
for i in a:
if i:
return True
return False
def ctd(x):
return ord(x)-ord('a')
def solve():
n, m = invr()
s = input()
d = {}
for i in range(n):
d[i+1] = s[i]
gp = defaultdict(list)
ind = [0 for _ in range(n+1)]
for _ in range(m):
x, y = invr()
gp[x].append(y)
ind[y]+=1
q = []
dp = [[0 for _ in range(27)]for _ in range(n + 1)]
for i in range(1, n+1):
if ind[i]==0:
q.append(i)
dp[i][ctd(d[i])] = 1
for i in q:
for j in gp[i]:
for k in range(26):
if ctd(d[j])==k:
dp[j][k] = max(dp[i][k]+1, dp[j][k])
else:
dp[j][k] = max(dp[i][k], dp[j][k])
ind[j]-=1
if ind[j]==0: q.append(j)
if check(ind):
print(-1)
else:
res = 0
for i in dp:
for j in i:
res = max(res, j)
print(res)
t = 1
#t = inp()
for _ in range(t):
solve()
``` | output | 1 | 66,954 | 13 | 133,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times. | instruction | 0 | 66,955 | 13 | 133,910 |
Tags: dfs and similar, dp, graphs
Correct Solution:
```
from collections import defaultdict,deque
import sys
input=sys.stdin.readline
n,m=map(int,input().split())
l=list(input())
beauty=[0 for i in range(n)]
graph=defaultdict(list)
for i in range(m):
a,b=map(int,input().split())
a-=1
b-=1
graph[a].append(b)
beauty[b]+=1
q=deque()
for i in range(n):
if beauty[i]==0:
q.append(i)
count=0
ans=0
# print(degree)
dp=[]
for i in range(n):
dp.append([0]*(26))
while count<n and q:
num=q.popleft()
count+=1
# print(ord(l[x])-97)
dp[num][ord(l[num])-97]+=1
for i in graph[num]:
for j in range(26):
dp[i][j]=max(dp[i][j],dp[num][j])
beauty[i]-=1
if beauty[i]==0:
q.append(i)
if count!=n:
print(-1)
else:
ans=0
for i in range(n):
ans=max(ans,max(dp[i]))
print(ans)
``` | output | 1 | 66,955 | 13 | 133,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times. | instruction | 0 | 66,956 | 13 | 133,912 |
Tags: dfs and similar, dp, graphs
Correct Solution:
```
maxi = 300005
n, m = map(int, input().split())
s = input()
s = " "+s
ed = []
dp = []
for i in range(n+1):
ed.append([])
dp.append([0]*26)
q = [0]*maxi
front = 0
rear = 0
deg = [0]*(n+1)
for i in range(m):
x, y = map(int, input().split())
ed[x].append(y)
deg[y] += 1
def topSort():
rear = front = 0
cnt = 0
for i in range(1, n+1):
if(deg[i] == 0):
q[rear] = i
rear += 1
dp[i][ord(s[i])-97] = 1
while(front != rear):
u = q[front]
front += 1
cnt += 1
for i in range(len(ed[u])):
v = ed[u][i]
for j in range(26):
x = dp[u][j]
if(j == ord(s[v])-ord('a')):
x += 1
dp[v][j] = max(x, dp[v][j])
deg[v] -= 1
if(deg[v] == 0):
q[rear] = v
rear += 1
ans = -1
for i in range(1, n+1):
for j in range(26):
ans = max(ans, dp[i][j])
return cnt == n, ans
ans = topSort()
if(ans[0]):
print(ans[1])
else:
print(-1)
``` | output | 1 | 66,956 | 13 | 133,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times. | instruction | 0 | 66,957 | 13 | 133,914 |
Tags: dfs and similar, dp, graphs
Correct Solution:
```
from sys import stdin
input=lambda : stdin.readline().strip()
from collections import deque
nodes,edges=map(int,input().split())
input_string=input()
x=[]
y=[]
for i in range(edges):
a,b=map(int,input().split())
x.append(a)
y.append(b)
def beauty(nodes,edges,input_string,x,y):
string=list(input_string)
degree=[0 for i in range(nodes)]
graph={i:[] for i in range(nodes)}
for i in range(edges):
a,b=x[i],y[i]
a-=1
b-=1
graph[a].append(b)
degree[b]+=1
q=deque()
for i in range(nodes):
if degree[i]==0:
q.append(i)
count=0
ans=0
# print(degree)
dp_table=[[0 for i in range(26)] for i in range(nodes)]
while count<nodes and q:
x=q.popleft()
count+=1
# print(ord(l[x])-97)
dp_table[x][ord(string[x])-97]+=1
for i in graph[x]:
for j in range(26):
dp_table[i][j]=max(dp_table[i][j],dp_table[x][j])
degree[i]-=1
if degree[i]==0:
q.append(i)
# print(degree)
if count!=nodes:
print(-1)
else:
ans=0
for i in range(nodes):
ans=max(ans,max(dp_table[i]))
print(ans)
beauty(nodes,edges,input_string,x,y)
``` | output | 1 | 66,957 | 13 | 133,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times. | instruction | 0 | 66,958 | 13 | 133,916 |
Tags: dfs and similar, dp, graphs
Correct Solution:
```
from collections import defaultdict,deque
import sys
input=sys.stdin.readline
n,m=map(int,input().split())
arr=list(input())
q=deque()
res=0
dg=[0 for i in range(n)]
cnt=0
gp=defaultdict(list)
for i in range(m):
l,k=map(int,input().split())
l=l-1
k=k-1
gp[l].append(k)
dg[k]=dg[k]+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
lmk=0
lmk=lmk+1
mt=[[0 for i in range(26)] for i in range(n)]
for i in range(n):
if dg[i]==0:
q.append(i)
while(cnt <n and q):
t=q.popleft()
cnt=cnt+1
mt[t][ord(arr[t])-97]+=1
for i in gp[t]:
for j in range(26):
mt[i][j]=max(mt[i][j],mt[t][j])
dg[i]-=1
if dg[i]==0:
q.append(i)
if(cnt!=n):
print(-1)
else:
for i in range(0,n):
res=max(res,max(mt[i]))
print(res)
``` | output | 1 | 66,958 | 13 | 133,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times. | instruction | 0 | 66,959 | 13 | 133,918 |
Tags: dfs and similar, dp, graphs
Correct Solution:
```
from collections import defaultdict
import sys
from sys import stdin
def check(a):
for i in a:
if i:
return True
return False
def change(x):
return ord(x)-ord('a')
def solve():
n, m = map(int, stdin.readline().split())
s = input()
d = {}
for i in range(n):
d[i+1] = s[i]
g = defaultdict(list)#[[] for _ in range(n+1)]
ind = [0 for _ in range(n+1)]
for _ in range(m):
x, y = map(int, stdin.readline().split())
g[x].append(y)
ind[y]+=1
q = []
dp = [[0 for _ in range(27)]for _ in range(n + 1)]
for i in range(1, n+1):
if ind[i]==0:
q.append(i)
dp[i][change(d[i])] = 1
for i in q:
for j in g[i]:
for k in range(26):
if change(d[j])==k:
dp[j][k] = max(dp[i][k]+1, dp[j][k])
else:
dp[j][k] = max(dp[i][k], dp[j][k])
ind[j]-=1
if ind[j]==0: q.append(j)
if check(ind):
print(-1)
else:
ans = 0
for i in dp:
for j in i:
ans = max(ans, j)
print(ans)
t = 1
#t = inp()
for _ in range(t):
solve()
``` | output | 1 | 66,959 | 13 | 133,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times. | instruction | 0 | 66,960 | 13 | 133,920 |
Tags: dfs and similar, dp, graphs
Correct Solution:
```
import sys
from collections import defaultdict, deque
input = sys.stdin.readline
def beauty(n,m,z,x,y):
l=z
degree=[0 for i in range(n)]
graph=defaultdict(list)
for i in range(m):
a,b=x[i],y[i]
a-=1
b-=1
graph[a].append(b)
degree[b]+=1
q=deque()
for i in range(n):
if degree[i]==0:
q.append(i)
count=0
ans=0
# print(degree)
dp=[[0 for i in range(26)] for i in range(n)]
while count<n and q:
x=q.popleft()
count+=1
# print(ord(l[x])-97)
dp[x][ord(l[x])-97]+=1
for i in graph[x]:
for j in range(26):
dp[i][j]=max(dp[i][j],dp[x][j])
degree[i]-=1
if degree[i]==0:
q.append(i)
# print(degree)
if count!=n:
return -1
else:
ans=0
for i in range(n):
ans=max(ans,max(dp[i]))
return ans
n,m = map(int,input().split())
z = list(input())
x = [None]*m
y = [None]*m
for i in range(m):
x[i],y[i] = map(int,input().split())
print(beauty(n,m,z,x,y))
``` | output | 1 | 66,960 | 13 | 133,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
Submitted Solution:
```
n, m = map(int, input().split())
s = " "+input()
ed,dp = [], []
maxi = 300005
for _ in range(n+1):
ed.append([])
dp.append([0]*26)
q,deg = [0]*maxi,[0]*(n+1)
for i in range(m):
x, y = map(int, input().split())
ed[x].append(y)
deg[y] += 1
fr,re = 0,0
def funct():
re = fr = 0
for i in range(1, n+1):
if(deg[i] == 0):
q[re] = i
re += 1
dp[i][ord(s[i])-97] = 1
count = 0
while(fr != re):
u = q[fr]
fr += 1
count += 1
for i in range(len(ed[u])):
v = ed[u][i]
for j in range(26):
x = dp[u][j]
if(j == ord(s[v])-ord('a')):
x += 1
dp[v][j] = max(x, dp[v][j])
deg[v] -= 1
if(deg[v] == 0):
q[re] = v
re += 1
ans = -9999999
for i in range(1, n+1):
for j in range(26):
ans = max(ans, dp[i][j])
return count == n, ans
ans1 = funct()
if(ans1[0]):
print(ans1[1])
else:
print(-1)
``` | instruction | 0 | 66,961 | 13 | 133,922 |
Yes | output | 1 | 66,961 | 13 | 133,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
Submitted Solution:
```
from collections import defaultdict, deque, Counter
import sys
import bisect
import math
input = sys.stdin.readline
mod = 1000000007
n ,m = input().split()
n = int(n)
m = int(m)
l = list(input())
degree = [0 for i in range(n)]
graph = defaultdict(list)
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
graph[a].append(b)
degree[b] += 1
q = deque()
for i in range(n):
if degree[i] == 0:
q.append(i)
count = 0
ans = 0
# print(degree)
dp = [[0 for i in range(26)] for i in range(n)]
while count < n and q:
x = q.popleft()
count += 1
dp[x][ord(l[x]) - 97] += 1
for i in graph[x]:
for j in range(26):
dp[i][j] = max(dp[i][j], dp[x][j])
degree[i] -= 1
if degree[i] == 0:
q.append(i)
if count != n:
print(-1)
else:
ans = 0
for i in range(n):
ans = max(ans, max(dp[i]))
print(ans)
``` | instruction | 0 | 66,962 | 13 | 133,924 |
Yes | output | 1 | 66,962 | 13 | 133,925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
Submitted Solution:
```
from collections import defaultdict,deque
import sys
input=sys.stdin.readline
n,m=map(int,input().split())
arr=list(input())
q=deque()
res=0
dg=[0 for i in range(n)]
cnt=0
gp=defaultdict(list)
for i in range(m):
l,k=map(int,input().split())
l=l-1
k=k-1
gp[l].append(k)
dg[k]=dg[k]+1
mt=[[0 for i in range(26)] for i in range(n)]
for i in range(n):
if dg[i]==0:
q.append(i)
while(cnt <n and q):
t=q.popleft()
cnt=cnt+1
mt[t][ord(arr[t])-97]+=1
for i in gp[t]:
for j in range(26):
mt[i][j]=max(mt[i][j],mt[t][j])
dg[i]-=1
if dg[i]==0:
q.append(i)
if(cnt!=n):
print(-1)
else:
for i in range(0,n):
res=max(res,max(mt[i]))
print(res)
``` | instruction | 0 | 66,963 | 13 | 133,926 |
Yes | output | 1 | 66,963 | 13 | 133,927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
Submitted Solution:
```
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")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
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 comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def ctd(chr): return ord(chr)-ord("a")
def main():
n, m = RL()
s = input()
gp = [[] for _ in range(n+1)]
ind = [0]*(n+1)
dic = {i+1: v for i, v in enumerate(s)}
for _ in range(m):
f, t = RL()
gp[f].append(t)
ind[t]+=1
dp = [[0] * 27 for _ in range(n + 1)]
q = deque()
for i in range(1, n+1):
if ind[i]==0:
q.append(i)
dp[i][ctd(dic[i])] = 1
res = 0
while q:
nd = q.popleft()
for nex in gp[nd]:
nc = ctd(dic[nex])
for i in range(27):
dp[nex][i] = max(dp[nex][i], dp[nd][i]+(1 if nc==i else 0))
res = max(dp[nex][i], res)
ind[nex]-=1
if ind[nex]==0: q.append(nex)
if any(ind[1:]):
print(-1)
else:
print(res)
if __name__ == "__main__":
main()
``` | instruction | 0 | 66,964 | 13 | 133,928 |
Yes | output | 1 | 66,964 | 13 | 133,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
Submitted Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
#INF = float('inf')
mod = 998244353
def toposort(graph):
res, found = [], [0] * len(graph)
stack = list(range(len(graph)))
while stack:
node = stack.pop()
if node < 0:
res.append(~node)
elif not found[node]:
found[node] = 1
stack.append(~node)
stack += graph[node]
# cycle check
for node in res:
if any(found[nei] for nei in graph[node]):
return None
found[node] = 0
return res[::-1]
def dfs(graph, start=0):
n = len(graph)
dp = [dd(int) for i in range(n)]
visited, finished = [False] * n, [False] * n
stack = [start]
ans = 0
while stack:
start = stack[-1]
# push unvisited children into stack
if not visited[start]:
visited[start] = True
for child in graph[start]:
if not visited[child]:
stack.append(child)
else:
stack.pop()
# update with finished children
for child in graph[start]:
if finished[child]:
for k in dp[child]:
dp[start][k] = max(dp[start][k],dp[child][k])
dp[start][s[start]] += 1
ans = max(dp[start].values())
finished[start] = True
return ans
n,m = mdata()
s = data()
graph = [[] for i in range(n)]
for i in range(m):
u,v = mdata()
graph[u-1].append(v-1)
if toposort(graph) == None:
print(-1)
else:
print(dfs(graph))
``` | instruction | 0 | 66,965 | 13 | 133,930 |
No | output | 1 | 66,965 | 13 | 133,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
Submitted Solution:
```
import sys,os,io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_left , bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')
#for deep recursion__________________________________________-
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 ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,p - 2, p)) % p
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
c = dict(Counter(l))
return list(set(l))
# return c
def power(x, y, p) :
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
#____________________GetPrimeFactors in log(n)________________________________________
def sieveForSmallestPrimeFactor():
MAXN = 100001
spf = [0 for i in range(MAXN)]
spf[1] = 1
for i in range(2, MAXN):
spf[i] = i
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, math.ceil(math.sqrt(MAXN))):
if (spf[i] == i):
for j in range(i * i, MAXN, i):
if (spf[j] == j):
spf[j] = i
return spf
def getPrimeFactorizationLOGN(x):
spf = sieveForSmallestPrimeFactor()
ret = list()
while (x != 1):
ret.append(spf[x])
x = x // spf[x]
return ret
#____________________________________________________________
def SieveOfEratosthenes(n):
#time complexity = nlog(log(n))
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
def si():
return input()
def divideCeil(n,x):
if (n%x==0):
return n//x
return n//x+1
def ii():
return int(input())
def li():
return list(map(int,input().split()))
#__________________________TEMPLATE__________________OVER_______________________________________________________
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
else:
input = sys.stdin.readline
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def solve():
n,m = li()
s = si().strip()
adj = [[] for i in range(n)]
ind = [0]*n
for i in range(m):
x,y = li()
x-=1
y-=1
adj[x].append(y)
ind[y]+=1
ancesstor = set()
vis = [False]*n
dp = [[0 for i in range(26)] for j in range(n)]
def dfs(node):
# print(node)
ancesstor.add(node)
for kid in adj[node]:
if kid in ancesstor:
exit(0)
return
if vis[kid]==False:
vis[kid] = True
dfs(kid)
for j in range(26):
dp[node][j] = dp[kid][j]
dp[node][ord(s[node])-97]+=1
# print(dp[node][ord(s[node])-97])
ancesstor.remove(node)
for i in range(n):
if vis[i]==False:
vis[i] = True
dfs(i)
ans = 0
# print(dp)
for i in dp:
ans =max(ans,max(i))
print(ans)
t = 1
# t = ii()
for _ in range(t):
solve()
``` | instruction | 0 | 66,966 | 13 | 133,932 |
No | output | 1 | 66,966 | 13 | 133,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
Submitted Solution:
```
def solve(cor,string,n):
graph={}
x=len(string)
visited1=[False]*x
dp1=[1]*x
visited=visited1
dp=dp1
maxi=-1
indeg={}
for ls in cor:
start=ls[0]-1
end=ls[1]-1
if(start in graph):
graph[start].append(end)
else:
graph[start]=[end]
if(end in indeg):
indeg[end] += 1
else:
indeg[end]=1
for k in graph:
if(not k in indeg):
indeg[k]=0
#print(graph)
#print(indeg)
qs=cycle(graph,indeg,n)
#print("qs-->",qs)
if(qs[0]==-1):
return -1
return find(graph,qs,string,n)
# for key in graph:
# maxi=max(maxi,find(graph,key,string))
# print(visited)
# print(maxi)
# return maxi
def cycle(graph,indeg,n):
q=[]
ans=[]
for t in indeg:
if(indeg[t]==0):
q.append(t)
if(len(q)==0):
return [-1]
val=0
while(q):
node=q.pop()
val += 1
if(not node in graph):
continue
ans.append(node)
for v in graph[node]:
indeg[v] -= 1
if(indeg[v]==0):
q.append(v)
#print("val-->",val)
if(val!=n):
return [-1]
return ans
#{1: [2, 10], 2: [4, 6, 10, 8], 3: [5, 9, 7], 4: [5, 6], 6: [8, 5], 10: [9]}
#{0: [1, 9], 1: [3, 5, 9, 7], 2: [4, 8, 6], 3: [4, 5], 5: [7, 4], 9: [8]}
def find(graph,q,string,n):
dp=[[1]*26 for _ in range(n+1)]
for node in q:
index=abs(ord(string[node])-ord('a'))
#print("node,index",(node,index))
dp[node][index] += 1
for v in graph[node]:
for j in range(26):
dp[v][j]=max(dp[v][j],dp[node][j])
maxi=-1
for ls in dp:
for p in ls:
maxi=max(maxi,p)
return maxi
ls=list(map(int,input().strip().split(' ')))
string=input()
pot=[]
for i in range(0,ls[1]):
ls1=list(map(int,input().strip().split(' ')))
pot.append(ls1)
print(solve(pot,string,ls[0]))
pot.clear()
``` | instruction | 0 | 66,967 | 13 | 133,934 |
No | output | 1 | 66,967 | 13 | 133,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
Output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
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")
###############################################
import threading
sys.setrecursionlimit(300000)
threading.stack_size(10**8)
from collections import defaultdict
def dfs(x):
global v,adj,s,l1,l2,l
if l[x]!=0:
return l[x],l1[x].copy()
v[x]=1
l2[x]=1
for i in adj[x]:
if not v[i]:
a,d=dfs(i)
if a==-1:
return -1,[]
else:
l[x]=max(l[x],a)
for i in range(26):
l1[x][i]=max(l1[x][i],d[i])
else:
if l2[i]==1:
return -1,[]
l1[x][ord(s[x-1])-97]+=1
for i in l1[x]:
l[x]=max(l[x],i)
l2[x]=0
return l[x],l1[x].copy()
def main():
global v,adj,s,l2,l1,l
n,m=map(int,input().split())
s=input()
adj=[[]for i in range(n+1)]
v=[0]*(n+1)
l=[0]*(n+1)
l2=[0]*(n+1)
l1=[[0]*26 for i in range(n+1)]
ans=True
ans1=0
for i in range(m):
x,y=map(int,input().split())
adj[x].append(y)
for i in range(1,n+1):
if not v[i]:
u,v=dfs(i)
if u==-1:
ans=False
break
ans1=max(ans1,u)
if ans==True:
print(ans1)
else:
print(-1)
t=threading.Thread(target=main)
t.start()
t.join()
``` | instruction | 0 | 66,968 | 13 | 133,936 |
No | output | 1 | 66,968 | 13 | 133,937 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are integers N and K, and a prime number P. Find the number, modulo P, of directed graphs G with N vertices that satisfy below. Here, the vertices are distinguishable from each other.
* G is a tournament, that is, G contains no duplicated edges or self-loops, and exactly one of the edges u\to v and v\to u exists for any two vertices u and v.
* The in-degree of every vertex in G is at most K.
* For any four distinct vertices a, b, c, and d in G, it is not the case that all of the six edges a\to b, b\to c, c\to a, a\to d, b\to d, and c\to d exist simultaneously.
Constraints
* 4 \leq N \leq 200
* \frac{N-1}{2} \leq K \leq N-1
* 10^8<P<10^9
* N and K are integers.
* P is a prime number.
Input
Input is given from Standard Input in the following format:
N K P
Output
Print the number of directed graphs that satisfy the conditions, modulo P.
Examples
Input
4 3 998244353
Output
56
Input
7 3 998244353
Output
720
Input
50 37 998244353
Output
495799508
Submitted Solution:
```
``` | instruction | 0 | 67,004 | 13 | 134,008 |
No | output | 1 | 67,004 | 13 | 134,009 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc.
A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i.
He would like to make one as follows:
* Specify two non-negative integers A and B.
* Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1.
* Repeat the following operation until he has one connected tree:
* Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y.
* Properly number the vertices in the tree.
Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized.
Solve this problem for him.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For the lexicographically smallest (A,B), print A and B with a space in between.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
6 7
Output
3 2
Input
8
1 2
2 3
3 4
4 5
5 6
5 7
5 8
Output
2 5
Input
10
1 2
2 3
3 4
2 5
6 5
6 7
7 8
5 9
10 5
Output
3 4 | instruction | 0 | 67,085 | 13 | 134,170 |
"Correct Solution:
```
from collections import deque
import sys
input=sys.stdin.readline
N=int(input())
edge=[[] for i in range(N)]
for i in range(N-1):
a,b=map(int,input().split())
edge[a-1].append(b-1)
edge[b-1].append(a-1)
parent=[-1]*N
parent[0]=0
que=deque([0])
ans=[0]
while que:
v=que.popleft()
for nv in edge[v]:
if parent[nv]==-1:
parent[nv]=v
que.append(nv)
ans.append(nv)
ans=ans[::-1]
def cond(n):
dp=[-1]*N
for v in ans:
if v!=0:
temp=[]
if len(edge[v])==1:
dp[v]=1
else:
for nv in edge[v]:
if nv!=parent[v]:
r=dp[nv]
if r==-1:
return False
temp.append(r)
if len(temp)%2==0:
temp.append(0)
temp.sort()
start=0
end=len(temp)-1
while end-start>1:
test=(end+start)//2
check=True
s=0;t=len(temp)-1
while t>s:
if s==test:
s+=1
elif t==test:
t-=1
else:
if temp[s]+temp[t]>n:
check=False
s+=1
t-=1
if check:
end=test
else:
start=test
check=True
s=0;t=len(temp)-1
while t>s:
if s==start:
s+=1
elif t==start:
t-=1
else:
if temp[s]+temp[t]>n:
check=False
s+=1
t-=1
if check:
dp[v]=temp[start]+1
else:
check=True
s=0;t=len(temp)-1
while t>s:
if s==end:
s+=1
elif t==end:
t-=1
else:
if temp[s]+temp[t]>n:
check=False
s+=1
t-=1
if check:
dp[v]=temp[end]+1
else:
return False
else:
temp=[]
for nv in edge[v]:
temp.append(dp[nv])
if len(temp)%2==1:
temp.append(0)
temp.sort()
k=len(temp)//2
for i in range(k):
test=temp[i]+temp[-i-1]
if test>n:
return False
return True
A=(len(edge[0])+1)//2
for i in range(1,N):
A+=(len(edge[i])-1)//2
start=0
end=N-1
while end-start>1:
test=(end+start)//2
if cond(test):
end=test
else:
start=test
print(A,end)
``` | output | 1 | 67,085 | 13 | 134,171 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc.
A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i.
He would like to make one as follows:
* Specify two non-negative integers A and B.
* Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1.
* Repeat the following operation until he has one connected tree:
* Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y.
* Properly number the vertices in the tree.
Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized.
Solve this problem for him.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For the lexicographically smallest (A,B), print A and B with a space in between.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
6 7
Output
3 2
Input
8
1 2
2 3
3 4
4 5
5 6
5 7
5 8
Output
2 5
Input
10
1 2
2 3
3 4
2 5
6 5
6 7
7 8
5 9
10 5
Output
3 4 | instruction | 0 | 67,086 | 13 | 134,172 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from bisect import bisect_left, bisect_right
N = int(readline())
m = map(int,read().split())
AB = zip(m,m)
graph = [[] for _ in range(N+1)]
for a,b in AB:
graph[a].append(b)
graph[b].append(a)
root = 1
parent = [0] * (N+1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
def make_pairs(S,x):
# a + b <= x となるペアをなるべくたくさん作る
# nペア(なるべくたくさん)作ったあと、1つ短い長さが残る
seg = 0
while S and S[-1] == x:
S.pop()
seg += 1
i = bisect_right(S,x//2)
lower = S[:i][::-1]; upper = S[i:]
cand = []
rest = []
for b in upper[::-1]:
while lower and lower[-1] + b <= x:
cand.append(lower.pop())
if cand:
cand.pop()
seg += 1
else:
rest.append(b)
cand += lower[::-1]
L = len(cand)
q,r = divmod(L,2)
if r:
return seg + len(rest) + q, cand[0]
else:
seg += q
if rest:
return seg + len(rest) - 1, rest[-1]
else:
# 全部ペアになった
return seg, 0
def solve(x):
# 長さ x までの線分を許容した場合に、必要となる本数を返す
dp = [0] * (N+1)
temp = [[] for _ in range(N+1)] # 下から出てくる長さ
for v in order[::-1]:
p = parent[v]
S = temp[v]
S.sort()
s, l = make_pairs(S,x)
dp[v] += s
dp[p] += dp[v]
temp[p].append(l + 1)
if v == 1:
return dp[1] if not l else dp[1] + 1
seg = solve(N + 10)
left = 0 # むり
right = N # できる
while left + 1 < right:
x = (left + right) // 2
if solve(x) == seg:
right = x
else:
left = x
print(seg, right)
``` | output | 1 | 67,086 | 13 | 134,173 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc.
A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i.
He would like to make one as follows:
* Specify two non-negative integers A and B.
* Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1.
* Repeat the following operation until he has one connected tree:
* Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y.
* Properly number the vertices in the tree.
Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized.
Solve this problem for him.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For the lexicographically smallest (A,B), print A and B with a space in between.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
6 7
Output
3 2
Input
8
1 2
2 3
3 4
4 5
5 6
5 7
5 8
Output
2 5
Input
10
1 2
2 3
3 4
2 5
6 5
6 7
7 8
5 9
10 5
Output
3 4 | instruction | 0 | 67,087 | 13 | 134,174 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from bisect import bisect_right
N = int(readline())
m = map(int,read().split())
AB = zip(m,m)
graph = [[] for _ in range(N+1)]
for a,b in AB:
graph[a].append(b)
graph[b].append(a)
def make_pairs(A,S):
half = S//2
A.sort()
complete = 0
while A and A[-1] == S:
A.pop()
complete += 1
i = bisect_right(A,half)
U = A[i:][::-1]
D = A[:i][::-1]
cand = []
rest_U = []
for y in U:
while D and D[-1] + y <= S:
cand.append(D.pop())
if cand:
cand.pop()
complete += 1
else:
rest_U.append(y)
cand += D[::-1]
L = len(cand)
if L & 1:
# 一番小さいものを余らせる
complete += L // 2 + len(rest_U)
return complete, cand[0]
else:
complete += L // 2
if rest_U:
return complete + len(rest_U) - 1, rest_U[-1]
else:
return complete, 0
root = 1
parent = [0] * (N+1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
def num_of_seg(B):
# 長さBまで許容したとき、いくつの線分が必要になるか
dp = [0] * (N+1)
seg_lens = [[] for _ in range(N+1)]
for v in order[::-1]:
p = parent[v]
A = seg_lens[v]
pair, r = make_pairs(A,B)
dp[v] += pair
if v == root:
if r:
return dp[v] + 1
else:
return dp[v]
dp[p] += dp[v]
seg_lens[p].append(r + 1)
opt_A = num_of_seg(N+10)
left = 0 # むり
right = N + 10 # 可能
while left + 1 < right:
x = (left + right) // 2
if num_of_seg(x) == opt_A:
right = x
else:
left = x
B = right
A = opt_A
print(A,B)
``` | output | 1 | 67,087 | 13 | 134,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc.
A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i.
He would like to make one as follows:
* Specify two non-negative integers A and B.
* Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1.
* Repeat the following operation until he has one connected tree:
* Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y.
* Properly number the vertices in the tree.
Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized.
Solve this problem for him.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For the lexicographically smallest (A,B), print A and B with a space in between.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
6 7
Output
3 2
Input
8
1 2
2 3
3 4
4 5
5 6
5 7
5 8
Output
2 5
Input
10
1 2
2 3
3 4
2 5
6 5
6 7
7 8
5 9
10 5
Output
3 4
Submitted Solution:
```
import sys,heapq
input=sys.stdin.readline
N=int(input())
edge=[[] for i in range(N)]
for _ in range(N-1):
a,b=map(int,input().split())
edge[a-1].append(b-1)
edge[b-1].append(a-1)
def dfs(v,pv,n):
#print(v,pv,len(edge[v]))
if v!=0:
if len(edge[v])==1:
return 1
temp=[]
for nv in edge[v]:
if nv!=pv:
r=dfs(nv,v,n)
if r==-1:
return -1
temp.append(r)
if len(temp)%2==0:
temp.append(0)
elif len(temp)==1:
return temp[0]+1
temp.sort()
que=[]
#ban=set([])
k=len(temp)//2
for i in range(k):
heapq.heappush(que,(-temp[i+1]-temp[-i-1],i+1,N-1-i))
for i in range(k):
val,id1,id2=heapq.heappop(que)
while id1+id2==N and id1<=i:
val,id1,id2=heapq.heappop(que)
if val>=-n:
return temp[i]+1
heapq.heappush(que,(-temp[i]-temp[-i-1],i,N-1-i))
#ban.add((i+1,N-1-i))
for i in range(k):
val,id1,id2=heapq.heappop(que)
while (id1+id2==N) or (id1+id2==N-1 and id2<i+k):
val,id1,id2=heapq.heappop(que)
if val>=-n:
return temp[i+k]+1
heapq.heappush(que,(-temp[k-1-i]-temp[i+k],k-1-i,i+k))
#ban.add((N-1-i-k,i+k))
val,id1,id2=heapq.heappop(que)
while id1+id2!=2*k-1:
val,id1,id2=heapq.heappop(que)
if val>=-n:
return temp[-1]+1
return -1
else:
temp=[]
for nv in edge[v]:
if nv!=pv:
r=dfs(nv,v,n)
if r==-1:
return False
temp.append(r)
if len(temp)%2==1:
temp.append(0)
temp.sort()
k=len(temp)//2
for i in range(k):
test=temp[i]+temp[-i-1]
if test>n:
return False
return True
A=(len(edge[0])+1)//2
for i in range(1,N):
A+=(len(edge[i])-1)//2
start=0
end=N-1
while end-start>1:
t=(end+start)//2
if dfs(0,-1,t):
end=t
else:
start=t
print(A,end)
#ans=dfs(0,-1)
#print("YES" if ans else "NO")
``` | instruction | 0 | 67,088 | 13 | 134,176 |
No | output | 1 | 67,088 | 13 | 134,177 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc.
A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i.
He would like to make one as follows:
* Specify two non-negative integers A and B.
* Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1.
* Repeat the following operation until he has one connected tree:
* Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y.
* Properly number the vertices in the tree.
Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized.
Solve this problem for him.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For the lexicographically smallest (A,B), print A and B with a space in between.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
6 7
Output
3 2
Input
8
1 2
2 3
3 4
4 5
5 6
5 7
5 8
Output
2 5
Input
10
1 2
2 3
3 4
2 5
6 5
6 7
7 8
5 9
10 5
Output
3 4
Submitted Solution:
```
from collections import defaultdict
import sys
from math import log2
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def main():
def init(i, oi=-1, dpt=0):
depth[i] = dpt
parent_2k[0][i] = oi
for ki in to[i]:
if ki == oi: continue
init(ki, i, dpt + 1)
return
def make_parent(level):
parent_2kk1 = parent_2k[0]
for k in range(1, level):
parent_2kk = parent_2k[k]
for i in range(n):
parent1 = parent_2kk1[i]
if parent1 != -1:
parent_2kk[i] = parent_2kk1[parent1]
parent_2kk1 = parent_2kk
return
def lca(u, v):
dist_uv = depth[u] - depth[v]
if dist_uv < 0:
u, v = v, u
dist_uv *= -1
k = 0
while dist_uv:
if dist_uv & 1:
u = parent_2k[k][u]
dist_uv >>= 1
k += 1
if u == v:
return u
for k in range(int(log2(depth[u])) + 1, -1, -1):
pu = parent_2k[k][u]
pv = parent_2k[k][v]
if pu != pv:
u = pu
v = pv
return parent_2k[0][u]
def dfs(i, mx, len_odd):
if i == len_odd:
return mx
if fin[i]:
return dfs(i + 1, mx, len_odd)
res = inf
fin[i] = True
for j in range(i + 1, len_odd):
if fin[j]: continue
fin[j] = True
res = min(res, dfs(i + 1, max(mx, dist[i][j]), len_odd))
fin[j] = False
fin[i] = False
return res
inf = 10 ** 6
n = int(input())
to = defaultdict(list)
for _ in range(n - 1):
a, b = map(int1, input().split())
to[a].append(b)
to[b].append(a)
depth = [0] * n
level = int(log2(n)) + 1
parent_2k = [[-1] * n for _ in range(level)]
init(0)
make_parent(level)
odd_degree_nodes = []
for u in range(n):
if len(to[u]) % 2:
odd_degree_nodes.append(u)
# print(odd_degree_nodes)
len_odd = len(odd_degree_nodes)
ans_a = len_odd // 2
dist = [[-1] * len_odd for _ in range(len_odd)]
for j in range(len_odd):
v = odd_degree_nodes[j]
for i in range(j):
u = odd_degree_nodes[i]
lca_uv = lca(u, v)
dist[i][j] = dist[j][i] = depth[u] + depth[v] - 2 * depth[lca_uv]
# p2D(dist)
fin = [False] * len_odd
ans_b = dfs(0, 0, len_odd)
print(ans_a, ans_b)
main()
``` | instruction | 0 | 67,089 | 13 | 134,178 |
No | output | 1 | 67,089 | 13 | 134,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc.
A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i.
He would like to make one as follows:
* Specify two non-negative integers A and B.
* Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1.
* Repeat the following operation until he has one connected tree:
* Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y.
* Properly number the vertices in the tree.
Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized.
Solve this problem for him.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For the lexicographically smallest (A,B), print A and B with a space in between.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
6 7
Output
3 2
Input
8
1 2
2 3
3 4
4 5
5 6
5 7
5 8
Output
2 5
Input
10
1 2
2 3
3 4
2 5
6 5
6 7
7 8
5 9
10 5
Output
3 4
Submitted Solution:
```
#!/usr/bin/env python3
import bisect
n = 0
edges = None
visited = None
def dfs(v, b, r = False):
global visited
if not r:
visited = [False] * n
count = [0] * n
visited[v] = True
lengths = []
for c in edges[v]:
if not visited[c]:
k = dfs(c, b, True)
if k < 0:
return -1
lengths.append(k)
odd = (len(lengths) % 2 == 1) ^ r
lengths.sort()
while 1 < len(lengths):
k = lengths.pop()
if b < k:
return -1
elif k == b and odd:
odd = False
else:
i = bisect.bisect_right(lengths, b - k)
if i == 0:
return -1
lengths.pop(i - 1)
if len(lengths) == 0:
return 1
else:
return lengths[0] + 1
def solve():
root = None
a = 1
for i in range(n):
c = len(edges[i])
if 3 <= c:
a += (c - 1) // 2
root = i
if root is None:
return 1, n - 1
ok = n - 1
ng = 1
while ng + 1 < ok:
mid = (ok + ng) // 2
if 0 <= dfs(root, mid):
ok = mid
else:
ng = mid
return a, ok
def main():
global n
global edges
n = int(input())
edges = [[] for _ in range(n)]
for i in range(n - 1):
a, b = input().split()
a = int(a) - 1
b = int(b) - 1
edges[a].append(b)
edges[b].append(a)
a, b = solve()
print('{} {}'.format(a, b))
if __name__ == '__main__':
main()
``` | instruction | 0 | 67,090 | 13 | 134,180 |
No | output | 1 | 67,090 | 13 | 134,181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc.
A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i.
He would like to make one as follows:
* Specify two non-negative integers A and B.
* Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1.
* Repeat the following operation until he has one connected tree:
* Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y.
* Properly number the vertices in the tree.
Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized.
Solve this problem for him.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For the lexicographically smallest (A,B), print A and B with a space in between.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
6 7
Output
3 2
Input
8
1 2
2 3
3 4
4 5
5 6
5 7
5 8
Output
2 5
Input
10
1 2
2 3
3 4
2 5
6 5
6 7
7 8
5 9
10 5
Output
3 4
Submitted Solution:
```
import sys,heapq
input=sys.stdin.readline
sys.setrecursionlimit(2*10**5)
N=int(input())
edge=[[] for i in range(N)]
for _ in range(N-1):
a,b=map(int,input().split())
edge[a-1].append(b-1)
edge[b-1].append(a-1)
temp=[[0 for j in range(len(edge[i])-1)] for i in range(N)]
temp[0].append(0)
for i in range(1,N):
if len(temp[i])%2==0:
temp[i].append(0)
if len(temp[0])%2==1:
temp[0].append(0)
def clear():
for i in range(N):
temp[i].sort()
for j in range(len(temp[i])):
temp[i][j]=0
start=0
end=N-1
while end-start>1:
t=(end+start)//2
clear()
end=t
print(end)
``` | instruction | 0 | 67,091 | 13 | 134,182 |
No | output | 1 | 67,091 | 13 | 134,183 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges.
Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
How many different paths start from vertex 1 and visit all the vertices exactly once?
Here, the endpoints of a path are considered visited.
For example, let us assume that the following undirected graph shown in Figure 1 is given.
<image>
Figure 1: an example of an undirected graph
The following path shown in Figure 2 satisfies the condition.
<image>
Figure 2: an example of a path that satisfies the condition
However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.
<image>
Figure 3: an example of a path that does not satisfy the condition
Neither the following path shown in Figure 4, because it does not start from vertex 1.
<image>
Figure 4: another example of a path that does not satisfy the condition
Constraints
* 2≦N≦8
* 0≦M≦N(N-1)/2
* 1≦a_i<b_i≦N
* The given graph contains neither self-loops nor double edges.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1
a_2 b_2
:
a_M b_M
Output
Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.
Examples
Input
3 3
1 2
1 3
2 3
Output
2
Input
7 7
1 3
2 7
3 4
4 5
4 6
5 6
6 7
Output
1 | instruction | 0 | 67,108 | 13 | 134,216 |
"Correct Solution:
```
import itertools
n, m = [int(x) for x in input().split()]
edges = set(tuple(int(x) for x in input().split()) for _ in range(m))
print(sum(1 if all(p in edges or tuple(reversed(p)) in edges for p in [(1, path[0])] + list(zip(path, path[1:]))) else 0 for path in itertools.permutations(range(2, n + 1))))
``` | output | 1 | 67,108 | 13 | 134,217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.