message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image>
instruction
0
34,305
13
68,610
Tags: dfs and similar, trees Correct Solution: ``` n=int(input()) sd=dict() lt=[0]*(n+1) for i in range(1,n+1): a,b=map(int,input().split()) if(a!=-1): if(a not in sd): sd[a]=[] sd[a].append(i) if(b==1): lt[i]=1 an=[] for j in range(1,n+1): if(lt[j]==1): if(j in sd): for k in sd[j]: if(lt[k]==0): break else: an.append(j) else: an.append(j) if(len(an)==0): print("-1") else: print(*an) ```
output
1
34,305
13
68,611
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image>
instruction
0
34,306
13
68,612
Tags: dfs and similar, trees Correct Solution: ``` from collections import defaultdict,Counter n=int(input()) l=[] p=[0]*n c=[0]*n for i in range(n): pp,cc=map(int,input().split()) p[i],c[i]=pp,cc d=c[:] for i in range(n): if p[i]!=-1 and not c[i]: d[p[i]-1]=0 if d==[0]*n: print(-1) else: for i,v in enumerate(d): if v: print(i+1,end=' ') ```
output
1
34,306
13
68,613
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image>
instruction
0
34,307
13
68,614
Tags: dfs and similar, trees Correct Solution: ``` def isvalid(l): global obeys for i in l: if(obeys[i]==0): return 0 return 1 n=int(input()) arrofp=[0 for i in range(n+1)] obeys=[0 for i in range(n+1)] isparentof=[[] for i in range(n+1)] for i in range(1,n+1): l=input().split() arrofp[i]=int(l[0]) if(arrofp[i]==-1): continue isparentof[arrofp[i]].append(i) obeys[i]=int(l[1]) lfi=[] for i in range(1,n+1): if(obeys[i]==1): if(isvalid(isparentof[i])): lfi.append(i) if(lfi==[]): print(-1) else: for i in lfi: print(i,end=" ") print() ```
output
1
34,307
13
68,615
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image>
instruction
0
34,308
13
68,616
Tags: dfs and similar, trees Correct Solution: ``` class node: def __init__(self, value, parent, respect): self.value = value self.children = [] self.parent = parent self.respect = respect all_nodes = {} root = -1 not_respectors = [] import sys n = int(sys.stdin.readline()) for i in range(n): line = sys.stdin.readline()[:-1] node_parent, node_res = line.split(" ") if i+1 in all_nodes: all_nodes[i+1].parent = int(node_parent) all_nodes[i+1].respect = int(node_res) else: all_nodes[i+1] = node(i+1, int(node_parent), int(node_res)) if int(node_parent) == -1: root = all_nodes[i+1] else: int_node_parent = int(node_parent) if int_node_parent not in all_nodes: all_nodes[int_node_parent] = node(int_node_parent, -1, -1) all_nodes[int_node_parent].children.append(all_nodes[i+1]) if int(node_res) == 1: not_respectors.append(all_nodes[i+1]) def get_val(n): return n.value not_respecters = sorted(not_respectors, key=get_val) tot = [] for n in not_respectors: b = True for c in n.children: if c.respect == 0: b = False break if b: tot.append(n) if len(tot) == 0: print("-1") else: print(" ".join(map(str, map(get_val, tot)))) ```
output
1
34,308
13
68,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image> Submitted Solution: ``` n=int(input()) parent=[0 for i in range(n)] root=[0 for i in range(n)] respected_parent=[0 for i in range(n)] do_not_respect_child=[0 for i in range(n)] for i in range(n): p,c=map(int,input().split()) parent[i]=p if(p==-1): root[i]=1 if(c==0 and p!=-1): respected_parent[p-1]=1 else: do_not_respect_child[i]=1 ls=[] for i in range(n): if(respected_parent[i]==0 and do_not_respect_child[i]==1 and root[i]==0): ls.append(i+1) if(len(ls)>0):print(*ls) else:print(-1) ```
instruction
0
34,309
13
68,618
Yes
output
1
34,309
13
68,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image> Submitted Solution: ``` n = int(input()) tree = [[] for i in range(n)] pl = list() cl = list() cdoom = [True]*n for i in range(n): p, c = map(int, input().split()) pl.append(p-1) cl.append(c) if p != -1: tree[p-1].append(i) if c == 0: cdoom[p-1] = False ans = [] for i in range(n): if cl[i] == 0: continue if cl[i] == 1 and cdoom[i] == True: ans.append(str(i+1)) if len(ans) == 0: print(-1) else: print(' '.join(ans)) ```
instruction
0
34,310
13
68,620
Yes
output
1
34,310
13
68,621
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image> Submitted Solution: ``` def f(graf): for i in graf: if i > 0: return False return True n = int(input()) graf = [[]] for i in range(n): graf.append([]) maspred = [0] for i in range(1, n + 1): p, c = map(int, input().split()) maspred.append(p) if c == 0: c = 1 else: c = -1 if p == -1: continue graf[p].append(i * c) graf[i].append(p * c) ch = 0 for i in range(1, len(graf)): if f(graf[i]) and maspred[i] != -1: print(i) ch += 1 if ch == 0: print(-1) ```
instruction
0
34,311
13
68,622
Yes
output
1
34,311
13
68,623
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image> Submitted Solution: ``` # Author Name: Ajay Meena # Codeforce : https://codeforces.com/profile/majay1638 import sys import math import bisect import heapq from bisect import bisect_right from sys import stdin, stdout # -------------- INPUT FUNCTIONS ------------------ def get_ints_in_variables(): return map( int, sys.stdin.readline().strip().split()) def get_int(): return int(sys.stdin.readline()) def get_ints_in_list(): return list( map(int, sys.stdin.readline().strip().split())) def get_list_of_list(n): return [list( map(int, sys.stdin.readline().strip().split())) for _ in range(n)] def get_string(): return sys.stdin.readline().strip() # -------- SOME CUSTOMIZED FUNCTIONS----------- def myceil(x, y): return (x + y - 1) // y # -------------- SOLUTION FUNCTION ------------------ def Solution(hm, adjList, n): # Write Your Code Here # print(adjList) f = 1 for i in range(1, n+1): if hm[i][1] == -1: continue if hm[i][1] == 1: flg = 1 for child in adjList[i]: if hm[child][1] == 0: flg = 0 break if flg: f = 0 print(i, end=" ") if f: print(-1) else: print() def main(): # Take input Here and Call solution function n = get_int() hm = {} adjList = [[] for _ in range(n+1)] for i in range(n): u, v = get_ints_in_variables() hm[i+1] = [u, v] if u != -1: adjList[u].append(i+1) Solution(hm, adjList, n) # calling main Function if __name__ == '__main__': main() ```
instruction
0
34,312
13
68,624
Yes
output
1
34,312
13
68,625
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image> Submitted Solution: ``` import sys input = sys.stdin.readline ''' ''' n = int(input()) parent_children = [[] for _ in range(n+1)] respects_parent = [None] * (n+1) for child in range(1, n+1): parent, respect = map(int, input().split()) if parent == -1: root = child parent_children[parent].append(child) respects_parent[child] = respect to_cut = [0] * (n+1) from collections import deque visited = [0] * (n+1) stack = deque([root]) visited[root] = 1 while stack: node = stack.pop() r = respects_parent[node] for child in parent_children[node]: r = r and respects_parent[child] if not visited[child]: stack.append(child) visited[child] = 1 to_cut[node] = r res = [] for node in range(1, n+1): if to_cut[node] and node != root: res.append(node) if len(res): print(*sorted(res)) else: print(-1) ```
instruction
0
34,313
13
68,626
No
output
1
34,313
13
68,627
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image> Submitted Solution: ``` n = int(input()) child=[[] for i in range(n+1)] nonr=[0 for i in range(n+1)] a=[[] for i in range(n+1)] b=[] for i in range(1,n+1): a[i]=list(map(int,input().split())) child[a[i][0]]+=[i] nonr[a[i][0]]+=a[i][1] for i in range(1,n+1): if a[i][1]==1: if len(child[i])==nonr[i]: b+=[i] child[a[i][0]].pop(child[a[i][0]].index(i)) child[a[i][0]]+=child[i] nonr[a[i][0]]+=(nonr[i]-1) if(len(b)>0): print(*b) else: print(-1) ```
instruction
0
34,314
13
68,628
No
output
1
34,314
13
68,629
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image> Submitted Solution: ``` from sys import * V = int(stdin.readline()) Tree = [] for v in range(V): Tree += [[[], None, True]] #print(Tree) for v in range(V): p, c = map(int, stdin.readline().split()) if p == -1: Tree[v][2] = False if p != -1: if c == 0: Tree[p - 1][2] = False Tree[v][2] = False Tree[v][1] = p - 1 else: if Tree[p - 1][2] == True: Tree[p - 1][0] += [v] Tree[v][1] = p - 1 from heapq import * curCan = [] allValid = set() for i, t in enumerate(Tree): if t[2]: allValid.add(i) for i, t in enumerate(Tree): if t[2] == True: parentInd = t[1] if Tree[parentInd][2] == False: heappush(curCan, i) if len(allValid) == 0: print(-1) else: ''' print(curCan) print(allValid) print(Tree)''' while curCan != []: newCan = [] for i in curCan: print(i + 1, end=' ') for j in Tree[i][0]: if j in allValid: newCan += [j] curCan = newCan ''' 5 3 1 1 1 -1 0 1 1 3 0 outputCopy 1 2 4 inputCopy 5 -1 0 1 1 1 1 2 0 3 0 outputCopy -1 inputCopy 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 outputCopy 5 ''' ```
instruction
0
34,315
13
68,630
No
output
1
34,315
13
68,631
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image> Submitted Solution: ``` n = int(input()) korz = 0 usu = [1] * (n + 1) for i in range(1, n + 1): a, b = list(map(int,input().split())) if b == 0: usu[i] = 0 usu[a] = 0 if b == -1: korz = a u = [] for i in range(n + 1): if usu[i] == 1 and i > 0: u.append(i) u = sorted(u) if len(u) == 0: print(-1) else: for i in u: if i != korz: print(i, end = " ") ```
instruction
0
34,316
13
68,632
No
output
1
34,316
13
68,633
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define the sum of prefix sums of an array [s_1, s_2, ..., s_k] as s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + ... + (s_1 + s_2 + ... + s_k). You are given a tree consisting of n vertices. Each vertex i has an integer a_i written on it. We define the value of the simple path from vertex u to vertex v as follows: consider all vertices appearing on the path from u to v, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence. Your task is to calculate the maximum value over all paths in the tree. Input The first line contains one integer n (2 ≤ n ≤ 150000) — the number of vertices in the tree. Then n - 1 lines follow, representing the edges of the tree. Each line contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), denoting an edge between vertices u_i and v_i. It is guaranteed that these edges form a tree. The last line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6). Output Print one integer — the maximum value over all paths in the tree. Example Input 4 4 2 3 2 4 1 1 3 3 7 Output 36 Note The best path in the first example is from vertex 3 to vertex 1. It gives the sequence [3, 3, 7, 1], and the sum of prefix sums is 36. Submitted Solution: ``` def prefix(t): return sum([(len(t)-i)*t[i] for i in range(len(t))]) def cal_prefix(L): nodes=L[len(L)-1] a=0 for i in range(len(nodes)): if nodes[i]>nodes[a]: a=i path_L=path(L[:-1], a) return max([prefix([nodes[i-1] for i in c]) for c in path_L]) def path(T,a): S=[] TT=[] for i in range(len(T)): if a==T[i][0] or a==T[i][1]: if a==T[i][0]: S.append(T[i]) else: S.append(T[i][::-1]) else: TT.append(T[i]) HH=[] if len(S)==0: HH.append([a]) for s in S: SS=path(TT,s[1]) if len(SS)>=0: for ss in SS: HH.append([a]+ss) return HH if __name__=='__main__': t=int(input()) L=[] for i in range(t): s=list(map(int,input().split())) L.append(s) print(cal_prefix(L)) # L=[[4, 2], [3, 2], [4, 1], [1, 3, 3, 7]] # S=[[1,2],[1,3],[3,4],[4,5]] # R=[[1,2],[1,3]] # c=path(L[:-1],2) # d=paths(L[:-1]) # print(cal_prefix(L)) ```
instruction
0
34,418
13
68,836
No
output
1
34,418
13
68,837
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define the sum of prefix sums of an array [s_1, s_2, ..., s_k] as s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + ... + (s_1 + s_2 + ... + s_k). You are given a tree consisting of n vertices. Each vertex i has an integer a_i written on it. We define the value of the simple path from vertex u to vertex v as follows: consider all vertices appearing on the path from u to v, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence. Your task is to calculate the maximum value over all paths in the tree. Input The first line contains one integer n (2 ≤ n ≤ 150000) — the number of vertices in the tree. Then n - 1 lines follow, representing the edges of the tree. Each line contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), denoting an edge between vertices u_i and v_i. It is guaranteed that these edges form a tree. The last line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6). Output Print one integer — the maximum value over all paths in the tree. Example Input 4 4 2 3 2 4 1 1 3 3 7 Output 36 Note The best path in the first example is from vertex 3 to vertex 1. It gives the sequence [3, 3, 7, 1], and the sum of prefix sums is 36. Submitted Solution: ``` def prefix(t): return sum([(len(t)-i)*t[i] for i in range(len(t))]) def cal_prefix(L): nodes=L[len(L)-1] from collections import Counter multi=Counter([a[0] for a in L[:-1] ]+[a[1] for a in L[:-1] ]) leaves=[a for a in multi if multi[a]==1] leaves_max=[leaves[0]] for c in range(len(leaves)): if leaves_max[0]<nodes[c]: leaves_max=[c] elif leaves_max[0]==nodes[c]: leaves_max.append(c) for a in leaves_max: path_L=path(L[:-1], a, nodes) path_L+=[a[::-1] for a in path_L] c=max([len(a) for a in path_L]) path_L=[a for a in path_L if len(a)==c] # print(path_L) return max([prefix(c) for c in path_L]) def path(T,a, nodes): S=[] TT=[] for i in range(len(T)): if a==T[i][0] or a==T[i][1]: if a==T[i][0]: S.append(T[i]) else: S.append(T[i][::-1]) else: TT.append(T[i]) HH=[] if len(S)==0: HH.append([nodes[a-1]]) for s in S: SS=path(TT,s[1],nodes) if len(SS)>=0: c=max([len(ss) for ss in SS]) for ss in SS: if len(ss)==c: HH.append([nodes[a-1]]+ss) return HH if __name__=='__main__': t=int(input()) L=[] for i in range(t): s=list(map(int,input().split())) L.append(s) print(cal_prefix(L)) # L=[[4, 2], [3, 2], [4, 1], [1, 3, 3, 7]] # S=[[1,2],[1,3],[3,4],[4,5]] # R=[[1,2],[1,3]] # c=path(L[:-1],2) # d=paths(L[:-1]) # print(cal_prefix(L)) ```
instruction
0
34,419
13
68,838
No
output
1
34,419
13
68,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define the sum of prefix sums of an array [s_1, s_2, ..., s_k] as s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + ... + (s_1 + s_2 + ... + s_k). You are given a tree consisting of n vertices. Each vertex i has an integer a_i written on it. We define the value of the simple path from vertex u to vertex v as follows: consider all vertices appearing on the path from u to v, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence. Your task is to calculate the maximum value over all paths in the tree. Input The first line contains one integer n (2 ≤ n ≤ 150000) — the number of vertices in the tree. Then n - 1 lines follow, representing the edges of the tree. Each line contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), denoting an edge between vertices u_i and v_i. It is guaranteed that these edges form a tree. The last line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6). Output Print one integer — the maximum value over all paths in the tree. Example Input 4 4 2 3 2 4 1 1 3 3 7 Output 36 Note The best path in the first example is from vertex 3 to vertex 1. It gives the sequence [3, 3, 7, 1], and the sum of prefix sums is 36. Submitted Solution: ``` def prefix(t): return sum([(len(t)-i)*t[i] for i in range(len(t))]) def cal_prefix(L): nodes=L[len(L)-1] from collections import Counter multi=Counter([a[0] for a in L[:-1] ]+[a[1] for a in L[:-1] ]) leaves=[a for a in multi if multi[a]==1] # for a in leaves: path_L=path(L[:-1], a) path_L+=[a[::-1] for a in path_L] c=max([len(a) for a in path_L]) path_L=[a for a in path_L if len(a)==c] # print(path_L) return max([prefix([nodes[i-1] for i in c]) for c in path_L]) def path(T,a): S=[] TT=[] for i in range(len(T)): if a==T[i][0] or a==T[i][1]: if a==T[i][0]: S.append(T[i]) else: S.append(T[i][::-1]) else: TT.append(T[i]) HH=[] if len(S)==0: HH.append([a]) for s in S: SS=path(TT,s[1]) if len(SS)>=0: c=max([len(ss) for ss in SS]) HH=[[a]+ss for ss in SS if len(ss)==c] return HH if __name__=='__main__': t=int(input()) L=[] for i in range(t): s=list(map(int,input().split())) L.append(s) print(cal_prefix(L)) # L=[[4, 2], [3, 2], [4, 1], [1, 3, 3, 7]] # S=[[1,2],[1,3],[3,4],[4,5]] # R=[[1,2],[1,3]] # c=path(L[:-1],2) # d=paths(L[:-1]) # print(cal_prefix(L)) ```
instruction
0
34,420
13
68,840
No
output
1
34,420
13
68,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We define the sum of prefix sums of an array [s_1, s_2, ..., s_k] as s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + ... + (s_1 + s_2 + ... + s_k). You are given a tree consisting of n vertices. Each vertex i has an integer a_i written on it. We define the value of the simple path from vertex u to vertex v as follows: consider all vertices appearing on the path from u to v, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence. Your task is to calculate the maximum value over all paths in the tree. Input The first line contains one integer n (2 ≤ n ≤ 150000) — the number of vertices in the tree. Then n - 1 lines follow, representing the edges of the tree. Each line contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), denoting an edge between vertices u_i and v_i. It is guaranteed that these edges form a tree. The last line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6). Output Print one integer — the maximum value over all paths in the tree. Example Input 4 4 2 3 2 4 1 1 3 3 7 Output 36 Note The best path in the first example is from vertex 3 to vertex 1. It gives the sequence [3, 3, 7, 1], and the sum of prefix sums is 36. Submitted Solution: ``` 12345 ```
instruction
0
34,421
13
68,842
No
output
1
34,421
13
68,843
Provide a correct Python 3 solution for this coding contest problem. We have a weighted directed graph with N vertices numbered 0 to N-1. The graph initially has N-1 edges. The i-th edge (0 \leq i \leq N-2) is directed from Vertex i to Vertex i+1 and has a weight of 0. Snuke will now add a new edge (i → j) for every pair i, j (0 \leq i,j \leq N-1,\ i \neq j). The weight of the edge will be -1 if i < j, and 1 otherwise. Ringo is a boy. A negative cycle (a cycle whose total weight is negative) in a graph makes him sad. He will delete some of the edges added by Snuke so that the graph will no longer contain a negative cycle. The cost of deleting the edge (i → j) is A_{i,j}. He cannot delete edges that have been present from the beginning. Find the minimum total cost required to achieve Ringo's objective. Constraints * 3 \leq N \leq 500 * 1 \leq A_{i,j} \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_{0,1} A_{0,2} A_{0,3} \cdots A_{0,N-1} A_{1,0} A_{1,2} A_{1,3} \cdots A_{1,N-1} A_{2,0} A_{2,1} A_{2,3} \cdots A_{2,N-1} \vdots A_{N-1,0} A_{N-1,1} A_{N-1,2} \cdots A_{N-1,N-2} Output Print the minimum total cost required to achieve Ringo's objective. Examples Input 3 2 1 1 4 3 3 Output 2 Input 4 1 1 1 1 1 1 1 1 1 1 1 1 Output 2 Input 10 190587 2038070 142162180 88207341 215145790 38 2 5 20 32047998 21426 4177178 52 734621629 2596 102224223 5 1864 41 481241221 1518272 51 772 146 8805349 3243297 449 918151 126080576 5186563 46354 6646 491776 5750138 2897 161 3656 7551068 2919714 43035419 495 3408 26 3317 2698 455357 3 12 1857 5459 7870 4123856 2402 258 3 25700 16191 102120 971821039 52375 40449 20548149 16186673 2 16 130300357 18 6574485 29175 179 1693 2681 99 833 131 2 414045824 57357 56 302669472 95 8408 7 1266941 60620177 129747 41382505 38966 187 5151064 Output 2280211
instruction
0
34,945
13
69,890
"Correct Solution: ``` N = int(input()) A = [[0] * N for _ in range(N)] Al = [[0] * (N+1) for _ in range(N+1)] Ar = [[0] * (N+1) for _ in range(N+1)] for i in range(N) : a = [int(i) for i in input().split()] for j in range(N) : if i < j : A[i][j] = a[j-1] elif i > j : A[i][j] = a[j] for i in range(N) : for j in range(i+1, N) : Al[j][i+1] = Al[j][i] + A[j][i] Ar[i][j] = Ar[i-1][j] + A[i][j] dp = [[float('inf')] * (N+1) for _ in range(N+1)] dp[0][0] = 0 for i in range(N+1) : for j in range(i, N+1) : if dp[i][j] == float('inf') : continue l, r = 0, 0 for k in range(j+1, N+1) : l += Al[k-1][i] r += Ar[k-2][k-1] - Ar[j-1][k-1] dp[j][k] = min(dp[j][k], dp[i][j] + l + r) print(min(dp[i][N] for i in range(N+1))) ```
output
1
34,945
13
69,891
Provide a correct Python 3 solution for this coding contest problem. We have a weighted directed graph with N vertices numbered 0 to N-1. The graph initially has N-1 edges. The i-th edge (0 \leq i \leq N-2) is directed from Vertex i to Vertex i+1 and has a weight of 0. Snuke will now add a new edge (i → j) for every pair i, j (0 \leq i,j \leq N-1,\ i \neq j). The weight of the edge will be -1 if i < j, and 1 otherwise. Ringo is a boy. A negative cycle (a cycle whose total weight is negative) in a graph makes him sad. He will delete some of the edges added by Snuke so that the graph will no longer contain a negative cycle. The cost of deleting the edge (i → j) is A_{i,j}. He cannot delete edges that have been present from the beginning. Find the minimum total cost required to achieve Ringo's objective. Constraints * 3 \leq N \leq 500 * 1 \leq A_{i,j} \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_{0,1} A_{0,2} A_{0,3} \cdots A_{0,N-1} A_{1,0} A_{1,2} A_{1,3} \cdots A_{1,N-1} A_{2,0} A_{2,1} A_{2,3} \cdots A_{2,N-1} \vdots A_{N-1,0} A_{N-1,1} A_{N-1,2} \cdots A_{N-1,N-2} Output Print the minimum total cost required to achieve Ringo's objective. Examples Input 3 2 1 1 4 3 3 Output 2 Input 4 1 1 1 1 1 1 1 1 1 1 1 1 Output 2 Input 10 190587 2038070 142162180 88207341 215145790 38 2 5 20 32047998 21426 4177178 52 734621629 2596 102224223 5 1864 41 481241221 1518272 51 772 146 8805349 3243297 449 918151 126080576 5186563 46354 6646 491776 5750138 2897 161 3656 7551068 2919714 43035419 495 3408 26 3317 2698 455357 3 12 1857 5459 7870 4123856 2402 258 3 25700 16191 102120 971821039 52375 40449 20548149 16186673 2 16 130300357 18 6574485 29175 179 1693 2681 99 833 131 2 414045824 57357 56 302669472 95 8408 7 1266941 60620177 129747 41382505 38966 187 5151064 Output 2280211
instruction
0
34,946
13
69,892
"Correct Solution: ``` N = int(input()) A = [[0] * N for _ in range(N)] Al = [[0] * (N+1) for _ in range(N+1)] Ar = [[0] * (N+1) for _ in range(N+1)] for i in range(N) : a = [int(i) for i in input().split()] for j in range(N) : if i < j : A[i][j] = a[j-1] elif i > j : A[i][j] = a[j] for i in range(N) : for j in range(i+1, N) : Al[j][i+1] = Al[j][i] + A[j][i] Ar[i][j] = Ar[i-1][j] + A[i][j] # for al in Al : # print(al) # print() # for ar in Ar : # print(ar) dp = [[float('inf')] * (N+1) for _ in range(N+1)] dp[0][0] = 0 for i in range(N+1) : for j in range(i, N+1) : l, r = 0, 0 for k in range(j+1, N+1) : l += Al[k-1][i] r += Ar[k-2][k-1] - Ar[j-1][k-1] dp[j][k] = min(dp[j][k], dp[i][j] + l + r) # print('i', i, 'j', j, 'k', k, l, r) # print(dp) print(min(dp[i][N] for i in range(N+1))) ```
output
1
34,946
13
69,893
Provide a correct Python 3 solution for this coding contest problem. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13
instruction
0
34,963
13
69,926
"Correct Solution: ``` N=int(input()) numlist=list(map(int,(input() for _ in range(N)))) numdict={y:x for x,y in enumerate(numlist)} sorted_list=sorted(numdict.items(),reverse=True) nextS=lambda Snow,child : Snow+2*child-N amount_of_child=[1]*N sum_of_distance_of_child=[0]*N branch_list=[] for S,num in sorted_list: nS=nextS(S,amount_of_child[num]) if nS in numdict: nextnum=numdict[nS] branch_list.append([num+1,nextnum+1]) amount_of_child[nextnum]+=amount_of_child[num] sum_of_distance_of_child[nextnum]+=(sum_of_distance_of_child[num]+amount_of_child[num]) if amount_of_child[nextnum]==N: break else: print (-1) exit() if sorted_list[-1][0]==sum_of_distance_of_child[sorted_list[-1][1]]: for _ in range(N-1): x,y=branch_list.pop() print(x,y) else: print (-1) exit() ```
output
1
34,963
13
69,927
Provide a correct Python 3 solution for this coding contest problem. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13
instruction
0
34,964
13
69,928
"Correct Solution: ``` N = int(input()) src = [int(input()) for i in range(N)] idx = {a:i for i,a in enumerate(src)} size = [1] * N ss = list(sorted(src)) es = [] gr = [[] for i in range(N)] while len(ss) > 1: a = ss.pop() k = size[idx[a]] b = a + 2*k - N if b == a or b not in idx: print(-1) exit() size[idx[b]] += k ai,bi = idx[a],idx[b] es.append((ai,bi)) gr[ai].append(bi) gr[bi].append(ai) from collections import deque dist = [N] * N dist[idx[ss[0]]] = 0 q = deque([idx[ss[0]]]) while q: v = q.popleft() for to in gr[v]: if dist[to] < N: continue q.append(to) dist[to] = dist[v] + 1 if all(d<N for d in dist) and sum(dist) == ss[0]: for a,b in es: print(a+1, b+1) else: print(-1) ```
output
1
34,964
13
69,929
Provide a correct Python 3 solution for this coding contest problem. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13
instruction
0
34,965
13
69,930
"Correct Solution: ``` n = int(input()) d = [int(input()) for i in range(n)] if sum(d)%2 > 0: print(-1) exit() d = sorted([(dd, i) for i, dd in enumerate(d)], reverse = True) d_to_i = {dd:i for dd, i in d} n_child = [1]*n d_child = [0]*n ans = [] for dd, i in d: d_i = dd+2*n_child[i]-n if d_i in d_to_i.keys(): i_next = d_to_i[d_i] ans.append((i+1, i_next+1)) n_child[i_next] += n_child[i] d_child[i_next] += d_child[i] + n_child[i] if n_child[i_next] == n: break else: print(-1) exit() d_min, i_min = d[-1] if d_min == d_child[i_min]: for a in ans: print(*a) else: print(-1) ```
output
1
34,965
13
69,931
Provide a correct Python 3 solution for this coding contest problem. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13
instruction
0
34,966
13
69,932
"Correct Solution: ``` import sys sys.setrecursionlimit(10**7) n = int(input()) d = [int(input()) for _ in range(n)] r = {v: i for i, v in enumerate(d)} sz = [1] * n dsorted = sorted(((di, i) for i, di in enumerate(d)), reverse=True) ans = [] to = [[] for _ in range(n)] for di, i in dsorted[:n-1]: nd = di + (sz[i] - 1) - (n - 2 - (sz[i] - 1)) if not nd in r: print(-1) exit() p = r[nd] to[p].append(i) sz[p] += sz[i] ans.append((i+1, p+1)) root = dsorted[-1][1] def dfs(u, cur=0): rv = cur for v in to[u]: rv += dfs(v, cur + 1) return rv if dfs(root) != d[root]: print(-1) exit() for u, v in ans: print(u, v) ```
output
1
34,966
13
69,933
Provide a correct Python 3 solution for this coding contest problem. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13
instruction
0
34,967
13
69,934
"Correct Solution: ``` import sys input = sys.stdin.readline N = int(input()) D = [None] + [int(input()) for _ in range(N)] parent = [None] * (N+1) size = [None] + [1] * N # 部分木の頂点数、自分を含む d_to_i = {d:i for i,d in enumerate(D)} D_desc = sorted(D[1:],reverse=True) D_subtree = [0] * (N+1) edges = [] bl = True for d in D_desc[:-1]: i = d_to_i[d] d_parent = d - N + 2*size[i] if d_parent not in d_to_i: bl = False break p = d_to_i[d_parent] edges.append('{} {}'.format(i,p)) parent[i] = p size[p] += size[i] D_subtree[p] += D_subtree[i] + size[i] root = d_to_i[D_desc[-1]] bl &= (D_subtree[root] == D[root]) if bl: print('\n'.join(edges)) else: print(-1) ```
output
1
34,967
13
69,935
Provide a correct Python 3 solution for this coding contest problem. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13
instruction
0
34,968
13
69,936
"Correct Solution: ``` def solve(n, ddd): dsd = {d: i for i, d in enumerate(ddd)} child_cnt = [1] * n child_dist = [0] * n buf = [] srt = sorted(dsd.items(), reverse=True) for d, i in srt[:-1]: cc = child_cnt[i] pd = d - (n - cc * 2) if pd == d or pd not in dsd: return -1 pi = dsd[pd] buf.append((pi + 1, i + 1)) child_cnt[pi] += cc child_dist[pi] += child_dist[i] + cc md, mi = srt[-1] if md != child_dist[mi]: return -1 return buf n = int(input()) ddd = list(map(int, (input() for _ in range(n)))) res = solve(n, ddd) if res == -1: print(-1) else: print('\n'.join('{} {}'.format(*l) for l in res)) ```
output
1
34,968
13
69,937
Provide a correct Python 3 solution for this coding contest problem. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13
instruction
0
34,969
13
69,938
"Correct Solution: ``` """ Writer: SPD_9X2 https://atcoder.jp/contests/arc103/tasks/arc103_d 面白そう! とっかかりはどのへんだろうか 偶奇あたりから考えてみる? まず、A→BとA←B の距離は等しいので、Dの合計は絶対偶数になる Dの和が奇数なら構築不可能 辺u,vを取り除いて,2つの部分木に分解する、各木の含む頂点数を x[u],x[v]とすると D[u]+x[u] == D[v]+x[v] となる (x[u] + x[v] == N) 最大のDについて考えてみよう 最大のDから繋がってる点を根とした部分木は少なくとも半分の数の要素を含む なので、Dmaxは2つ以上辺を持っていてはいけない→Dmaxは葉 Dmaxを置くと、それとつながる要素のdは1意に定まる 残り(unused)の頂点の内、最大のを考える。 こいつももう葉になるしかない 1意に定まりんぐ ん~? こんな感じで大を小につけていけば構築完了するんじゃね? 小-大-小 となることはない(小の成分は半分以上の点を含むため) なのでおkそう! D[u] > D[v]のとき D[v] = D[u] + x[u] - x[v] x[v] = N-x[u]なので D[v] = D[u] + 2*x[u] - N だめな理由がわからないが… 可能性1: 大が2つ以上の小に繋がってる場合がある(可能を-1にしてる) 可能性2: 実は構築したやつが条件を満たしてない(-1を可能にしてる) →どっちもそんなこと無さそうなのに… ====テストケースを見たら2っぽさそう==== 可能性2の方をつぶそう →連結じゃない?自分より小さいdにすべて繋いでるんだからそんなことないだろ じゃあ場合によってはxが違う? →どんな場合よ? →うーん? 最後に一応チェック機構入れるか →つまりジャッジを書く 簡易的に、xに問題が生じてそうなとき(根がNになってないとき)は-1にするようにしてみた →xの数がちゃんと計算されていないわけではない?? ===kmjp氏のぶろぐ=== 検算が必要??なんで? dの条件は必要条件であって十分条件ではないからか! →むずいよ… dの間に成り立つべき関係を書いただけで、d全部がずれてる可能性があると… →つまり1頂点の付いて成立すればいいので、根のdを調べてあげればいいか """ import sys N = int(input()) Dz = 0 Di = [] d_to_ind = {} for i in range(N): d = int(input()) if i == 0: Dz = d Di.append([d,i]) d_to_ind[d] = i Di.sort() Di.reverse() x = [1] * N ans = [] lis = [ [] for i in range(N) ] for lp in range(N-1): nowd,nowi = Di[lp] nexd = nowd + 2*x[nowi] - N if nexd >= nowd: print (-1) sys.exit() if nexd not in d_to_ind: print (-1) sys.exit() nexi = d_to_ind[nexd] x[nexi] += x[nowi] ans.append([nowi+1,nexi+1]) lis[nowi].append(nexi) lis[nexi].append(nowi) #ジャッジを書く(1頂点について成立すればおk) from collections import deque q = deque([0]) dis = [float("inf")] * N dis[0] = 0 while len(q) > 0: now = q.popleft() for nex in lis[now]: if dis[nex] > dis[now]: dis[nex] = dis[now] + 1 q.append(nex) if sum(dis) != Dz: print (-1) sys.exit() for i in range(N-1): print (ans[i][0] , ans[i][1]) ```
output
1
34,969
13
69,939
Provide a correct Python 3 solution for this coding contest problem. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13
instruction
0
34,970
13
69,940
"Correct Solution: ``` n = int(input()) a = [] s = [] for i in range(n): x = int(input()) a.append(x * n + i) s.append(1) a.sort() a.reverse() a.append(-1) Sum = 0 Have = True result = [] for i in range(n - 1): l = 0 r = n val = (a[i] // n) + s[i] + s[i] - n while (l < r): m = (l + r + 2) // 2 if (a[m] >= val * n): l = m else: r = m - 1 if((a[l] // n) != val): Have = False break s[l] += s[i] Sum += s[i] result.append([a[i] % n,a[l] % n]) if (Sum != (a[n - 1] // n)): Have = False if (Have == False): print("-1") else: for e in result: print(e[0] + 1,end = " ") print(e[1] + 1) ```
output
1
34,970
13
69,941
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13 Submitted Solution: ``` def main(): N = int(input()) D = [int(input()) for i in range(N)] C = [1] * N T = [0] * N DI = {} for i in range(len(D)): DI[D[i]] = i D = sorted(D) P = [-1] * N while len(D) > 1: d = D.pop() i = DI[d] nd = d - N + C[i] * 2 if nd in DI: ni = DI[nd] else: print(-1) return P[i] = ni C[ni] += C[i] T[ni] += T[i] + C[i] if D[0] == T[DI[D[0]]]: for i in range(N): if P[i] >= 0: print(i+1, P[i]+1) else: print(-1) main() ```
instruction
0
34,971
13
69,942
Yes
output
1
34,971
13
69,943
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13 Submitted Solution: ``` N=int(input()) numlist=[int(input()) for _ in range(N)] numdict={y:x for x,y in enumerate(numlist)} sorted_list=sorted(numdict.items(),reverse=True) nextS=lambda Snow,child : Snow+2*child-N amount_of_child=[1]*N sum_of_distance_of_child=[0]*N branch_list=[] for S,num in sorted_list: nS=nextS(S,amount_of_child[num]) if nS in numdict: nextnum=numdict[nS] branch_list.append([num+1,nextnum+1]) amount_of_child[nextnum]+=amount_of_child[num] sum_of_distance_of_child[nextnum]+=(sum_of_distance_of_child[num]+amount_of_child[num]) if amount_of_child[nextnum]==N: break else: print (-1) exit() if sorted_list[-1][0]==sum_of_distance_of_child[sorted_list[-1][1]]: for _ in range(N-1): x,y=branch_list.pop() print(x,y) else: print (-1) exit() ```
instruction
0
34,972
13
69,944
Yes
output
1
34,972
13
69,945
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13 Submitted Solution: ``` def solve(): # N = int(raw_input()) # D = [int(raw_input()) for i in range(N)] N = int(input()) D = [int(input()) for i in range(N)] if sum(D) % 2 > 0: print ('-1') return Di = sorted([(di, i) for i, di in enumerate(D)], key = lambda x : x[0], reverse = True) d_to_i = {dd:i for dd, i in Di} # child = [[] for i in range(N)] ans = [] n_child = [1] * N d_child = [0] * N for valD, node in Di: valD_par = valD - N + 2 * n_child[node] if valD_par in d_to_i.keys(): node_par = d_to_i[valD_par] # child[node].append(node_par) ## # child[node_par].append(node) ans.append((node_par + 1, node + 1)) n_child[node_par] += n_child[node] d_child[node_par] += n_child[node] + d_child[node] if n_child[node_par] == N: break else: print ('-1') return # check if Di satisfied or not d_min, i_min = Di[-1] if d_child[i_min] != d_min: print ('-1') return # for i in range(N): # for j in child[i]: # print str(i + 1) + ' ' + str(j + 1) for i,j in ans: print (str(i) + ' ' + str(j)) if __name__ == '__main__': solve() ```
instruction
0
34,973
13
69,946
Yes
output
1
34,973
13
69,947
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13 Submitted Solution: ``` #!/usr/bin/env python3 import sys sys.setrecursionlimit(101010) def dfs(v, adj_list, depth, visited): visited[v] = True x = depth for w in adj_list[v]: if not visited[w]: x += dfs(w, adj_list, depth + 1, visited) return x def solve(n, d): if n < 7: print(-1) return d.sort() w = [1] * n edges = [] adj_list = [[] for _ in range(n)] for j in range(n - 1, 0, -1): di, i = d[j] pdi = di - n + 2 * w[i] p = None lo, hi = 0, j while lo < hi: mid = (lo + hi) // 2 xdi, xi = d[mid] if xdi == pdi: p = xi break elif xdi < pdi: lo = mid + 1 else: hi = mid if p is None: print(-1) return u, v = i, p if v < u: u, v = v, u edges.append((u + 1, v + 1)) adj_list[u].append(v) adj_list[v].append(u) w[p] += w[i] d0, r = d[0] visited = [False] * n x = dfs(r, adj_list, 0, visited) if x != d0: print(-1) return edges.sort() for uv in edges: u, v = uv print('{} {}'.format(u, v)) def main(): n = input() n = int(n) d = [] for i in range(n): di = input() di = int(di) d.append((di, i)) solve(n, d) if __name__ == '__main__': main() ```
instruction
0
34,974
13
69,948
Yes
output
1
34,974
13
69,949
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13 Submitted Solution: ``` n = int(input()) coordinates = [] distance = [] for i in range(n): coordinate = list(map(int, input().split())) coordinates.append(coordinate) distance.append((abs(coordinate[0]) + abs(coordinate[1]))) def parity_check(p, index): if len(distance) < index + 1: return if p != distance[index] % 2: print(-1) exit() parity_check(p, index + 1) parity_check(distance[0] % 2, 1) m = max(distance) d = ["1"] * m print(m) print(" ".join(d)) for i in range(n): result = "RL" * ((m - distance[i]) // 2) if coordinates[i][0] < 0: result += "L" * -coordinates[i][0] else: result += "R" * coordinates[i][0] if coordinates[i][1] < 0: result += "D" * -coordinates[i][1] else: result += "U" * coordinates[i][1] print(result) ```
instruction
0
34,975
13
69,950
No
output
1
34,975
13
69,951
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13 Submitted Solution: ``` from collections import defaultdict N = int(input()) C = defaultdict(int) for i in range(N): D = int(input()) C[D] = i + 1 E = [] H = [1] * (N + 1) DD = sorted([[k, v] for k, v in C.items()], reverse=True) Adj = [[] for i in range(N)] for D, n in DD[:-1]: try: p = C[D - N + 2 * H[n]] if n == p: raise Error E.append([n, p]) Adj[n - 1].append(p - 1) Adj[p - 1].append(n - 1) H[p] += H[n] except: print(-1) break else: dist = [N] * N dist[DD[-1][1] - 1] = 0 Q = [DD[-1][1] - 1] for i in range(N - 1): s = Q[i] for adj in Adj[s]: if dist[adj] == N: dist[adj] = dist[s] + 1 Q.append(adj) if sum(dist) == DD[-1][0]: for e in E: print(e[0], e[1]) else: print(-1) ```
instruction
0
34,976
13
69,952
No
output
1
34,976
13
69,953
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13 Submitted Solution: ``` N = int(input()) src = [int(input()) for i in range(N)] idx = {a:i for i,a in enumerate(src)} size = [1] * N ss = list(sorted(src)) es = [] while len(ss) > 1: a = ss.pop() k = size[idx[a]] b = a + 2*k - N if b == a or b not in idx: print(-1) exit() size[idx[b]] = k + 1 es.append((idx[a],idx[b])) for a,b in es: print(a+1, b+1) ```
instruction
0
34,977
13
69,954
No
output
1
34,977
13
69,955
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. Constraints * 2 \leq N \leq 100000 * 1 \leq D_i \leq 10^{12} * D_i are all distinct. Input Input is given from Standard Input in the following format: N D_1 D_2 : D_N Output If a tree with n vertices that satisfies the conditions does not exist, print `-1`. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. Examples Input 7 10 15 13 18 11 14 19 Output 1 2 1 3 1 5 3 4 5 6 6 7 Input 2 1 2 Output -1 Input 15 57 62 47 45 42 74 90 75 54 50 66 63 77 87 51 Output 1 10 1 11 2 8 2 15 3 5 3 9 4 5 4 10 5 15 6 12 6 14 7 13 9 12 11 13 Submitted Solution: ``` from collections import defaultdict N = int(input()) C = defaultdict(int) for i in range(N): D = int(input()) C[D] = i + 1 E = [] H = [1] * (N + 1) for D, n in sorted([[k, v] for k, v in C.items()], reverse=True)[:-1]: try: p = C[D - N + 2 * H[n]] if n == p: raise Error E.append([n, p]) H[p] += H[n] except: print(-1) break else: for e in E: print(e[0], e[1]) ```
instruction
0
34,978
13
69,956
No
output
1
34,978
13
69,957
Provide tags and a correct Python 3 solution for this coding contest problem. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
instruction
0
35,203
13
70,406
Tags: combinatorics, data structures, dp, math Correct Solution: ``` n = int(input()) + 1 res = 0 a = tuple(map(int, input().split())) for ai in a: res += ai * (n - ai) for ai, aj in map(sorted, zip(a, a[1:])): res -= ai * (n - aj) print(res) ### ```
output
1
35,203
13
70,407
Provide tags and a correct Python 3 solution for this coding contest problem. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
instruction
0
35,204
13
70,408
Tags: combinatorics, data structures, dp, math Correct Solution: ``` ## n = int(input()) + 1 res = 0 a = tuple(map(int, input().split())) for ai in a: res += ai * (n - ai) for ai, aj in map(sorted, zip(a, a[1:])): res -= ai * (n - aj) print(res) ## ```
output
1
35,204
13
70,409
Provide tags and a correct Python 3 solution for this coding contest problem. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
instruction
0
35,205
13
70,410
Tags: combinatorics, data structures, dp, math Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq,bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) 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") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n=int(input()) l=list(map(int,input().split())) x=l[0]-1 y=n-l[0] ans=(n*(n+1))//2-(x*(x+1))//2-(y*(y+1))//2 for i in range(1,n): if l[i]>l[i-1]: ans+=(n-l[i]+1)*(l[i]-l[i-1]) else: ans+=l[i]*(l[i-1]-l[i]) print(ans) ```
output
1
35,205
13
70,411
Provide tags and a correct Python 3 solution for this coding contest problem. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
instruction
0
35,206
13
70,412
Tags: combinatorics, data structures, dp, math Correct Solution: ``` n=int(input()) l=input().split() li=[int(i) for i in l] li.insert(0,0) ans=0 for i in range(1,n+1): if(li[i]>=li[i-1]): ans=ans+((li[i]-li[i-1])*(n-li[i]+1)) else: ans=ans+(li[i]*(li[i-1]-li[i])) print(ans) ```
output
1
35,206
13
70,413
Provide tags and a correct Python 3 solution for this coding contest problem. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
instruction
0
35,207
13
70,414
Tags: combinatorics, data structures, dp, math Correct Solution: ``` n = int(input()) + 1 res = 0 a = tuple(map(int, input().split())) for ai in a: res += ai * (n - ai) for ai, aj in map(sorted, zip(a, a[1:])): res -= ai * (n - aj) print(res) ##### ```
output
1
35,207
13
70,415
Provide tags and a correct Python 3 solution for this coding contest problem. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
instruction
0
35,208
13
70,416
Tags: combinatorics, data structures, dp, math Correct Solution: ``` n = int(input()) a = list(map(int,input().split())) ans = a[0] * (n-a[0]+1) for i in range(1, n): if a[i-1] == a[i]: continue elif a[i-1] < a[i]: ans+= (a[i]-a[i-1]) * (n-a[i]+1) elif a[i-1] > a[i]: ans+= a[i] * (a[i-1]-a[i]) print(ans) ```
output
1
35,208
13
70,417
Provide tags and a correct Python 3 solution for this coding contest problem. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
instruction
0
35,209
13
70,418
Tags: combinatorics, data structures, dp, math Correct Solution: ``` import sys input = sys.stdin.readline n=int(input()) A=[0]+list(map(int,input().split())) ANS=0 for i in range(1,n+1): if A[i]>A[i-1]: ANS+=(n-A[i]+1)*(A[i]-A[i-1]) else: ANS+=A[i]*(A[i-1]-A[i]) print(ANS) ```
output
1
35,209
13
70,419
Provide tags and a correct Python 3 solution for this coding contest problem. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
instruction
0
35,210
13
70,420
Tags: combinatorics, data structures, dp, math Correct Solution: ``` import sys n = int(sys.stdin.readline().strip()) a = list(map(int, sys.stdin.readline().strip().split())) s = a[0] * (n - a[0] + 1) for i in range (1, n): if a[i - 1] < a[i]: s = s + (a[i] - a[i-1]) * (n - a[i] + 1) if a[i - 1] > a[i]: s = s + a[i] * (a[i-1] - a[i]) print(s) ```
output
1
35,210
13
70,421
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11. Submitted Solution: ``` from math import sqrt, pow, ceil from decimal import * #getcontext().prec = 10 #l1 = list(input()) l1 = int(input()) #l2 = int(input()) #l3 = int(input()) #l1 = input().split() #l2 = input() l2 = input().split() #l2 = list(input()) #l1 = [int(i) for i in l1] l2 = [int(i) for i in l2] l2 = [0] + l2 ans = 0 for i in range (1, l1+1): ans+= l2[i] * (l1-l2[i]+1); for i in range (2, l1+1): ans -= (l1-max(l2[i],l2[i-1])+1) * (min(l2[i],l2[i-1])) print(ans) ```
instruction
0
35,211
13
70,422
Yes
output
1
35,211
13
70,423
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11. Submitted Solution: ``` n = int(input()) a = [0] + list(map(int, input().split())) ans = 0 for i, j in zip(a[:-1], a[1:]): if i < j: ans += (j - i) * (n - j + 1) else: ans += j * (i - j) print(ans) ```
instruction
0
35,212
13
70,424
Yes
output
1
35,212
13
70,425
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11. Submitted Solution: ``` """ #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict as dd, deque as dq, Counter as dc import math, string def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] MOD = 10**9+7 """ Adjacent pair contributes 1 to the answer every time that A[i] is in the range and A[i+1] is not """ def sum_evens(l,r): return pow(r,2,MOD) - pow(l,2,MOD) + r + l def sum_odds(l,r): return pow(r,2,MOD) - pow(l,2,MOD) + 2*l - 1 def solve(): N = getInt() A = [0] + getInts() ans = 0 for i in range(N): a, b = A[i], A[i+1] if a > b: ans += b*(a-b) else: ans += (b-a)*(N-b+1) return ans print(solve()) ```
instruction
0
35,213
13
70,426
Yes
output
1
35,213
13
70,427
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11. Submitted Solution: ``` n = int(input()) nS = [int(x) for x in input().split()] nS.insert(0, 0) answer = 0 for i in range(1, n + 1): if nS[i] > nS[i-1]: answer += (nS[i] - nS[i-1]) * (n - nS[i] + 1) else: answer += (nS[i-1] - nS[i]) * nS[i] print(answer) ```
instruction
0
35,214
13
70,428
Yes
output
1
35,214
13
70,429
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11. Submitted Solution: ``` def mp(): return map(int, input().split()) def f(i, j): global n, a c = 0 for q in range(n): if i <= a[q] <= j and not(i <= a[q + 1] <= j): c += 1 return c n = int(input()) a = list(mp()) + [10 ** 9] res = 0 ''' for i in range(n): for j in range(i, n): res += f(i + 1, j + 1) ''' for i in range(n - 1): x = a[i] y = a[i + 1] x, y = min(x, y), max(x, y) res += y - x res += (n - y + 1) * (y - x) #print(y - x, (n - y + 1) * (y - x)) print(res + 1) ```
instruction
0
35,215
13
70,430
No
output
1
35,215
13
70,431
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
35,216
13
70,432
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` n=int(input()) d=[0]*(n+1) for i in range(n-1): u,v=map(int,input().split()) d[u]+=1 d[v]+=1 n=n*d[u]*d[v]%998244353 print(n) ```
output
1
35,216
13
70,433
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
35,217
13
70,434
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` #import sys #sys.stdin = open('inD', 'r') n = int(input()) #a = [int(x) for x in input().split()] #n,m = map(int, input().split()) ans = n mod = 998244353 d = [0]*(n+1) for i in range(n-1): u,v = map(int, input().split()) d[u] += 1 d[v] += 1 ans = (ans * d[u] % mod) * d[v] % mod print(ans) ```
output
1
35,217
13
70,435
Provide tags and a correct Python 3 solution for this coding contest problem. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
instruction
0
35,218
13
70,436
Tags: combinatorics, dfs and similar, dp, trees Correct Solution: ``` from collections import Counter n = int(input()) f = [1] for i in range(1, n): f.append(f[-1] * i % 998244353) d = [] for _ in range(n-1): d.extend(input().split()) res = n for v in Counter(d).values(): res *= f[v] res %= 998244353 print(res) ```
output
1
35,218
13
70,437