message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0
instruction
0
3,681
13
7,362
Tags: dp, graphs, shortest paths Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [''] * n for i in range(n - 1, -1, -1): x = a[i] for u in range(n): for v in range(n): if matrix[u][v] > matrix[u][x] + matrix[x][v]: matrix[u][v] = matrix[u][x] + matrix[x][v] upper, lower = 0, 0 for u in a[i:]: for v in a[i:]: lower += matrix[u][v] if lower >= 10**9: upper += 1 lower -= 10**9 ans[i] = str(upper * 10**9 + lower) sys.stdout.buffer.write(' '.join(ans).encode('utf-8')) ```
output
1
3,681
13
7,363
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0
instruction
0
3,682
13
7,364
Tags: dp, graphs, shortest paths Correct Solution: ``` #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools import bisect import heapq from array import array def input(): return sys.stdin.readline()[:-1] # sys.setrecursionlimit(1000000) # _INPUT = """4 # 0 57148 51001 13357 # 71125 0 98369 67226 # 49388 90852 0 66291 # 39573 38165 97007 0 # 2 3 1 4 # """ # sys.stdin = io.StringIO(_INPUT) INF = 10**10 N = int(input()) A = [array('i', list(map(int, input().split()))) for _ in range(N)] X = list(map(lambda x: int(x)-1, input().split())) result = [] for k in reversed(range(N)): x = X[k] for i in range(N): for j in range(N): d = A[i][x] + A[x][j] if d < A[i][j]: A[i][j] = d v = 0 upper = 0 for i in X[k:]: for j in X[k:]: v += A[i][j] if v > 10**9: v -= 10**9 upper += 1 result.append(str((10**9) * upper + v)) print(' '.join(reversed(result))) ```
output
1
3,682
13
7,365
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0
instruction
0
3,683
13
7,366
Tags: dp, graphs, shortest paths Correct Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush # from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 from sys import stdin input = stdin.readline def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] try: # sys.setrecursionlimit(int(pow(10,6))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass from array import array def input(): return sys.stdin.buffer.readline().decode('utf-8') def solve(): n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [''] * n for i in range(n - 1, -1, -1): x = a[i] for u in range(n): for v in range(n): if matrix[u][v] > matrix[u][x] + matrix[x][v]: matrix[u][v] = matrix[u][x] + matrix[x][v] upper, lower = 0, 0 for u in a[i:]: for v in a[i:]: lower += matrix[u][v] if lower >= 10**9: upper += 1 lower -= 10**9 ans[i] = str(upper * 10**9 + lower) sys.stdout.buffer.write(' '.join(ans).encode('utf-8')) solve() endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ```
output
1
3,683
13
7,367
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0
instruction
0
3,684
13
7,368
Tags: dp, graphs, shortest paths Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def solve(): n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [''] * n for i in range(n - 1, -1, -1): x = a[i] for u in range(n): for v in range(n): if matrix[u][v] > matrix[u][x] + matrix[x][v]: matrix[u][v] = matrix[u][x] + matrix[x][v] upper, lower = 0, 0 for u in a[i:]: for v in a[i:]: lower += matrix[u][v] if lower >= 10**9: upper += 1 lower -= 10**9 ans[i] = str(upper * 10**9 + lower) sys.stdout.buffer.write(' '.join(ans).encode('utf-8')) if __name__ == '__main__': solve() ```
output
1
3,684
13
7,369
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0
instruction
0
3,685
13
7,370
Tags: dp, graphs, shortest paths Correct Solution: ``` #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools import bisect import heapq from array import array def input(): return sys.stdin.readline()[:-1] # sys.setrecursionlimit(1000000) # _INPUT = """4 # 0 57148 51001 13357 # 71125 0 98369 67226 # 49388 90852 0 66291 # 39573 38165 97007 0 # 2 3 1 4 # """ # sys.stdin = io.StringIO(_INPUT) INF = 10**10 N = int(input()) A = [array('i', list(map(int, input().split()))) for _ in range(N)] X = list(map(lambda x: int(x)-1, input().split())) result = [] for k in reversed(range(N)): x = X[k] for i in range(N): for j in range(N): d = A[i][x] + A[x][j] if d < A[i][j]: A[i][j] = d v = 0 overflow = 0 for i in X[k:]: for j in X[k:]: v += A[i][j] if v > 10**9: v -= 10**9 overflow += 1 result.append(str(v + (10**9) * overflow)) print(' '.join(reversed(result))) ```
output
1
3,685
13
7,371
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0
instruction
0
3,686
13
7,372
Tags: dp, graphs, shortest paths Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] aa = tuple(map(lambda x: int(x) - 1, input().split())) ans = [''] * n for i in range(n-1, -1, -1): x = aa[i] for a in range(n): for b in range(n): if matrix[a][b] > matrix[a][x] + matrix[x][b]: matrix[a][b] = matrix[a][x] + matrix[x][b] lower, higher = 0, 0 for a in aa[i:]: for b in aa[i:]: lower += matrix[a][b] if lower > 10**9: higher += 1 lower -= 10**9 ans[i] = str(10**9 * higher + lower) print(' '.join(ans)) ```
output
1
3,686
13
7,373
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Submitted Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) edges = [tuple(map(int, input().split())) for _ in range(n)] matrix = [[10**9] * n for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [0] * n for i in range(n - 1, -1, -1): for j in range(n): matrix[a[i]][j] = min(matrix[a[i]][j], edges[a[i]][j]) matrix[j][a[i]] = min(matrix[j][a[i]], edges[j][a[i]]) for u in a[i + 1:]: for v in a[i + 1:]: matrix[u][v] = min(matrix[u][v], matrix[u][a[i]] + matrix[a[i]][v]) for u in a[i:]: for v in a[i:]: ans[i] += matrix[u][v] print(*ans) ```
instruction
0
3,687
13
7,374
No
output
1
3,687
13
7,375
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Submitted Solution: ``` #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools import bisect import heapq def input(): return sys.stdin.readline()[:-1] # sys.setrecursionlimit(1000000) # _INPUT = """4 # 0 3 1 1 # 6 0 400 1 # 2 4 0 1 # 1 1 1 0 # 4 1 2 3 # """ # sys.stdin = io.StringIO(_INPUT) INF = 10**10 N = int(input()) A = [list(map(int, input().split())) for _ in range(N)] X = list(map(lambda x: int(x)-1, input().split())) dist = [[INF] * N for _ in range(N)] for i in range(N): dist[i][i] = 0 result = [] Allowed = [] for x in reversed(X): Allowed.append(x) for i in Allowed: dist[i][x] = A[i][x] dist[x][i] = A[x][i] v = 0 for i in Allowed: for j in Allowed: dist[i][j] = min(dist[i][j], dist[i][x] + dist[x][j]) v += dist[i][j] result.append(v) print(*reversed(result)) ```
instruction
0
3,688
13
7,376
No
output
1
3,688
13
7,377
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Submitted Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) matrix = [list(map(int, input().split())) for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [0] * n for i in range(n - 1, -1, -1): for u in a[i + 1:]: for v in a[i + 1:]: matrix[a[i]][u] = min(matrix[a[i]][u], matrix[a[i]][v] + matrix[v][u]) matrix[u][a[i]] = min(matrix[u][a[i]], matrix[u][v] + matrix[v][a[i]]) matrix[u][v] = min(matrix[u][v], matrix[u][a[i]] + matrix[a[i]][v]) for u in a[i:]: for v in a[i:]: ans[i] += matrix[u][v] print(*ans) ```
instruction
0
3,689
13
7,378
No
output
1
3,689
13
7,379
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2
instruction
0
3,690
13
7,380
Tags: data structures, divide and conquer, trees Correct Solution: ``` class CentroidDecomposition(): def __init__(self, g): self.g = g self.n = len(g) self.parent = [-1]*self.n self.size = [1]*self.n self.cdparent = [-1]*self.n self.cddepth = [0]*self.n self.cdorder = [-1]*self.n self.cdused = [0]*self.n cnt = 0 stack = [0] while stack: v = stack.pop() p = self.cdparent[v] c = self.get_centroid(v) self.cdused[c] = True self.cdparent[c] = p self.cddepth[c] = self.cddepth[v] self.cdorder[c] = cnt cnt += 1 for u in self.g[c]: if self.cdused[u]: continue self.cdparent[u] = c self.cddepth[u] = self.cddepth[c]+1 stack.append(u) def get_centroid(self, root): self.parent[root] = -1 self.size[root] = 1 stack = [root] order = [] while stack: v = stack.pop() order.append(v) for u in g[v]: if self.parent[v] == u or self.cdused[u]: continue self.size[u] = 1 self.parent[u] = v stack.append(u) if len(order) <= 2: return root for v in reversed(order): if self.parent[v] == -1: continue self.size[self.parent[v]] += self.size[v] total = self.size[root] v = root while True: for u in self.g[v]: if self.parent[v] == u or self.cdused[u]: continue if self.size[u] > total//2: v = u break else: return v class HLD: def __init__(self, g): self.g = g self.n = len(g) self.parent = [-1]*self.n self.size = [1]*self.n self.head = [0]*self.n self.preorder = [0]*self.n self.k = 0 self.depth = [0]*self.n for v in range(self.n): if self.parent[v] == -1: self.dfs_pre(v) self.dfs_hld(v) def dfs_pre(self, v): g = self.g stack = [v] order = [v] while stack: v = stack.pop() for u in g[v]: if self.parent[v] == u: continue self.parent[u] = v self.depth[u] = self.depth[v]+1 stack.append(u) order.append(u) # 隣接リストの左端: heavyな頂点への辺 # 隣接リストの右端: 親への辺 while order: v = order.pop() child_v = g[v] if len(child_v) and child_v[0] == self.parent[v]: child_v[0], child_v[-1] = child_v[-1], child_v[0] for i, u in enumerate(child_v): if u == self.parent[v]: continue self.size[v] += self.size[u] if self.size[u] > self.size[child_v[0]]: child_v[i], child_v[0] = child_v[0], child_v[i] def dfs_hld(self, v): stack = [v] while stack: v = stack.pop() self.preorder[v] = self.k self.k += 1 top = self.g[v][0] # 隣接リストを逆順に見ていく(親 > lightな頂点への辺 > heavyな頂点 (top)) # 連結成分が連続するようにならべる for u in reversed(self.g[v]): if u == self.parent[v]: continue if u == top: self.head[u] = self.head[v] else: self.head[u] = u stack.append(u) def for_each(self, u, v): # [u, v]上の頂点集合の区間を列挙 while True: if self.preorder[u] > self.preorder[v]: u, v = v, u l = max(self.preorder[self.head[v]], self.preorder[u]) r = self.preorder[v] yield l, r # [l, r] if self.head[u] != self.head[v]: v = self.parent[self.head[v]] else: return def for_each_edge(self, u, v): # [u, v]上の辺集合の区間列挙 # 辺の情報は子の頂点に while True: if self.preorder[u] > self.preorder[v]: u, v = v, u if self.head[u] != self.head[v]: yield self.preorder[self.head[v]], self.preorder[v] v = self.parent[self.head[v]] else: if u != v: yield self.preorder[u]+1, self.preorder[v] break def subtree(self, v): # 頂点vの部分木の頂点集合の区間 [l, r) l = self.preorder[v] r = self.preorder[v]+self.size[v] return l, r def lca(self, u, v): # 頂点u, vのLCA while True: if self.preorder[u] > self.preorder[v]: u, v = v, u if self.head[u] == self.head[v]: return u v = self.parent[self.head[v]] import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, m = map(int, input().split()) g = [[] for i in range(n)] for i in range(n-1): a, b = map(int, input().split()) a, b = a-1, b-1 g[a].append(b) g[b].append(a) cd = CentroidDecomposition(g) hld = HLD(g) #print(cd.cdparent) min_dist = [0]*n for i in range(n): min_dist[i] = hld.depth[i] #print(min_dist) for i in range(m): t, v = map(int, input().split()) v -= 1 if t == 1: cur = v while cur != -1: l = hld.lca(cur, v) d = hld.depth[cur]+hld.depth[v]-2*hld.depth[l] min_dist[cur] = min(min_dist[cur], d) cur = cd.cdparent[cur] else: ans = n cur = v while cur != -1: l = hld.lca(cur, v) d = hld.depth[cur]+hld.depth[v]-2*hld.depth[l] ans = min(ans, d+min_dist[cur]) cur = cd.cdparent[cur] print(ans) ```
output
1
3,690
13
7,381
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2
instruction
0
3,691
13
7,382
Tags: data structures, divide and conquer, trees Correct Solution: ``` n,m=map(int,input().split()) tr=[set() for i in range(n+1)] trr=[[] for i in range(n+1)] for _ in range(n-1): a,b=map(int,input().split()) trr[a].append(b);trr[b].append(a) tr[a].add(b);tr[b].add(a) euler=[] disc=[-1 for i in range(n+1)] hei=[-1 for i in range(n+1)] def eulerr(): q=[1] pa={1:-1} hei[1]=0 while q: x=q.pop() if disc[x]==-1:disc[x]=len(euler) euler.append(x) if len(trr[x])==0: if pa[x]!=-1:q.append(pa[x]) elif trr[x][-1]==pa[x]: trr[x].pop(-1) q.append(x) euler.pop() else: y=trr[x].pop(-1) pa[y]=x hei[y]=hei[x]+1 q.append(y) eulerr() st=[-1 for i in range(2*len(euler))] for i in range(len(euler)): st[i+len(euler)]=euler[i] for i in range(len(euler)-1,0,-1): if disc[st[i<<1]]<disc[st[i<<1|1]]: st[i]=st[i<<1] else: st[i]=st[i<<1|1] def dist(a,b): i=disc[a];j=disc[b] if i>j:i,j=j,i i+=len(euler);j+=len(euler)+1 ans=st[i] while i<j: if i&1: if disc[st[i]]<disc[ans]:ans=st[i] i+=1 if j&1: j-=1 if disc[st[j]]<disc[ans]:ans=st[j] i>>=1 j>>=1 return(hei[a]+hei[b]-2*hei[ans]) size=[0 for i in range(n+1)] def siz(i): pa={i:-1} q=[i] w=[] while q: x=q.pop() w.append(x) size[x]=1 for y in tr[x]: if y==pa[x]:continue pa[y]=x q.append(y) for j in range(len(w)-1,0,-1): x=w[j] size[pa[x]]+=size[x] return(size[i]) def centroid(i,nn): pa={i:-1} q=[i] while q: x=q.pop() for y in tr[x]: if y!=pa[x] and size[y]>nn/2: q.append(y) pa[y]=x break else:return(x) ct=[-1 for i in range(n+1)] def build(): q=[1] while q: x=q.pop() nn=siz(x) j=centroid(x,nn) ct[j]=ct[x] for y in tr[j]: tr[y].discard(j) ct[y]=j q.append(y) tr[j].clear() build() ps=[float("INF") for i in range(n+1)] ps[1]=0 x=1 while ct[x]!=-1: ps[ct[x]]=min(ct[x],dist(1,ct[x])) x=ct[x] for _ in range(m): t,x=map(int,input().split()) if t==1: v=x while x!=-1: ps[x]=min(ps[x],dist(v,x)) x=ct[x] else: ans=ps[x] v=x while x!=-1: ans=min(ans,ps[x]+dist(v,x)) x=ct[x] print(ans) ```
output
1
3,691
13
7,383
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2
instruction
0
3,692
13
7,384
Tags: data structures, divide and conquer, trees Correct Solution: ``` class Tree(): def __init__(self, n): self.n = n self.tree = [[] for _ in range(n)] self.root = None def add_edge(self, u, v): self.tree[u].append(v) self.tree[v].append(u) def set_root(self, r=0): self.root = r self.par = [None] * self.n self.dep = [0] * self.n self.height = [0] * self.n self.size = [1] * self.n self.ord = [r] stack = [r] while stack: v = stack.pop() for adj in self.tree[v]: if self.par[v] == adj: continue self.par[adj] = v self.dep[adj] = self.dep[v] + 1 self.ord.append(adj) stack.append(adj) for v in self.ord[1:][::-1]: self.size[self.par[v]] += self.size[v] self.height[self.par[v]] = max(self.height[self.par[v]], self.height[v] + 1) def rerooting(self, op, e, merge, id): if self.root is None: self.set_root() dp = [e] * self.n lt = [id] * self.n rt = [id] * self.n inv = [id] * self.n for v in self.ord[::-1]: tl = tr = e for adj in self.tree[v]: if self.par[v] == adj: continue lt[adj] = tl tl = op(tl, dp[adj]) for adj in self.tree[v][::-1]: if self.par[v] == adj: continue rt[adj] = tr tr = op(tr, dp[adj]) dp[v] = tr for v in self.ord: if v == self.root: continue p = self.par[v] inv[v] = op(merge(lt[v], rt[v]), inv[p]) dp[v] = op(dp[v], inv[v]) return dp def euler_tour(self): if self.root is None: self.set_root() self.tour = [] self.etin = [None for _ in range(self.n)] self.etout = [None for _ in range(self.n)] used = [0 for _ in range(self.n)] used[self.root] = 1 stack = [self.root] while stack: v = stack.pop() if v >= 0: self.tour.append(v) stack.append(~v) if self.etin[v] is None: self.etin[v] = len(self.tour) - 1 for adj in self.tree[v]: if used[adj]: continue used[adj] = 1 stack.append(adj) else: self.etout[~v] = len(self.tour) if ~v != self.root: self.tour.append(self.par[~v]) def heavylight_decomposition(self): if self.root is None: self.set_root() self.hldid = [None] * self.n self.hldtop = [None] * self.n self.hldtop[self.root] = self.root self.hldnxt = [None] * self.n self.hldrev = [None] * self.n stack = [self.root] cnt = 0 while stack: v = stack.pop() self.hldid[v] = cnt self.hldrev[cnt] = v cnt += 1 maxs = 0 for adj in self.tree[v]: if self.par[v] == adj: continue if maxs < self.size[adj]: maxs = self.size[adj] self.hldnxt[v] = adj for adj in self.tree[v]: if self.par[v] == adj or self.hldnxt[v] == adj: continue self.hldtop[adj] = adj stack.append(adj) if self.hldnxt[v] is not None: self.hldtop[self.hldnxt[v]] = self.hldtop[v] stack.append(self.hldnxt[v]) def lca(self, u, v): while True: if self.hldid[u] > self.hldid[v]: u, v = v, u if self.hldtop[u] != self.hldtop[v]: v = self.par[self.hldtop[v]] else: return u def dist(self, u, v): lca = self.lca(u, v) return self.dep[u] + self.dep[v] - 2 * self.dep[lca] def range_query(self, u, v, edge_query=False): while True: if self.hldid[u] > self.hldid[v]: u, v = v, u if self.hldtop[u] != self.hldtop[v]: yield self.hldid[self.hldtop[v]], self.hldid[v] + 1 v = self.par[self.hldtop[v]] else: yield self.hldid[u] + edge_query, self.hldid[v] + 1 return def subtree_query(self, u): return self.hldid[u], self.hldid[u] + self.size[u] def _get_centroid_(self, r): self._par_[r] = None self._size_[r] = 1 ord = [r] stack = [r] while stack: v = stack.pop() for adj in self.tree[v]: if self._par_[v] == adj or self.cdused[adj]: continue self._size_[adj] = 1 self._par_[adj] = v ord.append(adj) stack.append(adj) if len(ord) <= 2: return r for v in ord[1:][::-1]: self._size_[self._par_[v]] += self._size_[v] sr = self._size_[r] // 2 v = r while True: for adj in self.tree[v]: if self._par_[v] == adj or self.cdused[adj]: continue if self._size_[adj] > sr: v = adj break else: return v def centroid_decomposition(self): self._par_ = [None] * self.n self._size_ = [1] * self.n self.cdpar = [None] * self.n self.cddep = [0] * self.n self.cdord = [None] * self.n self.cdused = [0] * self.n cnt = 0 stack = [0] while stack: v = stack.pop() p = self.cdpar[v] c = self._get_centroid_(v) self.cdused[c] = True self.cdpar[c] = p self.cddep[c] = self.cddep[v] self.cdord[c] = cnt cnt += 1 for adj in self.tree[c]: if self.cdused[adj]: continue self.cdpar[adj] = c self.cddep[adj] = self.cddep[c] + 1 stack.append(adj) def centroid(self): if self.root is None: self.set_root() sr = self.size[self.root] // 2 v = self.root while True: for adj in self.tree[v]: if self.par[v] == adj: continue if self.size[adj] > sr: v = adj break else: return v def diam(self): if self.root is None: self.set_root() u = self.dep.index(max(self.dep)) self.set_root(u) v = self.dep.index(max(self.dep)) return u, v def get_path(self, u, v): if self.root != u: self.set_root(u) path = [] while v != None: path.append(v) v = self.par[v] return path def longest_path_decomposition(self, make_ladder=True): assert self.root is not None self.lpdnxt = [None] * self.n self.lpdtop = [None] * self.n self.lpdtop[self.root] = self.root stack = [self.root] while stack: v = stack.pop() for adj in self.tree[v]: if self.par[v] == adj: continue if self.height[v] == self.height[adj] + 1: self.lpdnxt[v] = adj for adj in self.tree[v]: if self.par[v] == adj or self.lpdnxt[v] == adj: continue self.lpdtop[adj] = adj stack.append(adj) if self.lpdnxt[v] is not None: self.lpdtop[self.lpdnxt[v]] = self.lpdtop[v] stack.append(self.lpdnxt[v]) if make_ladder: self._make_ladder_() def _make_ladder_(self): self.ladder = [[] for _ in range(self.n)] for v in range(self.n): if self.lpdtop[v] != v: continue to = v path = [] while to is not None: path.append(to) to = self.lpdnxt[to] p = self.par[v] self.ladder[v] = path[::-1] for i in range(len(path)): self.ladder[v].append(p) if p is None: break p = self.par[p] def level_ancestor(self, v, k): while v is not None: id = self.height[v] h = self.lpdtop[v] if len(self.ladder[h]) > k + id: return self.ladder[h][k + id] v = self.ladder[h][-1] k -= len(self.ladder[h]) - id - 1 import io, os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, Q = map(int, input().split()) t = Tree(N) for _ in range(N - 1): u, v = map(int, input().split()) t.add_edge(u - 1, v - 1) t.heavylight_decomposition() t.centroid_decomposition() min_dist = [N] * N res = [] def query_1(v): cur = v while cur is not None: min_dist[cur] = min(min_dist[cur], t.dist(cur, v)) cur = t.cdpar[cur] def query_2(v): ret = N cur = v while cur is not None: ret = min(ret, t.dist(cur, v) + min_dist[cur]) cur = t.cdpar[cur] return ret query_1(0) for _ in range(Q): q, v = map(int, input().split()) if q == 1: query_1(v - 1) else: res.append((query_2(v - 1))) print('\n'.join(map(str, res))) ```
output
1
3,692
13
7,385
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2
instruction
0
3,693
13
7,386
Tags: data structures, divide and conquer, trees Correct Solution: ``` class CentroidDecomposition(): def __init__(self, g): self.g = g self.n = len(g) self.parent = [-1]*self.n self.size = [1]*self.n self.cdparent = [-1]*self.n self.cddepth = [0]*self.n self.cdorder = [-1]*self.n self.cdused = [0]*self.n cnt = 0 stack = [0] while stack: v = stack.pop() p = self.cdparent[v] c = self.get_centroid(v) self.cdused[c] = True self.cdparent[c] = p self.cddepth[c] = self.cddepth[v] self.cdorder[c] = cnt cnt += 1 for u in self.g[c]: if self.cdused[u]: continue self.cdparent[u] = c self.cddepth[u] = self.cddepth[c]+1 stack.append(u) def get_centroid(self, root): self.parent[root] = -1 self.size[root] = 1 stack = [root] order = [] while stack: v = stack.pop() order.append(v) for u in g[v]: if self.parent[v] == u or self.cdused[u]: continue self.size[u] = 1 self.parent[u] = v stack.append(u) if len(order) <= 2: return root for v in reversed(order): if self.parent[v] == -1: continue self.size[self.parent[v]] += self.size[v] total = self.size[root] v = root while True: for u in self.g[v]: if self.parent[v] == u or self.cdused[u]: continue if self.size[u] > total//2: v = u break else: return v class SegTree: def __init__(self, init_val, ide_ele, segfunc): self.n = len(init_val) self.num = 2**(self.n-1).bit_length() self.ide_ele = ide_ele self.segfunc = segfunc self.seg = [ide_ele]*2*self.num # set_val for i in range(self.n): self.seg[i+self.num] = init_val[i] # built for i in range(self.num-1, 0, -1): self.seg[i] = self.segfunc(self.seg[2*i], self.seg[2*i+1]) def update(self, k, x): k += self.num self.seg[k] = x while k: k = k >> 1 self.seg[k] = self.segfunc(self.seg[2*k], self.seg[2*k+1]) def query(self, l, r): if r <= l: return self.ide_ele l += self.num r += self.num res = self.ide_ele while l < r: if r & 1: r -= 1 res = self.segfunc(res, self.seg[r]) if l & 1: res = self.segfunc(res, self.seg[l]) l += 1 l = l >> 1 r = r >> 1 return res def segfunc(x, y): if x <= y: return x else: return y ide_ele = 10**18 class LCA: def __init__(self, g, root): # g: adjacency list # root self.n = len(g) self.root = root s = [self.root] self.parent = [-1]*self.n self.child = [[] for _ in range(self.n)] visit = [-1]*self.n visit[self.root] = 0 while s: v = s.pop() for u in g[v]: if visit[u] == -1: self.parent[u] = v self.child[v].append(u) visit[u] = 0 s.append(u) # Euler tour tank = [self.root] self.eulerTour = [] self.left = [0]*self.n self.right = [-1]*self.n self.depth = [-1]*self.n eulerNum = -1 de = -1 while tank: v = tank.pop() if v >= 0: eulerNum += 1 self.eulerTour.append(v) self.left[v] = eulerNum self.right[v] = eulerNum tank.append(~v) de += 1 self.depth[v] = de for u in self.child[v]: tank.append(u) else: de -= 1 if ~v != self.root: self.eulerTour.append(self.parent[~v]) eulerNum += 1 self.right[self.parent[~v]] = eulerNum #A = [self.depth[e] for e in self.eulerTour] A = [0]*(2*self.n-1) for i, e in enumerate(self.eulerTour): A[i] = self.depth[e]*(2*self.n-1)+i self.seg = SegTree(A, ide_ele, segfunc) def getLCA(self, u, v): # u, v: 0-indexed p = min(self.left[u], self.left[v]) q = max(self.right[u], self.left[v])+1 m = self.seg.query(p, q) return self.eulerTour[m%(2*self.n-1)] import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, m = map(int, input().split()) g = [[] for i in range(n)] for i in range(n-1): a, b = map(int, input().split()) a, b = a-1, b-1 g[a].append(b) g[b].append(a) cd = CentroidDecomposition(g) lca = LCA(g, 0) #print(cd.cdparent) min_dist = [0]*n for i in range(n): min_dist[i] = lca.depth[i] #print(min_dist) for i in range(m): t, v = map(int, input().split()) v -= 1 if t == 1: cur = v while cur != -1: l = lca.getLCA(cur, v) d = lca.depth[cur]+lca.depth[v]-2*lca.depth[l] min_dist[cur] = min(min_dist[cur], d) cur = cd.cdparent[cur] else: ans = n cur = v while cur != -1: l = lca.getLCA(cur, v) d = lca.depth[cur]+lca.depth[v]-2*lca.depth[l] ans = min(ans, d+min_dist[cur]) cur = cd.cdparent[cur] print(ans) ```
output
1
3,693
13
7,387
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Submitted Solution: ``` N = int(1e5)+10 logn=20 graph = [[] for i in range(N)] par,sub,level,ans=[0 for i in range(N)],[0 for i in range(N)],[0 for i in range(N)],[float('inf') for i in range(N)] dp = [[0 for i in range(N)] for j in range(logn)] nn=0 #preprocessing part! def dfs0(u): global graph,level for v in graph[u]: if v!=dp[0][u]: dp[0][v]=u level[v]=level[u]+1 dfs0(v) def preprocess(): global dp level[0]=0 dp[0][0]=0 dfs0(0) for i in range(logn): for j in range(int(1e5)+10): dp[i][j]=dp[i-1][dp[i-1][j]] def lca(a,b): global level,dp,logn if level[a]>level[b]: a,b=b,a d = level[b]-level[a] for i in range(logn): if d&(1<<i): b=dp[i][b] if a==b: return a for i in range(logn-1,-1,-1): if dp[i][a]!=dp[i][b]: a,b=dp[i][a],dp[i][b] return dp[0][a] def dist(u,v): global level return level[u]+level[v]-2*level[lca(u,v)] #Decomposition part def dfs1(u,p): global graph,sub,nn sub[u]=1 nn+=1 for v in graph[u]: if v!=p: dfs1(v,u) sub[u]+=sub[v] def dfs2(u,p): global graph,sub for v in graph[u]: if v!=p and sub[v]>nn/2: return dfs2(v,u) return u def decompose(root,p): global graph nn=0 dfs1(root,root) centroid=dfs2(root,root) if p==-1:p=centroid par[centroid]=p for v in graph[centroid]: graph[v].remove(centroid) decompose(v,centroid) graph[centroid]=[] #Handling the queries part! def update(u): global ans,par x=u while True: ans[x]=min(ans[x],dist(x,u)) if x==par[x]:break x=par[x] def query(u): global par,ans x=u;ret=float('inf') while True: ret = min(ret,dist(u,x)+ans[x]) if x==par[x]: break x=par[x] return ret n,m=map(int,input().split()) for i in range(n-1): a,b = map(int,input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) preprocess() decompose(0,-1) update(0) for i in range(m): t,v = map(int,input().split());v-=1 if t==1: update(v) else: print(query(v)) ```
instruction
0
3,694
13
7,388
No
output
1
3,694
13
7,389
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Submitted Solution: ``` n,m=map(int,input().split()) tr=[set() for i in range(n+1)] trr=[[] for i in range(n+1)] for _ in range(n-1): a,b=map(int,input().split()) trr[a].append(b);trr[b].append(a) tr[a].add(b);tr[b].add(a) euler=[] disc=[-1 for i in range(n+1)] hei=[-1 for i in range(n+1)] def eulerr(): q=[1] pa={1:-1} hei[1]=0 while q: x=q.pop() if disc[x]==-1:disc[x]=len(euler) euler.append(x) if len(trr[x])==0: if pa[x]!=-1:q.append(pa[x]) elif trr[x][-1]==pa[x]: trr[x].pop(-1) q.append(x) euler.pop() else: y=trr[x].pop(-1) pa[y]=x hei[y]=hei[x]+1 q.append(y) eulerr() print(euler) st=[-1 for i in range(2*len(euler))] for i in range(len(euler)): st[i+len(euler)]=euler[i] for i in range(len(euler)-1,0,-1): if disc[st[i<<1]]<disc[st[i<<1|1]]: st[i]=st[i<<1] else: st[i]=st[i<<1|1] def dist(a,b): i=disc[a];j=disc[b] if i>j:i,j=j,i i+=len(euler);j+=len(euler)+1 ans=st[i] while i<j: if i&1: if disc[st[i]]<disc[ans]:ans=st[i] i+=1 if j&1: j-=1 if disc[st[j]]<disc[ans]:ans=st[j] i>>=1 j>>=1 return(hei[a]+hei[b]-2*hei[ans]) size=[0 for i in range(n+1)] def siz(i): pa={i:-1} q=[i] w=[] while q: x=q.pop() w.append(x) size[x]=1 for y in tr[x]: if y==pa[x]:continue pa[y]=x q.append(y) for j in range(len(w)-1,0,-1): x=w[j] size[pa[x]]+=size[x] return(size[i]) def centroid(i,nn): pa={i:-1} q=[i] while q: x=q.pop() for y in tr[x]: if y!=pa[x] and size[y]>nn/2: q.append(y) pa[y]=x break else:return(x) ct=[-1 for i in range(n+1)] def build(): q=[1] while q: x=q.pop() nn=siz(x) j=centroid(x,nn) ct[j]=ct[x] for y in tr[j]: tr[y].discard(j) ct[y]=j q.append(y) tr[j].clear() build() print(ct) ps=[float("INF") for i in range(n+1)] ps[1]=0 x=1 while ct[x]!=-1: ps[ct[x]]=min(ct[x],dist(1,ct[x])) x=ct[x] for _ in range(m): t,x=map(int,input().split()) if t==1: v=x while x!=-1: ps[x]=min(ps[x],dist(v,x)) x=ct[x] else: ans=ps[x] v=x while x!=-1: ans=min(ans,ps[x]+dist(v,x)) x=ct[x] print(ans) ```
instruction
0
3,695
13
7,390
No
output
1
3,695
13
7,391
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Submitted Solution: ``` N = int(1e5)+10 logn=20 graph = [[] for i in range(N)] par,sub,level,ans=[0 for i in range(N)],[0 for i in range(N)],[0 for i in range(N)],[float('inf') for i in range(N)] dp = [[0 for i in range(N)] for j in range(logn)] nn=0 #preprocessing part! def dfs0(u): global graph,level for v in graph[u]: if v!=dp[0][u]: dp[0][v]=u level[v]=level[u]+1 dfs0(v) def preprocess(): global dp level[0]=0 dp[0][0]=0 dfs0(1) for i in range(20): for j in range(int(1e5)+10): dp[i][j]=dp[i-1][dp[i-1][j]] def lca(a,b): global level,dp,logn if level[a]>level[b]: a,b=b,a d = level[b]-level[a] for i in range(logn): if d&(1<<i): b=dp[i][b] if a==b: return a for i in range(logn-1,-1,-1): if dp[i][a]!=dp[i][b]: a,b=dp[i][a],dp[i][b] return dp[0][a] def dist(u,v): global level return level[u]+level[v]-2*level[lca(u,v)] #Decomposition part def dfs1(u,p): global graph,sub,nn sub[u]=1 nn+=1 for v in graph[u]: if v!=p: dfs1(v,u) sub[u]+=sub[v] def dfs2(u,p): global graph,sub for v in graph[u]: if v!=p and sub[v]>nn/2: return dfs2(v,u) return u def decompose(root,p): global graph nn=0 dfs1(root,root) centroid=dfs2(root,root) if p==-1:p=centroid par[centroid]=p for v in graph[centroid]: graph[v].remove(centroid) decompose(v,centroid) graph[centroid]=[] #Handling the queries part! def update(u): global ans,par x=u while True: ans[x]=min(ans[x],dist(x,u)) if x==par[x]:break x=par[x] def query(u): global par,ans x=u;ret=float('inf') while True: ret = min(ret,dist(u,x)+ans[x]) if x==par[x]: break x=par[x] return ret n,m=map(int,input().split()) for i in range(n-1): a,b = map(int,input().split()) graph[a].append(b) graph[b].append(a) preprocess() decompose(1,-1) update(1) for i in range(m): t,v = map(int,input().split()); if t==1: update(v) else: print(query(v)) ```
instruction
0
3,696
13
7,392
No
output
1
3,696
13
7,393
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Submitted Solution: ``` n,m=map(int,input().split()) tr=[set() for i in range(n+1)] trr=[[] for i in range(n+1)] for _ in range(n-1): a,b=map(int,input().split()) trr[a].append(b);trr[b].append(a) tr[a].add(b);tr[b].add(a) euler=[] disc=[-1 for i in range(n+1)] hei=[-1 for i in range(n+1)] def eulerr(): q=[1] pa={1:-1} hei[1]=0 while q: x=q.pop() if disc[x]==-1:disc[x]=len(euler) euler.append(x) if len(trr[x])==0: if pa[x]!=-1:q.append(pa[x]) elif trr[x][-1]==pa[x]: trr[x].pop(-1) q.append(x) euler.pop() else: y=trr[x].pop(-1) pa[y]=x hei[y]=hei[x]+1 q.append(y) eulerr() st=[-1 for i in range(2*len(euler))] for i in range(len(euler)): st[i+len(euler)]=euler[i] for i in range(len(euler)-1,0,-1): if disc[st[i<<1]]<disc[st[i<<1|1]]: st[i]=st[i<<1] else: st[i]=st[i<<1|1] def dist(a,b): i=disc[a];j=disc[b] if i>j:i,j=j,i i+=len(euler);j+=len(euler)+1 ans=st[i] while i<j: if i&1: if disc[st[i]]<disc[ans]:ans=st[i] i+=1 if j&1: j-=1 if disc[st[j]]<disc[ans]:ans=st[j] i>>=1 j>>=1 return(hei[a]+hei[b]-2*hei[ans]) size=[0 for i in range(n+1)] def siz(i): pa={i:-1} q=[i] w=[] while q: x=q.pop() w.append(x) size[x]=1 for y in tr[x]: if y==pa[x]:continue pa[y]=x q.append(y) for j in range(len(w)-1,0,-1): x=w[j] size[pa[x]]+=size[x] return(size[i]) def centroid(i,nn): pa={i:-1} q=[i] while q: x=q.pop() for y in tr[x]: if y!=pa[x] and size[y]>nn//2: q.append(y) pa[y]=x break else:return(x) ct=[-1 for i in range(n+1)] def build(): q=[1] while q: x=q.pop() nn=siz(x) j=centroid(x,nn) ct[j]=ct[x] for y in tr[j]: tr[y].discard(j) ct[y]=j q.append(y) tr[j].clear() build() ps=[float("INF") for i in range(n+1)] ps[1]=0 x=1 while ct[x]!=-1: ps[ct[x]]=min(ct[x],dist(1,ct[x])) x=ct[x] for _ in range(m): t,x=map(int,input().split()) if t==1: ps[x]=0 v=x while ct[x]!=-1: ps[ct[x]]=min(ct[x],dist(v,ct[x])) x=ct[x] else: ans=ps[x] v=x while ct[x]!=-1: ans=min(ans,ps[ct[x]]+dist(v,ct[x])) x=ct[x] print(ans) ```
instruction
0
3,697
13
7,394
No
output
1
3,697
13
7,395
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
3,812
13
7,624
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
3,812
13
7,625
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
3,813
13
7,626
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees Correct Solution: ``` import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(200000000) input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) from functools import lru_cache def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) N= int(input()) A = alele() root = -1 vis = [False]*N for i in range(N): if i == A[i] - 1: root = i vis[i] = True break count = 0 for i in range(N): if not vis[i]: vis[i] = True;x= A[i]-1 temp =[i] while not vis[x]: temp.append(x) vis[x] = True x = A[x] - 1 if x in temp: if root == -1: root = x A[x] = root + 1 count += 1 print(count) print(*A) ```
output
1
3,813
13
7,627
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
3,814
13
7,628
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees Correct Solution: ``` n = int(input()) par = [int(x)-1 for x in input().split()] assert len(par) == n changes = 0 root = -1 for i, p in enumerate(par): if i == p: root = i break # possibly cycles, 0-n roots, possibly still root == -1 seen = [-1 for _ in range(n)] for x in range(n): if seen[x] >= 0: continue seen[x] = x cur = x while par[cur] != cur: if seen[par[cur]] >= 0 and seen[par[cur]] < x: break if seen[par[cur]] == x: changes += 1 if root == -1: par[cur] = cur root = cur else: par[cur] = root break cur = par[cur] seen[cur] = x # no cycles, root >= 0, 1-n roots for i, p in enumerate(par): if i == p and i != root: par[i] = root changes += 1 # no cycles, root >= 0, 1 root print(changes) print(' '.join([str(p+1) for p in par])) ```
output
1
3,814
13
7,629
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
3,815
13
7,630
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
3,815
13
7,631
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
3,816
13
7,632
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, P): while x != P[x]: x = P[x] return x def Solucion(): P = [None]*n for i in range(0, n): P[i] = i ciclosC = 0 ciclos = deque([]) root = [] i = 0 # ir haciendo Merge a cada arista while i < n: # Merge padre = Padre(A[i], P) # Si dicha arista perticipa en un ciclo if padre == 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: P[i] = A[i] i += 1 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() P[ciclo[0]] = root[0] PC = [x + 1 for x in P] print(*PC, sep=" ") 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 n = int(input()) A = list(map(lambda x: int(x)-1, input().split())) 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
3,816
13
7,633
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
3,817
13
7,634
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
3,817
13
7,635
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
3,818
13
7,636
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees Correct Solution: ``` class DSU(object): def __init__(self, n): self.p = list(range(n)) self.rk = [0] * n def find(self, u): while u != self.p[u]: u = self.p[u] return u def unite(self, u, v): u = self.find(u) v = self.find(v) if u == v: return if self.rk[u] < self.rk[v]: u, v = v, u self.p[v] = u self.rk[u] += self.rk[u] == self.rk[v] n = int(input()) p = list(map(int, input().split())) dsu = DSU(n) s = None for u in range(n): p[u] -= 1 if p[u] == u: s = u for u in range(n): dsu.unite(u, p[u]) ans = 0 rt = [None] * n vis = [False] * n for u in range(n): if dsu.find(u) != u: continue v = u while not vis[v]: vis[v] = True v = p[v] rt[u] = v if p[v] != v: p[v] = v if s is None: ans += 1 s = v for u in range(n): if u != dsu.find(s) and u == dsu.find(u): p[rt[u]] = s ans += 1 print(ans) for u in range(n): p[u] += 1 print(*p) ```
output
1
3,818
13
7,637
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
3,819
13
7,638
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
3,819
13
7,639
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 deque def Padre(x, P): while x != P[x]: x = P[x] return x def Solucion(): P = [None]*n for i in range(0, n): P[i] = i ciclosC = 0 ciclos = deque([]) root = [] i = 0 while i < n: padre = Padre(A[i], P) if padre == i: if not root and (i == A[i]): root = [i, A[i]] else: ciclos.append([i, A[i]]) ciclosC += 1 else: P[i] = A[i] i += 1 print(str(ciclosC)) if ciclosC: i = 0 if not root: root = ciclos.popleft() i = 1 while ciclos: ciclo = ciclos.popleft() P[ciclo[0]] = root[0] PC = [x + 1 for x in P] print(*PC, sep=" ") def DFS(x, color, padre, ciclos, adyacentes, raiz): color[x] = 1 for y in adyacentes[x]: if color[y] == 0: DFS(y, color, padre, ciclos, adyacentes, raiz) padre[y] = x elif color[y] == 2: padre[y] = x else: if y == x and not raiz: raiz = x else: ciclos.append([x, y]) color[x] = 2 n = int(input()) A = list(map(lambda x: int(x)-1, input().split())) Solucion() ```
instruction
0
3,820
13
7,640
Yes
output
1
3,820
13
7,641
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()) parents = [None] + list(map(int, input().split())) visited = [None] * len(parents) candidates = set() hot = None for node in range(1, n+1): if visited[node]: continue run = node visited[node] = run while parents[node] != node and not visited[parents[node]]: node = parents[node] visited[node] = run if visited[parents[node]] == run: candidates.add(node) if parents[node] == node: hot = node if hot: root = hot candidates.remove(hot) else: root = candidates.pop() candidates.add(root) print(len(candidates)) print(" ".join(map(str, (p if node not in candidates else root for node, p in list(enumerate(parents))[1:])))) ```
instruction
0
3,821
13
7,642
Yes
output
1
3,821
13
7,643
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()) 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))) ```
instruction
0
3,822
13
7,644
Yes
output
1
3,822
13
7,645
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: ``` 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 ans= 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: #new cycle if root==-1: A[a]=a+1 root=a ans+=1 else : A[a]=root+1 ans+=1 print(ans) print(' '.join(map(str,A))) ```
instruction
0
3,823
13
7,646
Yes
output
1
3,823
13
7,647
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: ``` def get(x): if p[x] != x: p[x] = get(p[x]) return p[x] def union(x, y): x = get(x) y = get(y) p[x] = y n = int(input()) a = list(x - 1 for x in map(int, input().split())) p = list(range(n)) bad = [] root = None for i in range(n): if i == a[i]: if root is None: root = i else: bad.append(i) else: if get(i) != get(a[i]): union(i, a[i]) else: bad.append(i) result = len(bad) if root is None: root = bad[-1] bad = bad[:-1] a[root] = root components = set(p) for i in bad: cur = get(i) for j in components: if j != cur: a[i] = j union(i, j) break print(result) print(' '.join(map(str, map(lambda x: x + 1, a)))) ```
instruction
0
3,824
13
7,648
No
output
1
3,824
13
7,649
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
3,825
13
7,650
No
output
1
3,825
13
7,651
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: ``` class DSU(object): def __init__(self, n): self.p = list(range(n)) self.rk = [0] * n def find(self, u): while u != self.p[u]: u = self.p[u] return u def unite(self, u, v): u = self.find(u) v = self.find(v) if u == v: return if self.rk[u] < self.rk[v]: u, v = v, u self.p[v] = u self.rk[u] += self.rk[u] == self.rk[v] n = int(input()) p = list(map(int, input().split())) dsu = DSU(n) s = None for u in range(n): p[u] -= 1 if p[u] == u: s = u for u in range(n): dsu.unite(u, p[u]) ans = 0 rt = [None] * n vis = [False] * n for u in range(n): if dsu.find(u) != u: continue v = u while not vis[v]: vis[v] = True v = p[v] rt[u] = v if p[v] != v: p[v] = v if s is None: ans += 1 s = v for u in range(n): if u != dsu.find(s) and u == dsu.find(u): p[u] = s ans += 1 print(ans) for u in range(n): p[u] += 1 print(*p) ```
instruction
0
3,826
13
7,652
No
output
1
3,826
13
7,653
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())) class DisjSet: def __init__(self, n): # Constructor to create and # initialize sets of n items self.rank = [1] * n self.parent = [i for i in range(n)] self.extra = [] # Finds set of given item x def find(self, x): # Finds the representative of the set # that x is an element of if (self.parent[x] != x): # if x is not the parent of itself # Then x is not the representative of # its set, self.parent[x] = self.find(self.parent[x]) # so we recursively call Find on its parent # and move i's node directly under the # representative of this set return self.parent[x] # Do union of two sets represented # by x and y. def Union(self, x, y): # Find current sets of x and y xset = self.find(x) yset = self.find(y) # If they are already in same set if xset == yset: self.extra.append((x, y)) return # Put smaller ranked item under # bigger ranked item if ranks are # different if self.rank[xset] < self.rank[yset]: self.parent[xset] = yset elif self.rank[xset] > self.rank[yset]: self.parent[yset] = xset # If ranks are same, then move y under # x (doesn't matter which one goes where) # and increment rank of x's tree else: self.parent[yset] = xset self.rank[xset] = self.rank[xset] + 1 obj = DisjSet(n) self_parent=0 for i in range(n): obj.Union(i,a[i]-1) if i==a[i]-1: self_parent+=1 hashmap={} for i in range(n): temp=obj.find(i) if temp not in hashmap: hashmap[temp]=[] hashmap[temp].append(i) if len(hashmap)==1 and self_parent==1: print(0) print(*a) elif len(hashmap)==1 and self_parent==0: print(1) a[0]=1 print(*a) else: self_parents=[] total=0 for i in range(0,len(a)): if i==a[i]-1: self_parents.append(i) if len(self_parents)==0: total+=1 self_parents=[0] for i in hashmap: self_parent=-1 for k in hashmap[i]: if a[k]-1==k: self_parent=k if self_parent==-1: a[hashmap[i][0]]=self_parents[0]+1 total+=1 else: if a[self_parent]==self_parents[0]+1: continue a[self_parent]=self_parents[0]+1 total+=1 print(total) print(*a) ```
instruction
0
3,827
13
7,654
No
output
1
3,827
13
7,655
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
instruction
0
4,189
13
8,378
Tags: dfs and similar, trees Correct Solution: ``` import sys input=sys.stdin.readline n = int(input()) a = [int(t) for t in input().split(' ')] mx = [[] for _ in range(n)] for i in range(n-1): v1, v2 = map(int,input().split()) mx[v1-1].append(v2-1) mx[v2-1].append(v1-1) count = [[0, 0] for _ in range(n)] total = [a.count(1), a.count(2)] answer = 0 OBSERVE = 0 CHECK = 1 stack = [(OBSERVE, 0, -1)] while len(stack): #print(stack,count) state, vertex, parent = stack.pop() if state == OBSERVE: stack.append((CHECK, vertex, parent)) for child in mx[vertex]: #print(nv,v,from_) if child != parent: stack.append((OBSERVE, child, vertex)) else: for child in mx[vertex]: if child != parent: #print(child,parent,count) if count[child][0] == total[0] and count[child][1] == 0 or count[child][1] == total[1] and count[child][0] == 0: answer += 1 count[vertex][0] += count[child][0] count[vertex][1] += count[child][1] if a[vertex] != 0: #print(count) count[vertex][a[vertex]-1] += 1 #print(count) print(answer) ```
output
1
4,189
13
8,379
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
instruction
0
4,190
13
8,380
Tags: dfs and similar, trees Correct Solution: ``` import sys n = int(input()) a = [int(t) for t in input().split(' ')] mx = [[] for _ in range(n)] lines = sys.stdin.readlines() for i in range(n-1): v1, v2 = (int(t) - 1 for t in lines[i].split(' ')) mx[v1].append(v2) mx[v2].append(v1) count = [[0, 0] for _ in range(n)] total = [a.count(1), a.count(2)] answer = 0 OBSERVE = 0 CHECK = 1 stack = [(OBSERVE, 0, -1)] while len(stack): state, v, from_ = stack.pop() if state == OBSERVE: stack.append((CHECK, v, from_)) for nv in mx[v]: if nv != from_: stack.append((OBSERVE, nv, v)) else: for nv in mx[v]: if nv != from_: if count[nv][0] == total[0] and count[nv][1] == 0 or count[nv][1] == total[1] and count[nv][0] == 0: answer += 1 count[v][0] += count[nv][0] count[v][1] += count[nv][1] if a[v] != 0: count[v][a[v]-1] += 1 print(answer) ```
output
1
4,190
13
8,381
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
instruction
0
4,191
13
8,382
Tags: dfs and similar, trees Correct Solution: ``` #!/usr/bin/env python3 """ This file is part of https://github.com/cheran-senthil/PyRival Copyright 2019 Cheran Senthilkumar <hello@cheran.io> """ import os import sys from atexit import register from io import BytesIO input = BytesIO(os.read(0, os.fstat(0).st_size)).readline sys.__stdout__ = BytesIO() register(lambda: os.write(1, sys.__stdout__.getvalue())) res = 0 def main(): n = int(input()) a = input().split() red_cnt = a.count(b'1') blue_cnt = a.count(b'2') tree = [[] for _ in range(n)] for _ in range(n - 1): v, u = map(int, input().split()) tree[v - 1].append(u - 1) tree[u - 1].append(v - 1) dp, visited = [[0, 0] for _ in range(n)], [False] * n def dfs(node): global res finished = [False] * n stack = [node] while stack: node = stack[-1] node_cnt = dp[node] if not visited[node]: visited[node] = True else: stack.pop() node_cnt[0] += a[node] == b'1' node_cnt[1] += a[node] == b'2' finished[node] = True for child in tree[node]: if not visited[child]: stack.append(child) elif finished[child]: child_cnt = dp[child] node_cnt[0] += child_cnt[0] node_cnt[1] += child_cnt[1] if ((child_cnt[0] == red_cnt) and (child_cnt[1] == 0)) or ((child_cnt[0] == 0) and (child_cnt[1] == blue_cnt)): res += 1 dfs(0) print(res) if __name__ == '__main__': main() ```
output
1
4,191
13
8,383
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
instruction
0
4,192
13
8,384
Tags: dfs and similar, trees Correct Solution: ``` from sys import stdin,stdout from collections import * from math import gcd,floor,ceil st=lambda:list(stdin.readline().strip()) li=lambda:list(map(int,stdin.readline().split())) mp=lambda:map(int,stdin.readline().split()) inp=lambda:int(stdin.readline()) pr=lambda n: stdout.write(str(n)+"\n") mod=1000000007 INF=float('inf') ans=0 n=inp() l=[0]+li() edge=[li() for i in range(n-1)] d={i:[] for i in range(n+1)} for i in edge: a,b=i d[a].append(b) d[b].append(a) red,blue=0,0 for i in l: red+= (i==1) blue+= (i==2) stack=[1] v=[0 for i in range(n+1)] RED=[1 if i==1 else 0 for i in l ] BLUE=[1 if i==2 else 0 for i in l ] par=[-1 for i in range(n+1)] v[1]=1 while stack: a=stack[-1] f=0 for i in d[a]: if not v[i]: v[i]=1 stack.append(i) f=1 par[i]=a if f==0: z=stack.pop() if stack: RED[par[z]]+=RED[z] BLUE[par[z]]+=BLUE[z] for i in range(1,n+1): if par[i]!=-1: if RED[i]==red and BLUE[i]==0 or RED[i]==0 and BLUE[i]==blue: ans+=1 pr(ans) ```
output
1
4,192
13
8,385
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
instruction
0
4,193
13
8,386
Tags: dfs and similar, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase from collections import defaultdict, deque, Counter, OrderedDict import threading def main(): n = int(input()) a = [0]+[*map(int,input().split())] adj = [[] for _ in range(n+1)] for i in range(n-1): x,y = map(int,input().split()) adj[x].append(y) adj[y].append(x) num = [[0,0] for _ in range(n+1)] q=deque([[1,-1]]) Eq = deque() while q: x, par = q.popleft() Eq.appendleft([x,par]) for nx in adj[x]: if nx == par:continue q.append([nx,x]) while Eq: x, par = Eq.popleft() if a[x] == 1: num[x][0] += 1 if a[x] == 2: num[x][1] += 1 for nx in adj[x]: if nx == par: continue num[x][0] += num[nx][0] num[x][1] += num[nx][1] ans = 0 for i in range(2,n+1): if num[i][0] == num[1][0] and num[i][1] == 0:ans+=1 if num[i][0] == 0 and num[i][1] == num[1][1]: ans+=1 print(ans) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": """threading.stack_size(40960000) thread = threading.Thread(target=main) thread.start()""" main() ```
output
1
4,193
13
8,387
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
instruction
0
4,194
13
8,388
Tags: dfs and similar, trees Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def main(): n = int(input()) a = list(map(int,input().split())) red = a.count(1) blue = a.count(2) path = [[] for _ in range(n+1)] for _ in range(n-1): u1,v1 = map(int,input().split()) path[u1].append(v1) path[v1].append(u1) st = [1] parent = [0]*(n+1) parent[1] = 1 dp = [[0,0] for _ in range(n+1)] # red ; blue ans = 0 while len(st): while len(path[st[-1]]) and parent[path[st[-1]][-1]]: path[st[-1]].pop() if not len(path[st[-1]]): x = st.pop() if a[x-1] == 1: dp[x][0] += 1 elif a[x-1] == 2: dp[x][1] += 1 if (dp[x][0] == red and not dp[x][1]) or (dp[x][1] == blue and not dp[x][0]): ans += 1 if len(st): dp[st[-1]][0] += dp[x][0] dp[st[-1]][1] += dp[x][1] continue i = path[st[-1]].pop() parent[i] = 1 st.append(i) print(ans) #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main() ```
output
1
4,194
13
8,389
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
instruction
0
4,195
13
8,390
Tags: dfs and similar, trees Correct Solution: ``` from collections import deque import sys input = sys.stdin.readline class Graph(object): """docstring for Graph""" def __init__(self,n,d): # Number of nodes and d is True if directed self.n = n self.graph = [[] for i in range(n)] self.parent = [-1 for i in range(n)] self.directed = d def addEdge(self,x,y): self.graph[x].append(y) if not self.directed: self.graph[y].append(x) def bfs(self, root): # NORMAL BFS self.parent = [-1 for i in range(self.n)] queue = [root] queue = deque(queue) vis = [0]*self.n while len(queue)!=0: element = queue.popleft() vis[element] = 1 for i in self.graph[element]: if vis[i]==0: queue.append(i) self.parent[i] = element def dfs(self, root, ans): # Iterative DFS stack=[root] vis=[0]*self.n stack2=[] while len(stack)!=0: # INITIAL TRAVERSAL element = stack.pop() if vis[element]: continue vis[element] = 1 stack2.append(element) for i in self.graph[element]: if vis[i]==0: self.parent[i] = element stack.append(i) while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question element = stack2.pop() m = [0,0] for i in self.graph[element]: if i!=self.parent[element]: m[0] += ans[i][0] m[1] += ans[i][1] if arr[element] == 1: m[0] += 1 elif arr[element] == 2: m[1] += 1 ans[element] = m return ans def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes self.bfs(source) path = [dest] while self.parent[path[-1]]!=-1: path.append(parent[path[-1]]) return path[::-1] def ifcycle(self): self.bfs(0) queue = [0] vis = [0]*n queue = deque(queue) while len(queue)!=0: element = queue.popleft() vis[element] = 1 for i in graph[element]: if vis[i]==1 and i!=parent[element]: return True if vis[i]==0: queue.append(i) vis[i] = 1 return False def reroot(self, root, ans): stack = [root] count = 0 vis = [0]*self.n while len(stack)!=0: e = stack[-1] # print (e,ans) if vis[e]: stack.pop() if self.parent[e]!=-1: ans[self.parent[e]][0] += ans[e][0] ans[self.parent[e]][1] += ans[e][1] if self.parent[self.parent[e]]!=-1: ans[self.parent[e]][0] -= ans[self.parent[self.parent[e]]][0] ans[self.parent[e]][1] -= ans[self.parent[self.parent[e]]][1] continue vis[e]=1 for i in self.graph[e]: if not vis[i]: stack.append(i) if self.parent[e]==-1: continue ans[self.parent[e]][0] -= ans[e][0] ans[self.parent[e]][1] -= ans[e][1] if self.parent[self.parent[e]]!=-1: ans[self.parent[e]][0] += ans[self.parent[self.parent[e]]][0] ans[self.parent[e]][1] += ans[self.parent[self.parent[e]]][1] if 0 in ans[e] and 0 in ans[self.parent[e]]: count+=1 return count n = int(input()) g = Graph(n,False) arr = list(map(int,input().split())) for i in range(n-1): x,y = map(int,input().split()) g.addEdge(x-1,y-1) ans = [[0,0] for i in range(n)] a = g.dfs(0,ans) print (g.reroot(0,a)) ```
output
1
4,195
13
8,391
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
instruction
0
4,196
13
8,392
Tags: dfs and similar, trees Correct Solution: ``` import os, sys from io import IOBase, BytesIO py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # Cout implemented in Python import sys class ostream: def __lshift__(self,a): sys.stdout.write(str(a)) return self cout = ostream() endl = '\n' from collections import deque n=int(input()) a=list(map(int,input().split())) tr=[[] for i in range(n)] for i in range(n-1): u,v=map(int,input().split()) tr[u-1].append(v-1) tr[v-1].append(u-1) r={} b={} s=[0] s=deque() s.append(0) p={0:-1} m=[] while s: x=s.popleft() if a[x]==1:r[x]=1;b[x]=0 elif a[x]==2:r[x]=0;b[x]=1 else:r[x]=0;b[x]=0 for j in tr[x]: if j==p[x]:continue s.append(j) p[j]=x m.append(x) for i in range(n-1,0,-1): r[p[m[i]]]+=r[m[i]] b[p[m[i]]]+=b[m[i]] red=a.count(1) blue=a.count(2) ans=0 for i in range(1,n): if (r[i]==red and b[i]==0) or (r[i]==0 and b[i]==blue):ans+=1 print(ans) ```
output
1
4,196
13
8,393
Provide tags and a correct Python 2 solution for this coding contest problem. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
instruction
0
4,197
13
8,394
Tags: dfs and similar, trees Correct Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict raw_input = stdin.readline pr = stdout.write def in_arr(): return map(int,raw_input().split()) def pr_num(n): stdout.write(str(n)+'\n') def pr_arr(arr): for i in arr: stdout.write(str(i)+' ') stdout.write('\n') range = xrange # not for python 3.0+ n=int(raw_input()) l=in_arr() d=[[] for i in range(n+1)] b=l.count(2) r=l.count(1) for i in range(n-1): u,v=in_arr() d[u].append(v) d[v].append(u) q=[1] vis=[0]*(n+1) pos=0 vis[1]=1 while pos<n: x=q[pos] pos+=1 for i in d[x]: if not vis[i]: vis[i]=1 q.append(i) dp=[[0,0] for i in range(n+1)] while q: x=q.pop() vis[x]=0 if l[x-1]==1: dp[x][0]=1 elif l[x-1]==2: dp[x][1]=1 for i in d[x]: if not vis[i]: dp[x][0]+=dp[i][0] dp[x][1]+=dp[i][1] q=[1] vis[1]=1 ans=0 while q: x=q.pop(0) for i in d[x]: if not vis[i] and (dp[i][0] or dp[i][1]): vis[i]=1 q.append(i) if ((dp[i][1]==b) and (dp[i][0]==0)) or (dp[i][1]==0 and dp[i][0]==r): #print x,i,b-dp[i][1],r-dp[i][0] ans+=1 pr_num(ans) ```
output
1
4,197
13
8,395
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` from collections import deque import sys input = sys.stdin.readline def bfs(s): q = deque() q.append(s) visit = [0] * (n + 1) visit[s] = 1 parent = [-1] * (n + 1) p = [] while q: i = q.popleft() p.append(i) for j in G[i]: if not visit[j]: q.append(j) visit[j] = 1 parent[j] = i return parent, p n = int(input()) a = list(map(int, input().split())) cnt = [0] * 3 for i in a: cnt[i] += 1 G = [[] for _ in range(n + 1)] for _ in range(n - 1): u, v = map(int, input().split()) G[u].append(v) G[v].append(u) parent, p = bfs(1) dpr, dpb = [0] * (n + 1), [0] * (n + 1) ans = 0 for _ in range(n - 1): i = p.pop() j = parent[i] if a[i - 1] == 1: dpr[i] += 1 elif a[i - 1] == 2: dpb[i] += 1 if (not dpr[i] and dpb[i] == cnt[2]) or (not dpb[i] and dpr[i] == cnt[1]): ans += 1 dpr[j] += dpr[i] dpb[j] += dpb[i] print(ans) ```
instruction
0
4,198
13
8,396
Yes
output
1
4,198
13
8,397
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` import sys from collections import defaultdict n = int(input()) #n,k = [int(__) for __ in raw_input().split()] arr = [int(__) for __ in input().split()] sactive = set() sactive.add(0) nums = [0] * n d1 = defaultdict(set) d2 = defaultdict(set) d = defaultdict(set) lines = sys.stdin.readlines() for i in range(n-1): sactive.add(i+1) s,f = [int(__) for __ in lines[i].strip().split()] s -= 1 f -= 1 d[s].add(f) d[f].add(s) nums[f] += 1 nums[s] += 1 leaves = set() for i in range(n): if nums[i] == 1: leaves.add(i) while len(leaves): x = leaves.pop() if arr[x] == 0: sactive.remove(x) nums[x] -= 1 targ = d[x].pop() nums[targ] -= 1 d[targ].remove(x) if nums[targ] == 1: leaves.add(targ) sactive1 = sactive.copy() for targ in d: d1[targ] = d[targ].copy() nums1 = nums[:] nums2 = nums[:] for i in range(n): if nums1[i] == 1: leaves.add(i) while len(leaves): x = leaves.pop() if arr[x] != 1: sactive1.remove(x) nums1[x] -= 1 targ = d1[x].pop() nums1[targ] -= 1 d1[targ].remove(x) if nums1[targ] == 1: leaves.add(targ) sactive2 = sactive.copy() for targ in d: d2[targ] = d[targ].copy() for i in range(n): if nums2[i] == 1: leaves.add(i) while len(leaves): x = leaves.pop() if arr[x] != 2: sactive2.remove(x) nums2[x] -= 1 targ = d2[x].pop() nums2[targ] -= 1 d2[targ].remove(x) if nums2[targ] == 1: leaves.add(targ) if len(sactive1 & sactive2) > 0: print(0) else: print(len(sactive) - len(sactive1) - len(sactive2) + 1) #print(nums) #print('both',sactive) #print('1',sactive1) #print('2',sactive2) #print(d) ```
instruction
0
4,199
13
8,398
Yes
output
1
4,199
13
8,399
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from collections import defaultdict, deque, Counter, OrderedDict import threading def main(): n = int(input()) a = [0] + [*map(int, input().split())] adj = [[] for _ in range(n + 1)] for i in range(n - 1): x, y = map(int, input().split()) adj[x].append(y) adj[y].append(x) num = [[0, 0] for _ in range(n + 1)] q = deque([1]) visit = [0]*(n+1);visit[1] = 1 for i in range(n-1): x = q[i] for nx in adj[x]: if visit[nx]: continue q.append(nx) visit[nx] = 1 while q: x = q.pop() if a[x] == 1: num[x][0] += 1 if a[x] == 2: num[x][1] += 1 for nx in adj[x]: num[x][0] += num[nx][0] num[x][1] += num[nx][1] ans = 0 for i in range(2, n + 1): if num[i][0] == num[1][0] and num[i][1] == 0: ans += 1 if num[i][0] == 0 and num[i][1] == num[1][1]: ans += 1 print(ans) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": """threading.stack_size(40960000) thread = threading.Thread(target=main) thread.start()""" main() ```
instruction
0
4,200
13
8,400
Yes
output
1
4,200
13
8,401
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ####################################### import sys,threading sys.setrecursionlimit(600000) threading.stack_size(10**8) def dfs(x): global v,l,l1,l2,adj,a,b,ans v[x]=1 if l[x-1]==1: l1[x]+=1 elif l[x-1]==2: l2[x]+=1 for i in adj[x]: if not v[i]: dfs(i) l1[x]+=l1[i] l2[x]+=l2[i] if l1[x]*l2[x]==0: if l1[x]: if l1[x]==a: ans+=1 elif l2[x]: if l2[x]==b: ans+=1 def main(): global v,l,l1,l2,adj,a,b,ans n=int(input()) l=list(map(int,input().split())) v=[0]*(n+1) l1=[0]*(n+1) l2=[0]*(n+1) ans,a,b=0,l.count(1),l.count(2) adj=[[] for i in range(n+1)] for i in range(n-1): x,y=map(int,input().split()) adj[x].append(y) adj[y].append(x) dfs(1) print(ans) t=threading.Thread(target=main) t.start() t.join() ```
instruction
0
4,201
13
8,402
Yes
output
1
4,201
13
8,403
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` import sys red = 0 blue = 0 N = int(sys.stdin.readline().split()[0]) line = sys.stdin.readline().split() colored = [] tree = [] for i in range(N): item = int(line[i]) if item == 1: red += 1 elif item == 2: blue += 1 colored.append(item) tree.append([]) for _ in range(N - 1): line = sys.stdin.readline().split() u, v = int(line[0]) - 1, int(line[1]) - 1 tree[u].append(v) tree[v].append(u) answer = 0 def dfs(v: int , pi_v : int): global answer r = colored[v] == 1 if 1 else 0 b = colored[v] == 2 if 1 else 0 for u in tree[v]: if not u == pi_v: dfs_rec = dfs(u, v) answer += dfs_rec[0] == red and dfs_rec[1] == 0 if 1 else 0 answer += dfs_rec[1] == blue and dfs_rec[0] == 1 if 1 else 0 r += dfs_rec[0] b += dfs_rec[1] return [r, b] dfs(0, -1) sys.stdout.write(str(answer) + "\n") ```
instruction
0
4,202
13
8,404
No
output
1
4,202
13
8,405
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` n = int(input()) nc = list(map(int,input().split())) edges = [list(map(int,input().split())) for x in range(n-1)] a = 0 for x in range(len(edges)): c1 =[edges[x][0]] c2 = [edges[x][1]] rg = True for y in range(len(edges)): if y == x: continue e = edges[y] if e[0] in c1: c1.append(e[1]) continue if e[1] in c1: c1.append(e[0]) continue if e[1] in c2: c2.append(e[0]) continue if e[0] in c2: c2.append(e[1]) continue pcol = 0 rg1 = True for x in c1: if pcol == 0: if nc[x-1] != 0: pcol = nc[x-1] elif nc[x-1] != 0: if pcol != nc[x-1]: rg1=False pcol = 0 for x in c2: if pcol == 0: if nc[x-1] != 0: pcol = nc[x-1] elif nc[x-1] != 0: if pcol != nc[x-1]: rg=False if rg and rg1: a += 1 print(a) ```
instruction
0
4,203
13
8,406
No
output
1
4,203
13
8,407
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` n = int(input()) lst = list(map(int, input().split())) lst2 = [] for i in range(n-1): tupl = tuple(map(int, input().split())) lst2.append(tupl) def cut_tree(n, lst, lst2): my_dict = dict() for i in range(len(lst)): my_dict[i+1] = lst[i] output = len(lst2) for i in range(len(lst2)): a = lst2[i][0] b = lst2[i][1] red_a = 0 blue_a = 0 red_b = 0 blue_b = 0 if my_dict[a] == 1: red_a += 1 elif my_dict[a] == 2: blue_a += 1 if my_dict[b] == 1: red_b += 1 elif my_dict[b] == 2: blue_b += 1 #from the beginning to the point; left for k in range(0, i): if a in lst2[k]: if (lst2[k][0] != a and my_dict[lst2[k][0]] == 1) or (lst2[k][1] != a and my_dict[lst2[k][1]] == 1): red_a += 1 elif (lst2[k][0] != a and my_dict[lst2[k][0]] == 2) or (lst2[k][1] != a and my_dict[lst2[k][1]] == 2): blue_a += 1 elif b in lst2[k]: if (lst2[k][0] != b and my_dict[lst2[k][0]] == 1) or (lst2[k][1] != b and my_dict[lst2[k][1]] == 1): red_b += 1 elif (lst2[k][0] != b and my_dict[lst2[k][0]] == 2) or (lst2[k][1] != b and my_dict[lst2[k][1]] == 2): red_b += 1 if red_a > 0 and blue_a > 0: output -= 1 break elif red_b > 0 and blue_b > 0: output -= 1 break #from the point to the end; right for j in range(i+1, len(lst2)): if a in lst2[j]: if (lst2[j][0] != a and my_dict[lst2[j][0]] == 1) or (lst2[j][1] != a and my_dict[lst2[j][1]] == 1): red_a += 1 elif (lst2[j][0] != a and my_dict[lst2[j][0]] == 2) or (lst2[j][1] != a and my_dict[lst2[j][1]] == 2): blue_a += 1 elif b in lst2[j]: if (lst2[j][0] != b and my_dict[lst2[j][0]] == 1) or (lst2[j][1] != b and my_dict[lst2[j][1]] == 1): red_b += 1 elif (lst2[j][0] != b and my_dict[lst2[j][0]] == 2) or (lst2[j][1] != b and my_dict[lst2[j][1]] == 2): red_b += 1 if red_a > 0 and blue_a > 0: output -= 1 break elif red_b > 0 and blue_b > 0: output -= 1 break return output print(cut_tree(n, lst, lst2)) ```
instruction
0
4,204
13
8,408
No
output
1
4,204
13
8,409
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer — the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` def dfs(graph, visited, vertexes_colors, vertex, common_red, common_blue): visited[vertex] = True good_edges_count = 0 red = 0 blue = 0 if vertexes_colors[vertex] == 1: red += 1 elif vertexes_colors[vertex] == 2: blue += 1 for new_vertex in graph[vertex]: if visited[new_vertex]: continue new_red, new_blue, new_good_edges_count = dfs(graph, visited, vertexes_colors, new_vertex, common_red, common_blue) red += new_red blue += new_blue good_edges_count += new_good_edges_count if (not new_red and new_blue == common_blue) or (not new_blue and new_red == common_red): good_edges_count += 1 return red, blue, good_edges_count def main(): n = int(input()) vertexes_colors = list(map(int, input().split())) edges = [list(map(lambda v_: int(v_) - 1, input().split())) for _ in range(n - 1)] common_color_count = [0, 0, 0] _, common_red, common_blue = common_color_count for color in vertexes_colors: common_color_count[color] += 1 graph = [[] for _ in range(n)] for edge in edges: v, u = edge graph[v].append(u) graph[u].append(v) visited = [False] * n _, _, good_edges_count = dfs(graph, visited, vertexes_colors, 0, common_red, common_blue) print(good_edges_count) main() ```
instruction
0
4,205
13
8,410
No
output
1
4,205
13
8,411