message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red.
You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, β¦, a_k] good if it satisfies the following criterion:
* We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k.
* Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k.
* If you walked over at least one black edge during this process, then the sequence is good.
<image>
Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3].
There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7.
Input
The first line contains two integers n and k (2 β€ n β€ 10^5, 2 β€ k β€ 100), the size of the tree and the length of the vertex sequence.
Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 β€ u_i, v_i β€ n, x_i β \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge).
Output
Print the number of good sequences modulo 10^9 + 7.
Examples
Input
4 4
1 2 1
2 3 1
3 4 1
Output
252
Input
4 6
1 2 0
1 3 0
1 4 0
Output
0
Input
3 5
1 2 1
2 3 0
Output
210
Note
In the first example, all sequences (4^4) of length 4 except the following are good:
* [1, 1, 1, 1]
* [2, 2, 2, 2]
* [3, 3, 3, 3]
* [4, 4, 4, 4]
In the second example, all edges are red, hence there aren't any good sequences.
Submitted Solution:
```
def ConnectedComponents(dct,visited,s):
global count
count+=1
visited[s] = True
for v in dct[s]:
if(visited[v]==False):
ConnectedComponents(dct,visited,v)
def ModPower(n,k,Mod):
if(n==0):
return 0
if(k==0):
return 1
if(k%2==0):
temp = ModPower(n,k//2,Mod)
return temp*temp%Mod
else:
temp = ModPower(n,(k-1)//2,Mod)
return n*temp*temp%Mod
from collections import defaultdict
Mod = 10**9+7
n,k = map(int,input().split())
dct = defaultdict(list)
for i in range(n-1):
u,v,w = map(int,input().split())
if(w==0):
dct[u].append(v)
dct[v].append(u)
count = None
visited = [False for i in range(n+1)]
total = 0
for i in range(1,n+1):
if(visited[i]==False):
count = 0
ConnectedComponents(dct,visited,i)
total = (total+ModPower(count,k,Mod))%Mod
temp = ModPower(n,k,Mod) - total
print(temp)
``` | instruction | 0 | 6,626 | 13 | 13,252 |
No | output | 1 | 6,626 | 13 | 13,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red.
You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, β¦, a_k] good if it satisfies the following criterion:
* We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k.
* Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k.
* If you walked over at least one black edge during this process, then the sequence is good.
<image>
Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3].
There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7.
Input
The first line contains two integers n and k (2 β€ n β€ 10^5, 2 β€ k β€ 100), the size of the tree and the length of the vertex sequence.
Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 β€ u_i, v_i β€ n, x_i β \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge).
Output
Print the number of good sequences modulo 10^9 + 7.
Examples
Input
4 4
1 2 1
2 3 1
3 4 1
Output
252
Input
4 6
1 2 0
1 3 0
1 4 0
Output
0
Input
3 5
1 2 1
2 3 0
Output
210
Note
In the first example, all sequences (4^4) of length 4 except the following are good:
* [1, 1, 1, 1]
* [2, 2, 2, 2]
* [3, 3, 3, 3]
* [4, 4, 4, 4]
In the second example, all edges are red, hence there aren't any good sequences.
Submitted Solution:
```
n, k = map(int, input().split())
c = 0
for _ in range(n-1):
u, v, x = map(int, input().split())
if x == 0:
c += 1
print((pow(n, k) - n - (pow(c+1, k)-c)+1)%1000000007)
``` | instruction | 0 | 6,627 | 13 | 13,254 |
No | output | 1 | 6,627 | 13 | 13,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 6,957 | 13 | 13,914 |
Tags: binary search, data structures, dp
Correct Solution:
```
import bisect
n=int(input())
a=list(map(int,input().split()))
INF=10**18
dp=[INF]*n
for i in range(n):
dp[bisect.bisect_left(dp,a[i])]=a[i]
print(bisect.bisect_left(dp,INF))
``` | output | 1 | 6,957 | 13 | 13,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 6,958 | 13 | 13,916 |
Tags: binary search, data structures, dp
Correct Solution:
```
from bisect import bisect_right
def answer(n,A):
ans=[A[0]]
for i in range(1,n):
if ans[-1]<A[i]:
ans.append(A[i])
else:
index=bisect_right(ans,A[i])
ans[index]=A[i]
return len(ans)
n=int(input())
arr=list(map(int,input().split()))
print(answer(n,arr))
``` | output | 1 | 6,958 | 13 | 13,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 6,959 | 13 | 13,918 |
Tags: binary search, data structures, dp
Correct Solution:
```
def lis(a):
b = []
for c in a:
# if len(b) == 0 or c > b[-1]
if len(b) == 0 or c > b[-1]:
b.append(c)
else:
l = 0
r = len(b)
while l < r-1:
m = l+r>>1
# if b[m] <= c: l = m
if b[m] < c: l = m
else: r = m
# if b[l] <= c: l += 1
if b[l] < c: l += 1
b[l] = c
return len(b)
n = int(input())
a = list(map(int, input().split()))
print(lis(a))
# Made By Mostafa_Khaled
``` | output | 1 | 6,959 | 13 | 13,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 6,960 | 13 | 13,920 |
Tags: binary search, data structures, dp
Correct Solution:
```
import sys,math as mt
import heapq as hp
import collections as cc
import math as mt
import itertools as it
input=sys.stdin.readline
I=lambda:list(map(int,input().split()))
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (A[m] >= key):
r = m
else:
l = m
return r
def lis(A, size):
tailTable = [0 for i in range(size + 1)]
len = 0
tailTable[0] = A[0]
len = 1
for i in range(1, size):
if (A[i] < tailTable[0]):
tailTable[0] = A[i]
elif (A[i] > tailTable[len-1]):
tailTable[len] = A[i]
len+= 1
else:
tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i]
return len
n,=I()
l=I()
print(lis(l,n))
``` | output | 1 | 6,960 | 13 | 13,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 6,961 | 13 | 13,922 |
Tags: binary search, data structures, dp
Correct Solution:
```
import sys; sys.setrecursionlimit(1000000)
def solve():
# 3 1 2 4
# 1 2 3 4
# 2 1 3 5 4
# 1 2 3 4 5
n, = rv()
a, = rl(1)
# 3 1 2 7 4 6 5
# [ , 1 , , , , ]
# [ , 1 , 2 , , , ]
# [ , 1 , 2 , 4, 5, ]
mem = [10000000] * (n + 1)
mem[0] = a[0]
for i in range(1, n):
left, right = 0, n - 1
while left < right:
mid = (left + right) // 2
if a[i] < mem[mid]: right = mid
else: left = mid + 1
mem[left] = a[i]
# for j in range(n):
# if a[i] < mem[j]:
# mem[j] = a[i]
# break
res = 0
# print(mem)
for i in range(1, n):
if mem[i] != 10000000: res = i
print(res + 1)
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
``` | output | 1 | 6,961 | 13 | 13,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 6,962 | 13 | 13,924 |
Tags: binary search, data structures, dp
Correct Solution:
```
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (A[m] >= key):
r = m
else:
l = m
return r
def LongestIncreasingSubsequenceLength(A, size):
# Add boundary case,
# when array size is one
tailTable = [0 for i in range(size + 1)]
len = 0 # always points empty slot
tailTable[0] = A[0]
len = 1
for i in range(1, size):
if (A[i] < tailTable[0]):
# new smallest value
tailTable[0] = A[i]
elif (A[i] > tailTable[len-1]):
# A[i] wants to extend
# largest subsequence
tailTable[len] = A[i]
len+= 1
else:
# A[i] wants to be current
# end candidate of an existing
# subsequence. It will replace
# ceil value in tailTable
tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i]
return len
n=int(input())
l=list(map(int,input().split()))
print(LongestIncreasingSubsequenceLength(l, n))
``` | output | 1 | 6,962 | 13 | 13,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 6,963 | 13 | 13,926 |
Tags: binary search, data structures, dp
Correct Solution:
```
n = int(input())
num_list = list(map(int, input().split()))
# def lower_bound(min_lis, x):
# #goal return the position of the first element >= x
# left = 0
# right = len(min_lis) - 1
# res = -1
# while left <= right:
# mid = (left + right) // 2
# if min_lis[mid] < x:
# left = mid + 1
# else:
# res = mid
# right = mid - 1
# return res
import bisect
def LongestIncreasingSubsequence(a, n):
min_lis = []
#lis = [0 for i in range(n)]
for i in range(n):
pos = bisect.bisect_left(min_lis, a[i])
if pos == len(min_lis):
#lis[i] = len(min_lis) + 1
min_lis.append(a[i])
else:
#lis[i] = pos + 1
min_lis[pos] = a[i]
#print(*min_lis)
return (len(min_lis))
print(LongestIncreasingSubsequence(num_list, n))
``` | output | 1 | 6,963 | 13 | 13,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 6,964 | 13 | 13,928 |
Tags: binary search, data structures, dp
Correct Solution:
```
MXusl = int
MXuso = input
MXusL = map
MXusr = min
MXusI = print
n = MXusl(MXuso())
a = [1e6] * (n + 1)
s = 1
for x in MXusL(MXusl, MXuso().split()):
l = 0
r = s
while r-l > 1:
m = (l + r) >> 1
if a[m] < x:
l = m
else:
r = m
s += r == s
a[r] = MXusr(a[r], x)
MXusI(s - 1)
``` | output | 1 | 6,964 | 13 | 13,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
""" Python 3 compatibility tools. """
from __future__ import division, print_function
import itertools
import sys
import os
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
def is_it_local():
script_dir = str(os.getcwd()).split('/')
username = "dipta007"
return username in script_dir
def READ(fileName):
if is_it_local():
sys.stdin = open(f'./{fileName}', 'r')
# 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")
if not is_it_local():
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
def input1(type=int):
return type(input())
def input2(type=int):
[a, b] = list(map(type, input().split()))
return a, b
def input3(type=int):
[a, b, c] = list(map(type, input().split()))
return a, b, c
def input_array(type=int):
return list(map(type, input().split()))
def input_string():
s = input()
return list(s)
##############################################################
#Given a list of numbers of length n, this routine extracts a
#longest increasing subsequence.
#
#Running time: O(n log n)
#
# INPUT: a vector of integers
# OUTPUT: a vector containing the longest increasing subsequence
def lower_bound(nums, target):
l, r = 0, len(nums) - 1
res = len(nums)
while l <= r:
mid = int(l + (r - l) / 2)
if nums[mid] >= target:
res = mid
r = mid - 1
else:
l = mid + 1
return res
def upper_bound(nums, target):
l, r = 0, len(nums) - 1
res = len(nums)
while l <= r:
mid = int(l + (r - l) / 2)
if nums[mid] > target:
r = mid - 1
res = mid
else:
l = mid + 1
return res
def LIS(v, STRICTLY_INCREASING = False):
best = []
dad = [-1 for _ in range(len(v))]
for i in range(len(v)):
if STRICTLY_INCREASING:
item = (v[i], 0)
pos = lower_bound(best, item)
item.second = i
else:
item = (v[i], i)
pos = upper_bound(best, item)
if pos == len(best):
dad[i] = -1 if len(best) == 0 else best[-1][1]
best.append(item)
else:
dad[i] = -1 if pos == 0 else best[pos-1][1]
best[pos] = item
# print(pos, best)
# ret = []
i = best[-1][1]
cnt = 0
while i >= 0:
# ret.append(v[i])
cnt += 1
i = dad[i]
# ret.reverse()
return cnt
def main():
n = input1()
v = input_array()
print(LIS(v))
pass
if __name__ == '__main__':
READ('in.txt')
main()
``` | instruction | 0 | 6,965 | 13 | 13,930 |
Yes | output | 1 | 6,965 | 13 | 13,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
def lis(a):
b = []
for c in a:
# if len(b) == 0 or c > b[-1]
if len(b) == 0 or c > b[-1]:
b.append(c)
else:
l = 0
r = len(b)
while l < r-1:
m = l+r>>1
# if b[m] <= c: l = m
if b[m] < c: l = m
else: r = m
# if b[l] <= c: l += 1
if b[l] < c: l += 1
b[l] = c
return len(b)
n = int(input())
a = list(map(int, input().split()))
print(lis(a))
``` | instruction | 0 | 6,966 | 13 | 13,932 |
Yes | output | 1 | 6,966 | 13 | 13,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
from bisect import bisect_left, bisect_right, insort
R = lambda: map(int, input().split())
n, arr = int(input()), list(R())
dp = []
for i in range(n):
idx = bisect_left(dp, arr[i])
if idx >= len(dp):
dp.append(arr[i])
else:
dp[idx] = arr[i]
print(len(dp))
``` | instruction | 0 | 6,967 | 13 | 13,934 |
Yes | output | 1 | 6,967 | 13 | 13,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
from bisect import *
s, n = [0], input()
for i in map(int, input().split()):
if i > s[-1]: s.append(i)
else: s[bisect_right(s, i)] = i
print(len(s) - 1)
``` | instruction | 0 | 6,968 | 13 | 13,936 |
Yes | output | 1 | 6,968 | 13 | 13,937 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
from bisect import bisect_left
R = lambda: map(int, input().split())
n = int(input())
arr = list(R())
tps = [(0, 0)]
for x in arr:
i = bisect_left(tps, (x, -1)) - 1
tps.insert(i + 1, (x, tps[i][1] + 1))
print(max(x[1] for x in tps))
``` | instruction | 0 | 6,969 | 13 | 13,938 |
No | output | 1 | 6,969 | 13 | 13,939 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
def gis(A) :
F=[0]*(len(A)+1)
for i in range(1,len(A)+1) :
m=0
for j in range(i) :
if A[i-1]>A[j-1] :
m=max(m,F[j])
F[i]=m+1
return F[-1]
n=int(input())
l=list(map(int,input().split()))
print(gis(l))
``` | instruction | 0 | 6,970 | 13 | 13,940 |
No | output | 1 | 6,970 | 13 | 13,941 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
n = int(input())
X = [0]+[int(x) for x in input().split()]
def binSearch(L,Xi,X,M):
#if X[M[L]] < Xi: return L
#if X[M[1]] >= Xi: return 0
low = 1
high = L+1
while high-low > 1:
mid = (low+high)//2
if X[M[mid]] < Xi:
low = mid
else:
high = mid
if X[M[low]] < Xi: return low
return 0
L = 0
M = [0 for i in range(n+1)]
#P = [0 for i in range(n+1)]
for i in range(1,n+1):
j = binSearch(L,X[i],X,M)
#print(i,L,X[i],M,j)
#P[i] = M[j]
if j == L or X[i] < X[M[j+1]]:
#print("UPD",j,L,X[i],X[M[j+1]],i,j,M)
M[j+1] = i
L = max(L,j+1)
print(L)
#print(P)
``` | instruction | 0 | 6,971 | 13 | 13,942 |
No | output | 1 | 6,971 | 13 | 13,943 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 β€ n β€ 105). The next line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ n).
Output
Output a single integer β the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
ans=0
m=a[-1]
ans=1
for i in range(n-2,-1,-1):
if m>a[i]:
ans+=1
m=a[i]
print(ans)
``` | instruction | 0 | 6,972 | 13 | 13,944 |
No | output | 1 | 6,972 | 13 | 13,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color. | instruction | 0 | 7,058 | 13 | 14,116 |
Tags: dfs and similar, dp, dsu, graphs
Correct Solution:
```
def dfs_paths(graph, start, goal, path=list()):
if not path:
path.append(start)
if start == goal:
yield path
for vertex in graph[start] - set(path):
yield from dfs_paths(graph, vertex, goal, path=path + [vertex])
n, m = map(int, input().split())
graph = {}
for _ in range(m):
a, b, c = map(int, input().split())
if c not in graph:
graph[c] = {}
if a not in graph[c]:
graph[c][a] = set()
if b not in graph[c]:
graph[c][b] = set()
graph[c][a].add(b)
graph[c][b].add(a)
q = int(input())
for _ in range(q):
u, v = map(int, input().split())
count = 0
for k in graph:
if u not in graph[k] or v not in graph[k]:
continue
if len(list(dfs_paths(graph[k], u, v, []))) > 0:
count += 1
print(count)
``` | output | 1 | 7,058 | 13 | 14,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color. | instruction | 0 | 7,059 | 13 | 14,118 |
Tags: dfs and similar, dp, dsu, graphs
Correct Solution:
```
class Solution:
def __init__(self, n, m, edges):
self.n = n
self.m = m
self.edges = [[[] for _ in range(m+1)] for _ in range(n+1)]
for _from, _to, _color in edges:
self.edges[_from][_color].append(_to)
self.edges[_to][_color].append(_from)
self.id = 0
def initialize(self):
self.discovered = [[0]*(self.n+1) for i in range(self.m+1)]
def bfs(self, x0, color):
self.id += 1
stack = [x0]
while stack:
n = stack.pop()
if not self.discovered[color][n]:
self.discovered[color][n] = self.id
for neigh in self.edges[n][color]:
stack.append(neigh)
def solve(graph, colors, u, v):
counter = 0
for color in colors:
if not graph.discovered[color][u] and not graph.discovered[color][v]:
graph.bfs(u, color)
if graph.discovered[color][u] == graph.discovered[color][v]:
counter += 1
return counter
def main():
n, m = map(int, input().split())
edges = []
colors = set()
for _ in range(m):
a, b, c = map(int, input().split())
colors.add(c)
edges.append((a, b, c))
graph = Solution(n, m, edges)
graph.initialize()
q = int(input())
for _ in range(q):
u, v = map(int, input().split())
print(solve(graph, colors, u, v))
if __name__ == '__main__':
main()
``` | output | 1 | 7,059 | 13 | 14,119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color. | instruction | 0 | 7,060 | 13 | 14,120 |
Tags: dfs and similar, dp, dsu, graphs
Correct Solution:
```
import sys
from collections import defaultdict
from functools import lru_cache
from collections import Counter
def mi(s):
return map(int, s.strip().split())
def lmi(s):
return list(mi(s))
def mf(f, s):
return map(f, s)
def lmf(f, s):
return list(mf(f, s))
def path(graph, u, v, color, visited):
if u == v:
return True
elif u in visited:
return False
visited.add(u)
for child, c in graph[u]:
if color == c and path(graph, child, v, color, visited):
return True
return False
def main(graph, queries, colors):
ans = []
for u, v in queries:
c = 0
for color in colors:
if path(graph, u, v, color, set()):
c += 1
ans.append(c)
for n in ans:
print(n)
if __name__ == "__main__":
queries = []
colors = set()
for e, line in enumerate(sys.stdin.readlines()):
if e == 0:
n, ed = mi(line)
graph = defaultdict(list)
for i in range(1, n + 1):
graph[i]
k = 0
elif ed > 0:
a, b, c = mi(line)
# Undirected graph.
graph[a].append((b, c))
graph[b].append((a, c))
colors.add(c)
ed -= 1
elif ed == 0:
ed -= 1
continue
else:
queries.append(lmi(line))
main(graph, queries, colors)
``` | output | 1 | 7,060 | 13 | 14,121 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color. | instruction | 0 | 7,061 | 13 | 14,122 |
Tags: dfs and similar, dp, dsu, graphs
Correct Solution:
```
class CodeforcesTask505BSolution:
def __init__(self):
self.result = ''
self.n_m = []
self.edges = []
self.q = 0
self.queries = []
def read_input(self):
self.n_m = [int(x) for x in input().split(" ")]
for x in range(self.n_m[1]):
self.edges.append([int(y) for y in input().split(" ")])
self.q = int(input())
for x in range(self.q):
self.queries.append([int(y) for y in input().split(" ")])
def process_task(self):
graphs = [[[] for x in range(self.n_m[0])] for c in range(self.n_m[1])]
for edge in self.edges:
graphs[edge[2] - 1][edge[0] - 1].append(edge[1])
graphs[edge[2] - 1][edge[1] - 1].append(edge[0])
results = []
for query in self.queries:
to_visit = [(query[0], c) for c in range(self.n_m[1])]
used = set()
visited = [[False] * self.n_m[0] for x in range(self.n_m[1])]
while to_visit:
visiting = to_visit.pop(-1)
if visiting[1] not in used and not visited[visiting[1]][visiting[0] - 1]:
visited[visiting[1]][visiting[0] - 1] = True
if visiting[0] == query[1]:
used.add(visiting[1])
else:
to_visit.extend([(x, visiting[1]) for x in graphs[visiting[1]][visiting[0] - 1]])
colors = len(used)
results.append(colors)
self.result = "\n".join([str(x) for x in results])
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask505BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
``` | output | 1 | 7,061 | 13 | 14,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color. | instruction | 0 | 7,062 | 13 | 14,124 |
Tags: dfs and similar, dp, dsu, graphs
Correct Solution:
```
class Graph(object):
def __init__(self, num_nodes):
self.num_nodes = num_nodes
self.adj_list = {}
def __add_directional_edge(self, a, b, c):
if a in self.adj_list:
if b in self.adj_list[a]:
if c not in self.adj_list[a][b]:
self.adj_list[a][b].append(c)
else:
self.adj_list[a][b] = []
self.adj_list[a][b].append(c)
else:
self.adj_list[a] = {}
self.adj_list[a][b] = []
self.adj_list[a][b].append(c)
def add_edge(self, a, b, c):
self.__add_directional_edge(a, b, c)
self.__add_directional_edge(b, a, c)
def print_graph(self):
print(self.adj_list)
def tc():
g = readGraph()
# g.print_graph()
for k in range(1, g.num_nodes + 1):
for i in range(1, g.num_nodes + 1):
for j in range(1, g.num_nodes + 1):
l1 = g.adj_list.get(i, {}).get(k, [])
l2 = g.adj_list.get(k, {}).get(j, [])
for color in l1:
if color in l2:
g.add_edge(i,j,color)
# g.print_graph()
return g
def readGraph():
n, m = map(int, input().split())
g = Graph(n)
for _ in range(m):
a, b, c = map(int, input().split())
g.add_edge(a,b,c)
return g
def read_query():
q = int(input())
q_list = []
for _ in range(q):
u,v = map(int, input().split())
q_list.append((u,v))
return q_list
def solve_query(g, q_list):
for u,v in q_list:
if u in g.adj_list:
if v in g.adj_list[u]:
print(len(g.adj_list[u][v]))
else:
print("0")
else:
print("0")
def main():
g = tc()
q_list = read_query()
solve_query(g, q_list)
if __name__ == "__main__":
main()
``` | output | 1 | 7,062 | 13 | 14,125 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color. | instruction | 0 | 7,063 | 13 | 14,126 |
Tags: dfs and similar, dp, dsu, graphs
Correct Solution:
```
from collections import defaultdict
def DFS(d,a,visited):
visited[a] = 1
if a in d:
for i in d[a]:
if visited[i] == 1:
continue
else:
DFS(d,i,visited)
n,m = map(int,input().split())
l = [defaultdict(list) for i in range(m+1)]
for i in range(m):
a,b,c = map(int,input().split())
l[c][a].append(b)
l[c][b].append(a)
q = int(input())
for i in range(q):
a,b = map(int,input().split())
r = 0
for j in l:
visited = [0 for i in range(n+1)]
DFS(j,a,visited)
if visited[a] == 1 and visited[b] == 1:
r = r + 1
print(r)
``` | output | 1 | 7,063 | 13 | 14,127 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color. | instruction | 0 | 7,064 | 13 | 14,128 |
Tags: dfs and similar, dp, dsu, graphs
Correct Solution:
```
n,m=map(int,input().split())
g=[[] for _ in range(n)]
for _ in range(m):
a,b,c=map(int,input().split())
g[a-1].append((b-1,c-1))
g[b-1].append((a-1,c-1))
def dfs(x,c,t):
if x==t:return True
v[x]=1
for j in g[x]:
if j[1]==c and v[j[0]]==0:
if dfs(j[0],c,t):return True
return False
q=int(input())
o=[0]*q
v=[]
for i in range(q):
f,y=map(int,input().split())
for c in range(100):
v=[0]*n
if dfs(f-1,c,y-1):o[i]+=1
print('\n'.join(list(map(str,o))))
``` | output | 1 | 7,064 | 13 | 14,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color. | instruction | 0 | 7,065 | 13 | 14,130 |
Tags: dfs and similar, dp, dsu, graphs
Correct Solution:
```
def get_connected_matrix(adjacency_matrix):
n = len(adjacency_matrix)
non_visited_vertices = set(i for i in range(n))
cluster_numbers = [0] * n
cluster_number = 1
def traverse(u):
non_visited_vertices.remove(u)
cluster_numbers[u] = cluster_number
for v in range(n):
if v in non_visited_vertices:
if adjacency_matrix[u][v]:
traverse(v)
while non_visited_vertices:
vertex = non_visited_vertices.pop()
non_visited_vertices.add(vertex)
traverse(vertex)
cluster_number += 1
connected_matrix = [[False] * n for _ in range(n)]
for u in range(n):
for v in range(n):
if u == v:
continue
connected_matrix[u][v] = connected_matrix[v][u] = (cluster_numbers[u] == cluster_numbers[v])
return connected_matrix
def main():
n, m = [int(t) for t in input().split()]
matrices = [[[False] * n for _ in range(n)] for _ in range(m)]
for _ in range(m):
a, b, c = [int(t) - 1 for t in input().split()]
matrices[c][a][b] = True
matrices[c][b][a] = True
connected_matrices = [get_connected_matrix(matrix) for matrix in matrices]
q = int(input())
for _ in range(q):
u, v = [int(t) - 1 for t in input().split()]
total_connection = sum(1 for connected_matrix in connected_matrices if connected_matrix[u][v])
print(total_connection)
if __name__ == '__main__':
main()
``` | output | 1 | 7,065 | 13 | 14,131 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
from collections import defaultdict
def main():
n, m = map(int, input().split())
edges = defaultdict(lambda: defaultdict(list))
for _ in range(m):
a, b, c = map(int, input().split())
d = edges[c]
d[a].append(b)
d[b].append(a)
def dfs(t):
chain.add(t)
dd = color.get(t, ())
for y in dd:
if y not in chain:
dfs(y)
res = []
chain = set()
for _ in range(int(input())):
a, b = map(int, input().split())
x = 0
for color in edges.values():
chain.clear()
dfs(a)
if b in chain:
x += 1
res.append(str(x))
print('\n'.join(res))
if __name__ == '__main__':
main()
``` | instruction | 0 | 7,066 | 13 | 14,132 |
Yes | output | 1 | 7,066 | 13 | 14,133 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
from collections import defaultdict
from sys import stdin, stdout
par = defaultdict(list)
def build(n):
global par, size
for c in range(101):
par[c] = []
for i in range(n):
par[c].append(i)
return par
def find(c, i):
global par
if par[c][i] == i:
return i
par[c][i] = find(c, par[c][i])
return par[c][i]
def union(a, b, c):
global par, scc, size
p = find(c, a)
q = find(c, b)
if p == q:
return
par[c][q] = par[c][p]
def main():
(n, m) = map(int, stdin.readline().strip().split(' '))
par = build(n)
max_c = 0
for i in range(m):
(a, b, c) = map(lambda i: int(i) - 1, stdin.readline().strip().split(' '))
union(a, b, c)
max_c = max(max_c, c)
q = int(stdin.readline().strip())
for i in range(q):
(a, b) = map(lambda i: int(i) - 1, stdin.readline().strip().split(' '))
count = 0
for c in range(max_c + 1):
p = find(c, a)
q = find(c, b)
if p == q:
count += 1
stdout.write('{}\n'.format(count))
main()
``` | instruction | 0 | 7,067 | 13 | 14,134 |
Yes | output | 1 | 7,067 | 13 | 14,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
class Union:
def __init__(self, size):
self.ancestor = [i for i in range(size+1)]
def find(self, node):
if self.ancestor[node] == node:
return node
self.ancestor[node] = self.find(self.ancestor[node])
return self.ancestor[node]
def merge(self, a, b):
a, b = self.find(a), self.find(b)
self.ancestor[a] = b
n, m = map(int, input().split())
unions = [Union(n) for _ in range(m+1)]
graph = [[] for _ in range(n+1)]
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((b, c))
graph[b].append((a, c))
unions[c].merge(a, b)
for _ in range(int(input())):
a, b = map(int, input().split())
ans = 0
for i in range(1, m+1):
ans += unions[i].find(a) == unions[i].find(b)
print(ans)
``` | instruction | 0 | 7,068 | 13 | 14,136 |
Yes | output | 1 | 7,068 | 13 | 14,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
def dfs(place,target):
vis[place]=True
if target==place:total[0]+=1;return()
anyAdj=0
for i in j[place]:
if not vis[i]:anyAdj=1;dfs(i,target)
if anyAdj==0:return()
v,e=map(int,input().split())
edges=[]
for i in range(e):edges.append(list(map(int,input().split())))
colors=[]
for i in edges:colors.append(i[2])
colors=list(set(colors))
colorAdjs=[]
for i in colors:
colorAdjs.append([[] for w in range(v)])
for j in edges:
if j[2]==i:
colorAdjs[-1][j[0]-1].append(j[1]-1)
colorAdjs[-1][j[1]-1].append(j[0]-1)
q=int(input())
for i in range(q):
total=[0]
a,b=map(int,input().split())
a-=1;b-=1
for j in colorAdjs:
vis=[False]*v
dfs(a,b)
print(total[0])
``` | instruction | 0 | 7,069 | 13 | 14,138 |
Yes | output | 1 | 7,069 | 13 | 14,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
import sys
import math
from collections import defaultdict
import itertools
MAXNUM = math.inf
MINNUM = -1 * math.inf
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def printOutput(ans):
sys.stdout.write()
pass
def dfs(a, b, edgeList):
total = 0
for nxt, col in edgeList[a]:
explored = dict()
explored[a] = True
explored[nxt] = True
total += dfs_helper(nxt, b, edgeList, col, explored)
return total
def dfs_helper(cur, goal, edgeList, color, explored):
if cur == goal:
return 1
for nxt, col in edgeList[cur]:
if col == color and nxt not in explored:
explored[nxt] = True
if dfs_helper(nxt, goal, edgeList, color, explored) == 1:
return 1
return 0
def solve(n, m, edgeList, queries):
for a, b in queries:
print(dfs(a, b, edgeList))
def readinput():
n, m = getInts()
edgeList = defaultdict(list)
for _ in range(m):
a, b, c = getInts()
edgeList[a].append((b, c))
edgeList[b].append((a, c))
queries = []
q = getInt()
for _ in range(q):
queries.append(tuple(getInts()))
(solve(n, m, edgeList, queries))
readinput()
``` | instruction | 0 | 7,070 | 13 | 14,140 |
No | output | 1 | 7,070 | 13 | 14,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
def gerarGrafo(cor):
adjancencias = {}
for aresta in arestas:
if aresta[2] == cor:
if adjancencias.get(aresta[0]) == None:
adjancencias[aresta[0]] = []
if adjancencias.get(aresta[1]) == None:
adjancencias[aresta[1]] = []
adjancencias[aresta[0]].append(aresta[1])
adjancencias[aresta[1]].append(aresta[0])
return adjancencias
def dfs(u, w, adjacencias):
pilha = [u]
visitados = {u: 1}
existeCaminhoUV = False
if adjacencias.get(u) == None or adjacencias.get(w) == None:
return existeCaminhoUV
while len(pilha) > 0:
vertice = pilha.pop()
for v in adjacencias[vertice]:
if visitados.get(v) == None:
visitados[v] = 1
pilha.append(v)
if visitados.get(w) != None:
existeCaminhoUV = True
return existeCaminhoUV
entrada = input().split()
n = int(entrada[0])
m = int(entrada[1])
cores = set()
arestas = []
i = 0
while i < m:
aresta = input().split()
cores.add(aresta[2])
arestas.append(aresta)
i += 1
q = int(input())
paresVertices = []
i = 0
while i < q:
paresVertices.append(input().split())
i += 1
res = [0] * q
for cor in cores:
grafo = gerarGrafo(cor)
print(grafo)
i = 0
for par in paresVertices:
if dfs(par[0], par[1], grafo):
res[i] += 1
i += 1
for e in res:
print(e)
``` | instruction | 0 | 7,071 | 13 | 14,142 |
No | output | 1 | 7,071 | 13 | 14,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
import sys
import math
from collections import defaultdict
import itertools
MAXNUM = math.inf
MINNUM = -1 * math.inf
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def printOutput(ans):
sys.stdout.write()
pass
def dfs(a, b, edgeList):
total = 0
for nxt, col in edgeList[a]:
explored = dict()
explored[a] = True
explored[nxt] = True
total += dfs_helper(nxt, b, edgeList, col, explored)
return total
def dfs_helper(cur, goal, edgeList, color, explored):
if cur == goal:
return 1
for nxt, col in edgeList[cur]:
if col == color and nxt not in explored:
explored[nxt] = True
if dfs_helper(nxt, goal, edgeList, color, explored) == 1:
return 1
del explored[nxt]
return 0
def solve(n, m, edgeList, queries):
for a, b in queries:
print(dfs(a, b, edgeList))
def readinput():
n, m = getInts()
edgeList = defaultdict(list)
for _ in range(m):
a, b, c = getInts()
edgeList[a].append((b, c))
edgeList[b].append((a, c))
queries = []
q = getInt()
for _ in range(q):
queries.append(tuple(getInts()))
(solve(n, m, edgeList, queries))
readinput()
``` | instruction | 0 | 7,072 | 13 | 14,144 |
No | output | 1 | 7,072 | 13 | 14,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers β ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers β n and m (2 β€ n β€ 100, 1 β€ m β€ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers β ai, bi (1 β€ ai < bi β€ n) and ci (1 β€ ci β€ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i β j, (ai, bi, ci) β (aj, bj, cj).
The next line contains a integer β q (1 β€ q β€ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers β ui and vi (1 β€ ui, vi β€ n). It is guaranteed that ui β vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
def build_graph():
line1 = input().strip().split()
n = int(line1[0])
m = int(line1[1])
graph = {}
for _ in range(m):
line = input().strip().split()
u = int(line[0])
v = int(line[1])
c = int(line[2])
if c not in graph:
graph[c] = {j: [] for j in range(1, n+1)}
graph[c][u].append(v)
graph[c][v].append(u)
return graph
parent_history = {}
def no_of_paths(u, v, graph):
x = 0
for c in graph:
if c in parent_history:
if v in parent_history[c]:
parent = parent_history[c]
if u in parent:
x += 1
elif u in parent_history[c]:
parent = parent_history[c]
if v in parent:
x += 1
else:
parent = {}
parent = dfs_visit(v, graph[c], parent)
if len(parent_history[c]) < len(parent):
parent_history[c] = parent
else:
parent = {}
parent = dfs_visit(v, graph[c], parent)
parent_history[c] = parent
if u in parent:
x += 1
return x
def dfs_visit(i, adj_list, parent):
for j in adj_list[i]:
if j not in parent:
parent[j] = i
dfs_visit(j, adj_list, parent)
return parent
if __name__ == "__main__":
graph = build_graph()
for _ in range(int(input())):
line = input().strip().split()
print(no_of_paths(int(line[0]), int(line[1]), graph))
``` | instruction | 0 | 7,073 | 13 | 14,146 |
No | output | 1 | 7,073 | 13 | 14,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid. | instruction | 0 | 7,143 | 13 | 14,286 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
from collections import deque
# ver si hay un camino que llega a el a partir
# de su padre entonces hay un ciclo
def Padre(x, padre):
while x != padre[x]:
x = padre[x]
return x
def DFS(x, color, padre, ciclos, adyacentes, raiz):
color[x] = 1 # nodo gris
for y in adyacentes[x]:
# el adyacente es blanco
if color[y] == 0:
DFS(y, color, padre, ciclos, adyacentes, raiz)
padre[y] = x
elif color[y] == 2:
padre[y] = x
# ese adyacente es gris entonces <u,v> rista de retroceso
else:
if y == x and not raiz:
raiz = x
else:
ciclos.append([x, y])
color[x] = 2 # nodo negro
def Solucion():
n = int(input())
A = list(map(lambda x: int(x)-1, input().split()))
padre = [x for x in range(0, n)]
ciclosC = 0
ciclos = deque([])
root = []
# ir haciendo Merge a cada arista
for i in range(0, n):
p = Padre(A[i], padre)
# Si dicha arista perticipa en un ciclo
if p == i:
# Si es un ciclo del tipo raiz y no hay raiz
if not root and (i == A[i]):
root = [i, A[i]]
else:
ciclos.append([i, A[i]])
ciclosC += 1
# Si no hay ciclo
else:
padre[i] = A[i]
print(str(ciclosC))
# si existe al menos un ciclo diferente d raiz
if ciclosC:
i = 0
# si no hay raiz el primer ciclo lo hago raiz
if not root:
root = ciclos.popleft()
i = 1
# los restantes ciclos hago que su padre sea la raiz
while ciclos:
ciclo = ciclos.popleft()
padre[ciclo[0]] = root[0]
PC = [x + 1 for x in padre]
print(*PC, sep=" ")
Solucion()
# Casos de prueba:
# 4
# 2 3 3 4
# respuesta
# 1
# 2 3 3 3
# 5
# 3 2 2 5 3
# respuesta
# 0
# 3 2 2 5 3
# 8
# 2 3 5 4 1 6 6 7
# respuesta
# 2
# 2 3 5 4 1 4 6 7
# 200000
# hacer con el generador
``` | output | 1 | 7,143 | 13 | 14,287 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid. | instruction | 0 | 7,144 | 13 | 14,288 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
from collections import deque
# Para revisar la correctitud pueden probar el codigo en el codeforce que va a dar accepted
# ver si hay un camino que llega a el a partir
# de su padre entonces hay un ciclo
def Padre(x, padre):
while x != padre[x]:
x = padre[x]
return x
def FixATree():
n = int(input())
A = list(map(lambda x: int(x)-1, input().split()))
padre = [x for x in range(0, n)]
ciclosC = 0
ciclos = deque([])
root = []
# ir haciendo Merge a cada arista
for i in range(0, n):
p = Padre(A[i], padre)
# Si dicha arista perticipa en un ciclo
if p == i:
# Si es un ciclo del tipo raiz y no hay raiz
if not root and (i == A[i]):
root = [i, A[i]]
else:
ciclos.append([i, A[i]])
ciclosC += 1
# Si no hay ciclo
else:
padre[i] = A[i]
print(str(ciclosC))
# si existe al menos un ciclo diferente d raiz
if ciclosC:
i = 0
# si no hay raiz el primer ciclo lo hago raiz
if not root:
root = ciclos.popleft()
i = 1
# los restantes ciclos hago que su padre sea la raiz
while ciclos:
ciclo = ciclos.popleft()
padre[ciclo[0]] = root[0]
PC = [x + 1 for x in padre]
print(*PC, sep=" ")
FixATree()
# Casos de prueba:
# 4
# 2 3 3 4
# respuesta
# 1
# 2 3 3 3
# 5
# 3 2 2 5 3
# respuesta
# 0
# 3 2 2 5 3
# 8
# 2 3 5 4 1 6 6 7
# respuesta
# 2
# 2 3 5 4 1 4 6 7
# El codigo da accepted en el codeforce por lo que los casos de prueba que emplee son los que ahi estan
``` | output | 1 | 7,144 | 13 | 14,289 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid. | instruction | 0 | 7,145 | 13 | 14,290 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
tree_size = int(input())
parents = [int(x)-1 for x in input().split(' ')]
num_changes = 0
root = tree_size
for node, parent in enumerate(parents):
if parent == node:
root = node
break
visited = set()
finished = set()
visited.add(root)
finished.add(root)
stack = []
fringe = []
for node in range(len(parents)):
if node not in visited:
fringe.append(node)
while fringe:
cur = fringe.pop()
visited.add(cur)
stack.append(cur)
if parents[cur] not in finished:
if parents[cur] in visited:
parents[cur] = root
num_changes += 1
else:
fringe.append(parents[cur])
while stack:
finished.add(stack.pop())
if root == tree_size:
new_root = None
for node, parent in enumerate(parents):
if parent == root:
if new_root is None:
new_root = node
parents[node] = new_root
for i in range(len(parents)):
parents[i] += 1
print(num_changes)
print(*parents)
``` | output | 1 | 7,145 | 13 | 14,291 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid. | instruction | 0 | 7,146 | 13 | 14,292 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split(' ')))
root=-1
for i,a in enumerate(arr) :
if i == a-1 :
root = i
break
v = [False]*len(arr)
if root>-1 :
v[root]=True
ans = 0
for i,a in enumerate(arr) :
if v[i] :
continue
v[i]= True
l=[i]
a-=1
while not v[a] :
l.append(a)
v[a]=True
a=arr[a]-1
if a in l: #new cycle
if root==-1:
arr[a]=a+1
root=a
ans+=1
else :
arr[a]=root+1
ans+=1
print(ans)
print(' '.join(map(str,arr)))
``` | output | 1 | 7,146 | 13 | 14,293 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid. | instruction | 0 | 7,147 | 13 | 14,294 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
# Why do we fall ? So we can learn to pick ourselves up.
root = -1
def find(i,time):
parent[i] = time
while not parent[aa[i]]:
i = aa[i]
parent[i] = time
# print(parent,"in",i)
if parent[aa[i]] == time:
global root
if root == -1:
root = i
if aa[i] != root:
aa[i] = root
global ans
ans += 1
n = int(input())
aa = [0]+[int(i) for i in input().split()]
parent = [0]*(n+1)
ans = 0
time = 0
for i in range(1,n+1):
if aa[i] == i:
root = i
break
for i in range(1,n+1):
if not parent[i]:
# print(i,"pp")
time += 1
find(i,time)
# print(parent)
print(ans)
print(*aa[1:])
``` | output | 1 | 7,147 | 13 | 14,295 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid. | instruction | 0 | 7,148 | 13 | 14,296 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
# from debug import debug
import sys; input = sys.stdin.readline
n = int(input())
lis = [0, *map(int , input().split())]
v = [0]*(n+1)
cycles = set()
roots = set()
for i in range(1, n+1):
if v[i] == 0:
node = i
while v[node] == 0:
v[node] = 1
node = lis[node]
if v[node] == 2: continue
start = node
ignore = 0
l = 1
while lis[node] != start:
if v[node] == 2: ignore = 1; break
v[node] = 2
node = lis[node]
l+=1
if ignore: continue
v[node] = 2
if l == 1: roots.add(node)
else: cycles.add(node)
ans = 0
if roots:
base = roots.pop()
for i in roots: lis[i] = base; ans+=1
for i in cycles: lis[i] = base; ans+=1
elif cycles:
base = cycles.pop()
cycles.add(base)
for i in roots: lis[i] = base; ans+=1
for i in cycles: lis[i] = base; ans+=1
print(ans)
print(*lis[1:])
``` | output | 1 | 7,148 | 13 | 14,297 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid. | instruction | 0 | 7,149 | 13 | 14,298 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
# [https://codeforces.com/contest/698/submission/42129034]
input()
A = list(map(int, input().split(' ')))
root = -1
for i,a in enumerate(A) :
if i == a-1 :
root = i
break
v = [False]*len(A)
if root>-1 :
v[root]=True
changed = 0
for i,a in enumerate(A) :
if v[i] :
continue
v[i]= True
l=[i]
a-=1
while not v[a] :
l.append(a)
v[a]=True
a=A[a]-1
if a in l:
if root==-1:
A[a]=a+1
root=a
changed+=1
else :
A[a]=root+1
changed+=1
print(changed)
print(' '.join(map(str,A)))
``` | output | 1 | 7,149 | 13 | 14,299 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid. | instruction | 0 | 7,150 | 13 | 14,300 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
input()
A = list(map(int, input().split(' ')))
root = -1
for i,a in enumerate(A) :
if i == a-1 :
root = i
break
v = [False]*len(A)
if root>-1 :
v[root]=True
changed = 0
for i,a in enumerate(A) :
if v[i] :
continue
v[i]= True
l=[i]
a-=1
while not v[a] :
l.append(a)
v[a]=True
a=A[a]-1
if a in l:
if root==-1:
A[a]=a+1
root=a
changed+=1
else :
A[a]=root+1
changed+=1
print(changed)
print(' '.join(map(str,A)))
# Made By Mostafa_Khaled
``` | output | 1 | 7,150 | 13 | 14,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
par=[]
for i in range(n):
if a[i]==i+1:
par.append(i)
v=[False for i in range(n)]
for i in par:
v[i]=True
ccl=[]
for i in range(n):
if v[i]:continue
s=[i]
v[i]=True
p=set(s)
t=True
while s and t:
x=s.pop()
j=a[x]-1
if j in p:
ccl.append(j)
t=False
else:
s.append(j)
p.add(j)
if v[j]:t=False
else:v[j]=True
if len(par)==0:
print(len(ccl))
c=ccl[0]
a[c]=c+1
for i in range(1,len(ccl)):
a[ccl[i]]=c+1
print(*a)
else:
print(len(ccl)+len(par)-1)
c=par[0]
for i in range(1,len(par)):
a[par[i]]=c+1
for i in range(len(ccl)):
a[ccl[i]]=c+1
print(*a)
``` | instruction | 0 | 7,151 | 13 | 14,302 |
Yes | output | 1 | 7,151 | 13 | 14,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
from collections import defaultdict
from sys import stdin,setrecursionlimit
setrecursionlimit(10**6)
import threading
def f(a):
n=len(a)
a=list(map(lambda s:s-1,a))
root=None
for i in range(len(a)):
if a[i]==i:
root=i
vis=[0]*(n)
traitors=[]
for i in range(0,n):
cycle=-1
cur=i
move=set()
while vis[cur]==0:
vis[cur]=1
move.add(cur)
if a[cur] in move:
cycle=cur
cur=a[cur]
if cycle!=-1:
traitors.append(cycle)
ans=len(traitors)-1
if root==None:
a[traitors[0]]=traitors[0]
root=traitors[0]
ans+=1
for i in traitors:
if i!=root:
a[i]=root
print(ans)
a=list(map(lambda s:s+1,a))
return a
n=input()
a=list(map(int,input().strip().split()))
print(*f(a))
``` | instruction | 0 | 7,152 | 13 | 14,304 |
Yes | output | 1 | 7,152 | 13 | 14,305 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
tree_size = int(input())
parents = [int(x)-1 for x in input().split(' ')]
num_changes = 0
root = None
for node, parent in enumerate(parents):
if parent == node:
root = node
if not root:
root = tree_size
num_changes += 1
finished = set()
visited = set()
visited.add(root)
finished.add(root)
def visit(node):
global num_changes
visited.add(node)
if parents[node] not in finished:
if parents[node] in visited:
parents[node] = root
num_changes += 1
else:
visit(parents[node])
finished.add(node)
for node in range(tree_size):
if node not in visited:
visit(node)
new_root = None
for node, parent in enumerate(parents):
if parent == tree_size:
if not new_root:
new_root = node
parents[node] = new_root
for i in range(tree_size):
parents[i] += 1
print(num_changes)
print(*parents)
``` | instruction | 0 | 7,153 | 13 | 14,306 |
No | output | 1 | 7,153 | 13 | 14,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
from collections import defaultdict
from sys import stdin,setrecursionlimit
setrecursionlimit(10**6)
import threading
def dfs(node,g,vis):
vis[node]=1
for i in g[node]:
if vis[i]==0:
dfs(i,g,vis)
def dfs2(node,g,vis,path):
path.append(node)
vis[node]=1
for i in g[node]:
if vis[i]==0:
dfs2(i,g,vis,path)
def main():
def f(a):
n=len(a)
g=defaultdict(list)
good=None
for i in range(0,len(a)):
if a[i]==i+1 and good==None:
# print(a[i],i,"lodu")
good=a[i]
g[i+1].append(a[i])
g[a[i]].append(i+1)
cnt=0
if good==None:
a[0]=1
good=1
cnt+=1
vis=[0]*(len(a)+1)
dfs(good,g,vis)
for i in range(1,n+1):
if i==good-1:
continue
if vis[i]==0:
pah=[]
dfs2(i,g,vis,pah)
if pah:
cnt+=1
a[i-1]=good
print(cnt)
print(*a)
a=input()
lst=list(map(int,input().strip().split()))
f(lst)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()
``` | instruction | 0 | 7,154 | 13 | 14,308 |
No | output | 1 | 7,154 | 13 | 14,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
tree_size = int(input())
parents = [int(x)-1 for x in input().split(' ')]
num_changes = 0
root = None
for node, parent in enumerate(parents):
if parent == node:
root = node
break
if not root:
root = tree_size
finished = set()
visited = set()
visited.add(root)
finished.add(root)
def visit(node):
global num_changes
visited.add(node)
if parents[node] not in finished:
if parents[node] in visited:
parents[node] = root
num_changes += 1
else:
visit(parents[node])
finished.add(node)
for node in range(tree_size):
if node not in visited:
visit(node)
new_root = None
for node, parent in enumerate(parents):
if parent == tree_size:
if not new_root:
new_root = node
parents[node] = new_root
for i in range(tree_size):
parents[i] += 1
print(num_changes)
print(*parents)
``` | instruction | 0 | 7,155 | 13 | 14,310 |
No | output | 1 | 7,155 | 13 | 14,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 β€ n β€ 200 000) β the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
from collections import defaultdict
from sys import stdin,setrecursionlimit
setrecursionlimit(10**6)
import threading
def dfs(node,g,vis):
vis[node]=1
for i in g[node]:
if vis[i]==0:
dfs(i,g,vis)
def dfs2(node,g,vis,path):
path.append(node)
vis[node]=1
for i in g[node]:
if vis[i]==0:
dfs2(i,g,vis,path)
def main():
def f(a):
n=len(a)
g=defaultdict(list)
good=None
for i in range(0,len(a)):
if a[i]==i+1 and good==None:
# print(a[i],i,"lodu")
good=a[i]
g[i+1].append(a[i])
g[a[i]].append(i+1)
cnt=0
# print(g)
if good==None:
t=max(g.keys(),key=lambda s:len(g[s]))
g[t].remove(a[t-1])
g[a[t-1]].remove(t)
g[t].append(t)
a[t-1]=t
good=t
cnt+=1
vis=[0]*(len(a)+1)
dfs(good,g,vis)
# print(vis)
for i in range(1,n+1):
if vis[i]==0:
pah=[]
dfs2(i,g,vis,pah)
if pah:
cnt+=1
a[i-1]=good
ind=[]
for i in range(0,len(a)):
if a[i]==i+1:
ind+=[a[i],i]
if len(ind)>2:
print(*ind,sep="+")
else:
print(cnt)
print(*a)
a=input()
lst=list(map(int,input().strip().split()))
f(lst)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()
``` | instruction | 0 | 7,156 | 13 | 14,312 |
No | output | 1 | 7,156 | 13 | 14,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Timofey has a big tree β an undirected connected graph with n vertices and no simple cycles. He likes to walk along it. His tree is flat so when he walks along it he sees it entirely. Quite naturally, when he stands on a vertex, he sees the tree as a rooted tree with the root in this vertex.
Timofey assumes that the more non-isomorphic subtrees are there in the tree, the more beautiful the tree is. A subtree of a vertex is a subgraph containing this vertex and all its descendants. You should tell Timofey the vertex in which he should stand to see the most beautiful rooted tree.
Subtrees of vertices u and v are isomorphic if the number of children of u equals the number of children of v, and their children can be arranged in such a way that the subtree of the first son of u is isomorphic to the subtree of the first son of v, the subtree of the second son of u is isomorphic to the subtree of the second son of v, and so on. In particular, subtrees consisting of single vertex are isomorphic to each other.
Input
First line contains single integer n (1 β€ n β€ 105) β number of vertices in the tree.
Each of the next n - 1 lines contains two integers ui and vi (1 β€ ui, vi β€ 105, ui β vi), denoting the vertices the i-th edge connects.
It is guaranteed that the given graph is a tree.
Output
Print single integer β the index of the vertex in which Timofey should stand. If there are many answers, you can print any of them.
Examples
Input
3
1 2
2 3
Output
1
Input
7
1 2
4 2
2 3
5 6
6 7
3 7
Output
1
Input
10
1 7
1 8
9 4
5 1
9 2
3 5
10 6
10 9
5 10
Output
2
Note
In the first example we can stand in the vertex 1 or in the vertex 3 so that every subtree is non-isomorphic. If we stand in the vertex 2, then subtrees of vertices 1 and 3 are isomorphic.
In the second example, if we stand in the vertex 1, then only subtrees of vertices 4 and 5 are isomorphic.
In the third example, if we stand in the vertex 1, then subtrees of vertices 2, 3, 4, 6, 7 and 8 are isomorphic. If we stand in the vertex 2, than only subtrees of vertices 3, 4, 6, 7 and 8 are isomorphic. If we stand in the vertex 5, then subtrees of vertices 2, 3, 4, 6, 7 and 8 are isomorphic, and subtrees of vertices 1 and 9 are isomorphic as well:
1 9
/\ /\
7 8 4 2
Submitted Solution:
```
from random import randint
mod1 = 10**9 + 7
def hashing_dfs(v,deep, adj_list,rfd,_hash):
if len(adj_list[v]) == 0:
return 0
h = 1
set_hsh = []
for u in adj_list[v]:
if deep[u] == -1:
deep[u] = deep[v] + 1
h = max( h , hashing_dfs(u,deep,adj_list,rfd,_hash))
set_hsh.append(_hash[u])
if rfd[h] == -1:
rfd[h] = randint(1,mod1)
for value in set_hsh:
_hash[v] = (_hash[v] * (rfd[h] + value)) % mod1
return h
def min_isomorphic_tree(n,adj_list):
randix = 0
mic = n # min isomorphic counter
for v in range(1,n + 1):
_hash, deep, rfd = [1] * (n + 1), [-1] * (n + 1), [-1] * n
deep[v] = 0
hashing_dfs(v,deep,adj_list,rfd,_hash)
_hash.sort()
count = 0
for i in range( 1,n ):
count = count + (_hash[i] == _hash[i + 1])
if mic > count + (count != 0):
mic = count + (count != 0)
randix = v
print(randix)
``` | instruction | 0 | 7,173 | 13 | 14,346 |
No | output | 1 | 7,173 | 13 | 14,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a connected undirected graph with n vertices and m edges. The vertices are enumerated from 1 to n.
You are given n integers c1, c2, ..., cn, each of them is between - n and n, inclusive. It is also guaranteed that the parity of cv equals the parity of degree of vertex v. The degree of a vertex is the number of edges connected to it.
You are to write a weight between - 2Β·n2 and 2Β·n2 (inclusive) on each edge in such a way, that for each vertex v the sum of weights on edges connected to this vertex is equal to cv, or determine that this is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 105, n - 1 β€ m β€ 105) β the number of vertices and the number of edges.
The next line contains n integers c1, c2, ..., cn ( - n β€ ci β€ n), where ci is the required sum of weights of edges connected to vertex i. It is guaranteed that the parity of ci equals the parity of degree of vertex i.
The next m lines describe edges of the graph. The i-th of these lines contains two integers ai and bi (1 β€ ai, bi β€ n; ai β bi), meaning that the i-th edge connects vertices ai and bi.
It is guaranteed that the given graph is connected and does not contain loops and multiple edges.
Output
If there is no solution, print "NO".
Otherwise print "YES" and then m lines, the i-th of them is the weight of the i-th edge wi ( - 2Β·n2 β€ wi β€ 2Β·n2).
Examples
Input
3 3
2 2 2
1 2
2 3
1 3
Output
YES
1
1
1
Input
4 3
-1 0 2 1
1 2
2 3
3 4
Output
YES
-1
1
1
Input
6 6
3 5 5 5 1 5
1 4
3 2
4 3
4 5
3 5
5 6
Output
YES
3
5
3
-1
-3
5
Input
4 4
4 4 2 4
1 2
2 3
3 4
4 1
Output
NO | instruction | 0 | 7,232 | 13 | 14,464 |
Tags: constructive algorithms, dfs and similar, graphs
Correct Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=0):
self.BIT = [0]*(n+1)
self.num = n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.size = n
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
if r==self.size:
r = self.num
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
n,m = mi()
c = li()
edge = [[] for i in range(n)]
for i in range(m):
u,v = mi()
edge[u-1].append((v-1,i))
edge[v-1].append((u-1,i))
parent = [(-1,-1) for v in range(n)]
tree_edge = [[] for v in range(n)]
depth = [0 for v in range(n)]
special = None
stack = [0]
cnt = [0 for v in range(n)]
while stack:
v = stack[-1]
if cnt[v]==len(edge[v]):
stack.pop()
else:
nv,idx = edge[v][cnt[v]]
cnt[v] += 1
if nv==0 or parent[nv]!=(-1,-1):
if depth[nv] < depth[v] and (depth[v]-depth[nv])%2==0 and not special:
special = (v,nv,idx)
else:
parent[nv] = (v,idx)
depth[nv] = depth[v] + 1
tree_edge[v].append((nv,idx))
stack.append(nv)
if not special:
even = 0
odd = 0
for v in range(n):
if depth[v]&1:
odd += c[v]
else:
even += c[v]
if odd!=even:
print("NO")
else:
print("YES")
deq = deque([0])
topo = []
while deq:
v = deq.popleft()
topo.append(v)
for nv,idx in tree_edge[v]:
deq.append(nv)
ans = [0 for i in range(m)]
for v in topo[::-1]:
if v==0:
continue
_,i = parent[v]
ans[i] = c[v]
for nv,idx in tree_edge[v] :
ans[i] -= ans[idx]
print(*ans,sep="\n")
else:
print("YES")
even = 0
odd = 0
for v in range(n):
if depth[v]&1:
odd += c[v]
else:
even += c[v]
ans = [0 for i in range(m)]
v,nv,idx = special
if depth[v]&1:
ans[idx] -= (even-odd)//2
c[v] += (even-odd)//2
c[nv] += (even-odd)//2
else:
ans[idx] -= (odd-even)//2
c[v] += (odd-even)//2
c[nv] += (odd-even)//2
#print(ans)
deq = deque([0])
topo = []
while deq:
v = deq.popleft()
topo.append(v)
for nv,idx in tree_edge[v]:
deq.append(nv)
for v in topo[::-1]:
if v==0:
continue
_,i = parent[v]
ans[i] = c[v]
for nv,idx in tree_edge[v] :
ans[i] -= ans[idx]
print(*ans,sep="\n")
``` | output | 1 | 7,232 | 13 | 14,465 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.