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. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1
instruction
0
46,232
13
92,464
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` from itertools import combinations from sys import stdin import math def listIn(): return list((map(int,stdin.readline().strip().split()))) def stringIn(): return([x for x in stdin.readline().split()]) def intIn(): return (int(stdin.readline())) def ncr(n,k): res = 1 c = [0]*(k+1) c[0]=1 for i in range(1,n+1): for j in range(min(i,k),0,-1): c[j] = (c[j]+c[j-1])%MOD return c[k] n=intIn() p=listIn() s=listIn() p=[0]*2+p s=[0]+s if s.count(-1)==n-1: print(s[1]) else: tree={} par=[0]*(n+1) for i in range(2,n+1): if p[i] not in tree: tree[p[i]]=[i] else: tree[p[i]].append(i) par[i]=p[i] #print(tree) s2=s[:] for ver in tree: l=tree[ver] if s[ver]==-1: count=0 for child in l: if s[child]!=-1 and count==0: s2[ver]=s[child] count+=1 else: s2[ver]=min(s2[ver],s[child]) total=s2[1] #print(s2) flag=False for i in range(2,n+1): if s2[i]!=-1: if s2[par[i]]==-1: s2[par[i]]=s2[par[par[i]]] val=s2[i]-s2[par[i]] if val<0: flag=True break else: total+=val if flag: print(-1) else: print(total) ```
output
1
46,232
13
92,465
Provide tags and a correct Python 3 solution for this coding contest problem. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1
instruction
0
46,233
13
92,466
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` def solve(): n = int(input()) p = list(map(int, input().split(" "))) # 2...n s = list(map(int, input().split(" "))) # 1...n MAX_VAL = 10**9 + 2 v_child = [None] * n # 1...n for i, p_i in enumerate(p): idx = i + 1 if v_child[p_i - 1]: v_child[p_i - 1].append(idx) else: v_child[p_i - 1] = [idx] def fill_s(v_idx, parent_s): if s[v_idx] == -1 and v_idx != 0: s_for_ch = parent_s else: s_for_ch = s[v_idx] if v_child[v_idx]: min_ch_s = MAX_VAL for ch_idx in v_child[v_idx]: ch_s = fill_s(ch_idx, s_for_ch) if 0 <= ch_s < min_ch_s: min_ch_s = ch_s if s[v_idx] == -1: if min_ch_s != MAX_VAL: s[v_idx] = min_ch_s else: s[v_idx] = s_for_ch elif s[v_idx] > min_ch_s: # error raise ValueError("") elif s[v_idx] == -1 and v_idx != 0: s[v_idx] = parent_s return s[v_idx] def get_a(v_idx): p_idx = p[v_idx - 1] - 1 if s[v_idx] == -1: if v_idx == 0 or s[p_idx] == -1: return 0 s[v_idx] = s[p_idx] a = s[v_idx] if v_child[v_idx]: for ch_idx in v_child[v_idx]: ch_a = get_a(ch_idx) if ch_a < 0: raise ValueError("") a += ch_a if v_idx > 0: a -= s[p_idx] return a try: fill_s(0, 0) # print(s) print(get_a(0)) except Exception as e: print(-1) from sys import setrecursionlimit setrecursionlimit(2 * 10**5) import threading threading.stack_size(10**8) t = threading.Thread(target=solve) t.start() t.join() ```
output
1
46,233
13
92,467
Provide tags and a correct Python 3 solution for this coding contest problem. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1
instruction
0
46,234
13
92,468
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` def solution(n,p,v): sv = v[:] #print(sv) for i in range(1, n): if v[i] != -1: #still alive par = p[i] - 1 #parent index #updating if sv[par] == -1: sv[par] = v[i] else: sv[par] = min(sv[par], v[i])#for minimazing #print(sv) ans = sv[0] flag = True for i in range(1, n): if sv[i] != -1: a = sv[i] - sv[p[i] - 1] #child-parent should be >=0 because we are deepening by collecting values if a >= 0: ans += a else:#tree doesnt exist with given rules flag = False break if flag: return ans else: return -1 def main(): n=int(input()) parents=[0]+list(map(int,input().strip().split()))# == for len(values) values=list(map(int,input().strip().split())) print(solution(n,parents,values)) if __name__ == '__main__': main() ```
output
1
46,234
13
92,469
Provide tags and a correct Python 3 solution for this coding contest problem. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1
instruction
0
46,235
13
92,470
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial,gcd from collections import deque n=int(input()) l=list(map(int,input().split())) s=list(map(int,input().split())) graph={i:set() for i in range(1,n+1)} for i in range(n-1): graph[l[i]].add(i+2) level=[[] for i in range(n+2)] stack=[[1,1]] flag=1 while stack: x,y=stack.pop() level[y].append(x) for i in graph[x]: stack.append([i,y+1]) # print(level) ans=[0 for i in range(n+2)] ans[1]=s[0] for i in range(1,n+1): if i%2==0: for j in level[i]: papa=s[l[j-2]-1] if len(graph[j])==0: s[j-1]=papa ans[j]=0 else: mi=float("infinity") for k in graph[j]: mi=min(mi,s[k-1]) if s[k-1]<papa: flag=0 break ans[j]=mi-papa s[j-1]=papa+ans[j] else: if i>1: for j in level[i]: papa=s[l[j-2]-1] # print(papa) ans[j]=s[j-1]-papa # print(ans) if flag==0: print(-1) else: print(sum(ans)) ```
output
1
46,235
13
92,471
Provide tags and a correct Python 3 solution for this coding contest problem. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1
instruction
0
46,236
13
92,472
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` import sys n=int(input()) p=list(map(int,input().split())) s=list(map(int,input().split())) children=[] for i in range(n): children.append([]) for i in range(n-1): children[p[i]-1].append(i+1) a=[-1]*n a[0]=s[0] for i in range(1,n): if s[i]==-1: if not children[i]: s[i]=s[p[i-1]-1] else: k=10**10 for j in children[i]: k=min(k,s[j]) s[i]=k ans=a[0] for i in range(1,n): if s[p[i-1]-1]>s[i]: print(-1) sys.exit() ans+=s[i]-s[p[i-1]-1] print(ans) ```
output
1
46,236
13
92,473
Provide tags and a correct Python 3 solution for this coding contest problem. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1
instruction
0
46,237
13
92,474
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` import sys import math,bisect sys.setrecursionlimit(10 ** 6) from itertools import groupby,accumulate from heapq import heapify,heappop,heappush from collections import deque,Counter,defaultdict def I(): return int(sys.stdin.readline()) def neo(): return map(int, sys.stdin.readline().split()) def Neo(): return list(map(int, sys.stdin.readline().split())) n = I() parents = [0] + Neo() values = Neo() sv = values[:] for i in range(1,n): if values[i] != -1: par = parents[i] - 1 if sv[par] == -1: sv[par] = values[i] else: sv[par] = min(sv[par], values[i]) out = sv[0] works = True for i in range(1,n): if sv[i] != -1: a_val = sv[i] - sv[parents[i] - 1] if a_val >= 0: out += a_val else: works = False break if works: print(out) else: print(-1) ```
output
1
46,237
13
92,475
Provide tags and a correct Python 3 solution for this coding contest problem. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1
instruction
0
46,238
13
92,476
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` # -*- coding: utf-8 -*- # @Time : 2019/1/6 1:37 # @Author : LunaFire # @Email : gilgemesh2012@gmail.com # @File : D. Sum in the tree.py from collections import deque def main(): n = int(input()) p = list(map(int, input().split())) s = list(map(int, input().split())) s.insert(0, 0) a = [0] * len(s) a[1] = s[1] child_dict, parent_dict = {}, {} for i in range(len(p)): if p[i] not in child_dict: child_dict[p[i]] = [] child_dict[p[i]].append(i + 2) parent_dict[i + 2] = p[i] q = deque() q.append(1) while q: node = q.popleft() if s[node] == -1: if node not in child_dict or not child_dict[node]: s[node] = s[parent_dict[node]] else: s[node] = s[child_dict[node][0]] for x in child_dict[node]: s[node] = min(s[node], s[x]) if node in child_dict: for x in child_dict[node]: q.append(x) for i in range(2, n + 1): a[i] = s[i] - s[parent_dict[i]] if a[i] < 0: print(-1) return print(sum(a)) if __name__ == '__main__': main() ```
output
1
46,238
13
92,477
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1 Submitted Solution: ``` n,ans=int(input()),0 a=[0,0]+list(map(int,input().split())) s=[0]+[i if i!=-1 else 1e9+1 for i in map(int,input().split())] for i in range(1,n+1):s[a[i]]=min(s[a[i]],s[i]) for i in range(1,n+1): if s[a[i]]>s[i]:print(-1);exit() if s[i]==1e9+1:s[i]=s[a[i]] ans+=s[i]-s[a[i]] print(ans) ```
instruction
0
46,239
13
92,478
Yes
output
1
46,239
13
92,479
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1 Submitted Solution: ``` from collections import defaultdict n = int(input()) p = list(map(int, input().split())) s = list(map(int, input().split())) clds, pars = defaultdict(list), [0] * (n + 1) for i in range(n - 1): cur, par = i + 2, p[i] clds[p[i]].append(cur) pars[cur] = par ans, ok = s[0], True i, q = 0, [1] while i < len(q): cur = q[i] i += 1 par_v = s[pars[cur] - 1] if cur in clds: mmin, summ, k = float('inf'), 0, 0 for item in clds[cur]: mmin = min(mmin, s[item - 1]) summ += s[item - 1] k += 1 q.append(item) if s[cur - 1] != -1: continue if mmin < par_v: ok = False break ans -= par_v ans += (summ - (k - 1) * mmin) if ok: print(ans) else: print(-1) ```
instruction
0
46,240
13
92,480
Yes
output
1
46,240
13
92,481
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1 Submitted Solution: ``` from collections import * n=int(input()) fa=[0,0]+[int(i) for i in input().split()] s=[0]+[int(i) for i in input().split()] g=[[] for i in range(n+1)] for x in range(2,len(fa)): g[fa[x]].append(x) sub=[0]*(n+1) q=deque([1]) rcr=[] while(q): x=q.popleft() rcr.append(x) for y in g[x]: q.append(y) rcr.reverse() inf=int(1e10) s1=[inf if i==-1 else i for i in s] for x in rcr: sub[x]=s1[x] if g[x]: sub[x]=min(sub[x], min([sub[y] for y in g[x]]) ) dp=[0]*(n+1) a=[0]*(n+1) q=deque(g[1]) a[1] = s[1] if s[1]!=-1 else 0 dp[1]=a[1] ans=a[1] ok=1 while(q): x=q.popleft() if sub[x]==inf: a[x]=0 else: if s[x]==-1 : a[x]=sub[x]-dp[fa[x]] else : a[x]=s[x]-dp[fa[x]] if a[x]<0 : ok=0 break dp[x]=dp[fa[x]]+a[x] ans+=a[x] for y in g[x]: q.append(y) print(ans) if ok else print(-1) ```
instruction
0
46,241
13
92,482
Yes
output
1
46,241
13
92,483
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1 Submitted Solution: ``` n = int(input()) p = list(map(int,input().split())) ps = set(p) s = list(map(int,input().split())) ok = True for i in range(1, n + 1): if not i in ps: if s[i - 1] == -1: m = s[p[i - 2] - 1] else: m = s[i - 1] j = i while j != 1: if m < s[j - 1]: ok = False break if s[j - 1] != -1: m = s[j - 1] j = p[j - 2] if m < s[0]: ok = False if not ok: break if ok: sp = [-1] * n for i in range(n - 1): if sp[p[i] - 1] == -1: sp[p[i] - 1] = [i + 2] else: sp[p[i] - 1].append(i + 2) a = [0] * n a[0] = s[0] for i in range(1, n + 1): if s[i - 1] == -1 and sp[i - 1] != -1: m = s[sp[i - 1][0] - 1] - s[p[i - 2] - 1] for j in sp[i - 1]: m = min(m, s[j - 1] - s[p[i - 2] - 1]) a[i - 1] = m for i in range(2, n + 1): if s[i - 1] != -1: a[i - 1] = s[i - 1] - s[p[p[i - 2] - 2] - 1] - a[p[i - 2] - 1] print(sum(a)) else: print(-1) ```
instruction
0
46,242
13
92,484
Yes
output
1
46,242
13
92,485
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1 Submitted Solution: ``` # print(final) from collections import defaultdict def bfs(node): bool[node] = True queue = [node] ans = l[0] while queue!=[]: z = queue.pop(0) mini = 10**18 go = set() go1 = set() for i in hash[z]: if bool[i] == False: bool[i] = True queue.append(i) if l[par[i-1]-1] == -1: z1 = l[i-1]-l[par[par[i-1]-1]-1] # if i == 3: # print(l[i-1],par[par[i-1]-1]) mini = min(z1,mini) go.add(z1) if z1<0: print(-1) exit() elif l[i-1]!=-1: z1 = l[i-1]-l[par[i-1]-1] if z1<0: print(-1) exit() else: go1.add(z1) for i in go1: ans+=i for i in go: ans+=i-mini if go!=set(): ans+=mini return ans hash = defaultdict(list) n = int(input()) par = [1]+list(map(int,input().split())) l = list(map(int,input().split())) bool = [False]*(n+1) a = [-1]*(n+1) for i in range(1,n): hash[i+1].append(par[i]) hash[par[i]].append(i+1) ans = 0 print(bfs(1)) ```
instruction
0
46,243
13
92,486
No
output
1
46,243
13
92,487
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1 Submitted Solution: ``` from collections import defaultdict, deque def read_nums(): return [int(x) for x in input().split()] def parse_input(text, symbols='?*'): res = [] prev_index = 0 for index, char in enumerate(text): if char in symbols: res.append(('', text[prev_index: index - 1])) res.append((char, text[index - 1])) prev_index = index + 1 last_chunk = text[prev_index:] if len(last_chunk) != 0: res.append(('', last_chunk)) return res def calc_length(parsed_input): res = 0 for part in parsed_input: if part[0] == '': res += len(part[1]) return res def main(): n, = read_nums() graph = defaultdict(list) index = 2 for parent in read_nums(): graph[parent].append(index) index += 1 index = 1 vertex_values = {} for value in read_nums(): vertex_values[index] = value index += 1 output = {} if vertex_values[1] == -1: output[1] = 0 else: output[1] = vertex_values[1] d = deque() for ch in graph[1]: d.appendleft((ch, output[1])) # vertex, parent_sum while len(d) > 0: vertex, parent_sum = d.pop() value = vertex_values[vertex] if value != -1: if value < parent_sum: print(-1) exit(0) else: output[vertex] = value - parent_sum elif len(graph[vertex]) == 0: output[vertex] = 0 else: children_values = [vertex_values[ch] for ch in graph[vertex]] if any([x for x in children_values if x != -1 and x < parent_sum]): print(-1) exit(0) if all([vertex_values[x] == -1 for x in graph[vertex]]): output[vertex] = 0 else: output[vertex] = min([x for x in children_values if x != -1]) - parent_sum children = graph[vertex] for ch in children: d.appendleft((ch, parent_sum + output[vertex])) print(sum(output.values())) if __name__ == '__main__': main() ```
instruction
0
46,244
13
92,488
No
output
1
46,244
13
92,489
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1 Submitted Solution: ``` s=[] n=int(input()) l=list(map(int,input().split())) k=list(map(int,input().split())) itog=[] for i in range(n+1): itog.append(0) for i in range(n+1): s.append([]) for i in range(2,n+1): s[l[i-2]].append(i) k.insert(0,0) flag=True def gr(num,t,last): global flag global k global s if k[num]==-1 and last==-1: flag=False elif k[num]!=-1 and last!=-1: flag=False if flag and k[num]==-1: if len(s[num])!=0: itog[num]=k[s[num][0]]-t if itog[num]<0: flag=False if flag: for i in range(0,len(s[num])): gr(s[num][i],t+itog[num],-1) if len(s[num])==0: itog[num]=0 elif flag and k[num]!=-1: itog[num]=k[num]-t if itog[num]<0: flag=False for i in range(0,len(s[num])): gr(s[num][i],k[num],1) itog[1]=k[1] gr(1,0,-1) if flag: print(sum(itog)) else: print(-1) ```
instruction
0
46,245
13
92,490
No
output
1
46,245
13
92,491
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β‰₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β€” the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n β€” the number of vertices in the tree (2 ≀ n ≀ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≀ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≀ s_v ≀ 10^9), where erased values are replaced by -1. Output Output one integer β€” the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1 Submitted Solution: ``` import sys import math sys.setrecursionlimit(10**9) n = int(sys.stdin.readline()) g = list(map(int, sys.stdin.readline().split())) graphe = [[]for i in range(n)] for i in range(n-1): graphe[g[i]-1].append(i+2) somme = list(map(int, sys.stdin.readline().split())) a = [-1]*n if somme[0] == -1: somme[0] = 0 a[0]=somme[0] possible = True total = a[0] def dfs(noeud, pere): global g, somme, possible, total if somme[noeud-1] == -1: somme[noeud-1] = somme[pere] a[noeud-1] = 0 total += 0 for i in range(len(graphe[noeud-1])): dfs(graphe[noeud-1][i], noeud-1) elif somme[noeud-1] >= somme[pere]: a[noeud-1] = somme[noeud-1]-(somme[pere]) total += a[noeud-1] for i in range(len(graphe[noeud-1])): dfs(graphe[noeud-1][i], noeud-1) elif somme[noeud-1] < somme[pere]: possible = False return for i in range(len(graphe[0])): dfs(graphe[0][i], 0) if possible: print(total) else: print(-1) #print(somme) #print(a) ```
instruction
0
46,246
13
92,492
No
output
1
46,246
13
92,493
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Input The first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ 5) β€” the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≀ ai, bi ≀ n) β€” the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. Output Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Examples Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 Note In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). <image> There are <image> pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 3.
instruction
0
46,748
13
93,496
Tags: dfs and similar, dp, trees Correct Solution: ``` import sys input = sys.stdin.buffer.readline from collections import deque n, k = map(int, input().split()) tot_dist = 0 vis = [0]*(n+1) dist = [[[0]*2 for j in range(k)] for i in range(n+1)] adj = [[]for i in range(n+1)] for i in range(n-1): u,v = map(int,input().split()) adj[u].append(v) adj[v].append(u) s = deque([1]) while s: c = s[-1] if not vis[c]: vis[c] = 1 for ne in adj[c]: if not vis[ne]: s.append(ne) else: # update dists via pairing paths at the current node tot = [0]*k sum_dist = 0 pairable = 0 for ne in adj[c]: # direct jumps of exactly k tot_dist += pairable * sum([dist[ne][i][0] for i in range(k)]) + \ sum_dist * sum([dist[ne][i][1] for i in range(k)]) # extra from remainder mod k for i in range(k): for j in range(k): tot_dist += (i+j+2+k-1)//k*dist[ne][i][1]*tot[j] # update pairable nodes for i in range(k): tot[i]+= dist[ne][i][1] pairable += dist[ne][i][1] sum_dist += dist[ne][i][0] # update paths for ne in adj[c]: for i in range(k): for j in range(2): dist[c][i][j] += dist[ne][(i+k-1)%k][j] dist[c][0][0] += dist[ne][k-1][1] dist[c][0][1] += 1 # update dists from path directly to current node for i in range(k): tot_dist += dist[c][i][0] + (i+k-1)//k * dist[c][i][1] s.pop() print(tot_dist) ```
output
1
46,748
13
93,497
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Input The first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ 5) β€” the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≀ ai, bi ≀ n) β€” the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. Output Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. Examples Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 Note In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). <image> There are <image> pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 3.
instruction
0
46,749
13
93,498
Tags: dfs and similar, dp, trees Correct 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 """ Each edge goes from parent U to child V Edge appears on S_V * (N - S_V) paths For each path of length L, (L + (-L)%K)/K L%K 0, 1, 2, 3, 4 (K - L%K)%K K K-1 K-2 ... 0 K-1 K-2 ... """ def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def solve(): N, K = getInts() graph = dd(set) for i in range(N-1): A, B = getInts() graph[A].add(B) graph[B].add(A) dp_count = [[0 for j in range(5)] for i in range(N+1)] dp_total = [0 for j in range(N+1)] global ans ans = 0 @bootstrap def dfs(node,parent,depth): global ans dp_count[node][depth % K] = 1 dp_total[node] = 1 for neigh in graph[node]: if neigh != parent: yield dfs(neigh,node,depth+1) for i in range(K): for j in range(K): diff = (i+j-2*depth)%K req = (-diff)%K ans += req * dp_count[node][i] * dp_count[neigh][j] for i in range(K): dp_count[node][i] += dp_count[neigh][i] dp_total[node] += dp_total[neigh] ans += dp_total[node] * (N - dp_total[node]) yield dfs(1,-1,0) return ans//K print(solve()) ```
output
1
46,749
13
93,499
Provide tags and a correct Python 3 solution for this coding contest problem. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a Β«goodΒ» subset of edges of the graph or say, that it doesn't exist. Subset is called Β«goodΒ», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≀ n ≀ 3Β·105, n - 1 ≀ m ≀ 3Β·105) β€” number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≀ di ≀ 1) β€” numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≀ u, v ≀ n) β€” edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k β€” number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.
instruction
0
46,768
13
93,536
Tags: constructive algorithms, data structures, dfs and similar, dp, graphs Correct Solution: ``` import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys import heapq INF=10**9 def Dijkstra(graph, start,m): dist=[INF]*len(graph) parent=[INF]*len(graph) queue=[(0, start)] while queue: path_len, v=heapq.heappop(queue) if dist[v]==INF: dist[v]=path_len for w in graph[v]: if dist[w[0]]==INF: parent[w[0]]=[v,w[1]] heapq.heappush(queue, (dist[v]+1, w[0])) return (dist,parent) n,m=map(int,input().split()) d=list(map(int,input().split())) graph=[] for i in range(n): graph.append([]) for i in range(m): u,v=map(int,input().split()) graph[u-1].append([v-1,i]) graph[v-1].append([u-1,i]) count=0 flag=0 for i in range(n): if d[i]==1: count+=1 elif d[i]==-1: flag=1 if count%2==1 and flag==0: print(-1) sys.exit() if count%2==1: for i in range(n): if d[i]==-1 and flag==1: d[i]=1 flag=0 elif d[i]==-1: d[i]=0 else: for i in range(n): if d[i]==-1: d[i]=0 dist,parent=Dijkstra(graph,0,m) actualused=[0]*m children=[0]*n actualchildren=[0]*n for i in range(1,n): children[parent[i][0]]+=1 stack=[] for i in range(n): if children[i]==actualchildren[i]: stack.append(i) while stack: curr=stack.pop() if curr==0: break p=parent[curr] k=p[0] if d[curr]==1: actualused[p[1]]=1 d[k]=1-d[k] actualchildren[k]+=1 if actualchildren[k]==children[k]: stack.append(k) ans=[] for i in range(m): if actualused[i]: ans.append(str(i+1)) print(len(ans)) print(' '.join(ans)) ```
output
1
46,768
13
93,537
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a Β«goodΒ» subset of edges of the graph or say, that it doesn't exist. Subset is called Β«goodΒ», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≀ n ≀ 3Β·105, n - 1 ≀ m ≀ 3Β·105) β€” number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≀ di ≀ 1) β€” numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≀ u, v ≀ n) β€” edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k β€” number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1. Submitted Solution: ``` import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys import heapq INF=10**9 def Dijkstra(graph, start,m): dist=[INF]*len(graph) parent=[INF]*len(graph) queue=[(0, start)] while queue: path_len, v=heapq.heappop(queue) if dist[v]==INF: dist[v]=path_len for w in graph[v]: if dist[w[0]]==INF: parent[w[0]]=[v,w[1]] heapq.heappush(queue, (dist[v]+1, w[0])) return (dist,parent) n,m=map(int,input().split()) d=list(map(int,input().split())) edges=[] uses=[0]*m graph=[] for i in range(n): graph.append([]) for i in range(m): u,v=map(int,input().split()) graph[u-1].append([v-1,i]) graph[v-1].append([u-1,i]) count=0 flag=0 for i in range(n): if d[i]==1: count+=1 elif d[i]==-1: flag=1 if count%2==1 and flag==0: print(-1) sys.exit() if count%2==1: for i in range(n): if d[i]==-1 and flag==1: d[i]=1 flag=0 elif d[i]==-1: d[i]=0 dist,parent=Dijkstra(graph,0,m) actualused=[0]*m children=[0]*n actualchildren=[0]*n for i in range(1,n): children[parent[i][0]]+=1 stack=[] for i in range(n): if children[i]==actualchildren[i]: stack.append(i) while stack: curr=stack.pop() if curr==0: break p=parent[curr] k=p[0] if d[curr]==1: actualused[p[1]]=1 d[k]=1-d[k] actualchildren[k]+=1 if actualchildren[k]==children[k]: stack.append(k) ans=[] for i in range(m): if actualused[i]: ans.append(str(i+1)) print(len(ans)) print(' '.join(ans)) ```
instruction
0
46,769
13
93,538
No
output
1
46,769
13
93,539
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem. You are given a tree with n vertices. In each vertex v there is positive integer a_{v}. You have to answer q queries. Each query has a from u v x. You have to calculate ∏_{w ∈ P} gcd(x, a_{w}) mod (10^{9} + 7), where P is a set of vertices on path from u to v. In other words, you are to calculate the product of gcd(x, a_{w}) for all vertices w on the path from u to v. As it might be large, compute it modulo 10^9+7. Here gcd(s, t) denotes the greatest common divisor of s and t. Note that the numbers in vertices do not change after queries. I suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them. Input In the first line of input there is one integer n (1 ≀ n ≀ 10^{5}) β€” the size of the tree. In the next n-1 lines the edges of the tree are described. The i-th edge is described with two integers u_{i} and v_{i} (1 ≀ u_{i}, v_{i} ≀ n) and it connects the vertices u_{i} and v_{i}. It is guaranteed that graph with these edges is a tree. In the next line there are n integers a_1, a_2, …, a_n (1 ≀ a_{v} ≀ 10^{7}). In the next line there is one integer q (1 ≀ q ≀ 10^{5}) β€” the number of queries. And in the next q lines the queries are described. Each query is described with three integers u_{i}, v_{i} and x_{i} (1 ≀ u_{i}, v_{i} ≀ n, 1 ≀ x_{i} ≀ 10^{7}). Output Print q numbers β€” the answers to the queries in the order they are given in the input. Print each answer modulo 10^9+7 = 1000000007. Print each number on a separate line. Examples Input 4 1 2 1 3 1 4 6 4 9 5 3 2 3 6 2 3 2 3 4 7 Output 36 4 1 Input 6 1 2 2 3 2 4 1 5 5 6 100000 200000 500000 40000 800000 250000 3 3 5 10000000 6 2 3500000 4 1 64000 Output 196000 12250 999998215 Submitted Solution: ``` n = int(input()) num = list(map(int, input().split())) res = 0 for i in range(len(num)): res += (num[i] == (i - 1)) if (res < 2): print('Petr') else: print('Um_nik') ```
instruction
0
46,824
13
93,648
No
output
1
46,824
13
93,649
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem. You are given a tree with n vertices. In each vertex v there is positive integer a_{v}. You have to answer q queries. Each query has a from u v x. You have to calculate ∏_{w ∈ P} gcd(x, a_{w}) mod (10^{9} + 7), where P is a set of vertices on path from u to v. In other words, you are to calculate the product of gcd(x, a_{w}) for all vertices w on the path from u to v. As it might be large, compute it modulo 10^9+7. Here gcd(s, t) denotes the greatest common divisor of s and t. Note that the numbers in vertices do not change after queries. I suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them. Input In the first line of input there is one integer n (1 ≀ n ≀ 10^{5}) β€” the size of the tree. In the next n-1 lines the edges of the tree are described. The i-th edge is described with two integers u_{i} and v_{i} (1 ≀ u_{i}, v_{i} ≀ n) and it connects the vertices u_{i} and v_{i}. It is guaranteed that graph with these edges is a tree. In the next line there are n integers a_1, a_2, …, a_n (1 ≀ a_{v} ≀ 10^{7}). In the next line there is one integer q (1 ≀ q ≀ 10^{5}) β€” the number of queries. And in the next q lines the queries are described. Each query is described with three integers u_{i}, v_{i} and x_{i} (1 ≀ u_{i}, v_{i} ≀ n, 1 ≀ x_{i} ≀ 10^{7}). Output Print q numbers β€” the answers to the queries in the order they are given in the input. Print each answer modulo 10^9+7 = 1000000007. Print each number on a separate line. Examples Input 4 1 2 1 3 1 4 6 4 9 5 3 2 3 6 2 3 2 3 4 7 Output 36 4 1 Input 6 1 2 2 3 2 4 1 5 5 6 100000 200000 500000 40000 800000 250000 3 3 5 10000000 6 2 3500000 4 1 64000 Output 196000 12250 999998215 Submitted Solution: ``` n = int(input()) num = list(map(int, input().split())) res = 0 for i in range(len(num)): res += (num[i] != (i - 1)) if not (res < 2): print('Petr') else: print('Um_nik') ```
instruction
0
46,825
13
93,650
No
output
1
46,825
13
93,651
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem. You are given a tree with n vertices. In each vertex v there is positive integer a_{v}. You have to answer q queries. Each query has a from u v x. You have to calculate ∏_{w ∈ P} gcd(x, a_{w}) mod (10^{9} + 7), where P is a set of vertices on path from u to v. In other words, you are to calculate the product of gcd(x, a_{w}) for all vertices w on the path from u to v. As it might be large, compute it modulo 10^9+7. Here gcd(s, t) denotes the greatest common divisor of s and t. Note that the numbers in vertices do not change after queries. I suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them. Input In the first line of input there is one integer n (1 ≀ n ≀ 10^{5}) β€” the size of the tree. In the next n-1 lines the edges of the tree are described. The i-th edge is described with two integers u_{i} and v_{i} (1 ≀ u_{i}, v_{i} ≀ n) and it connects the vertices u_{i} and v_{i}. It is guaranteed that graph with these edges is a tree. In the next line there are n integers a_1, a_2, …, a_n (1 ≀ a_{v} ≀ 10^{7}). In the next line there is one integer q (1 ≀ q ≀ 10^{5}) β€” the number of queries. And in the next q lines the queries are described. Each query is described with three integers u_{i}, v_{i} and x_{i} (1 ≀ u_{i}, v_{i} ≀ n, 1 ≀ x_{i} ≀ 10^{7}). Output Print q numbers β€” the answers to the queries in the order they are given in the input. Print each answer modulo 10^9+7 = 1000000007. Print each number on a separate line. Examples Input 4 1 2 1 3 1 4 6 4 9 5 3 2 3 6 2 3 2 3 4 7 Output 36 4 1 Input 6 1 2 2 3 2 4 1 5 5 6 100000 200000 500000 40000 800000 250000 3 3 5 10000000 6 2 3500000 4 1 64000 Output 196000 12250 999998215 Submitted Solution: ``` n = int(input()) num = list(map(int, input().split())) res = 0 for i in range(len(num)): res += (num[i] == (i - 1)) if not (res < 2): print('Petr') else: print('Um_nik') ```
instruction
0
46,826
13
93,652
No
output
1
46,826
13
93,653
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem. You are given a tree with n vertices. In each vertex v there is positive integer a_{v}. You have to answer q queries. Each query has a from u v x. You have to calculate ∏_{w ∈ P} gcd(x, a_{w}) mod (10^{9} + 7), where P is a set of vertices on path from u to v. In other words, you are to calculate the product of gcd(x, a_{w}) for all vertices w on the path from u to v. As it might be large, compute it modulo 10^9+7. Here gcd(s, t) denotes the greatest common divisor of s and t. Note that the numbers in vertices do not change after queries. I suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them. Input In the first line of input there is one integer n (1 ≀ n ≀ 10^{5}) β€” the size of the tree. In the next n-1 lines the edges of the tree are described. The i-th edge is described with two integers u_{i} and v_{i} (1 ≀ u_{i}, v_{i} ≀ n) and it connects the vertices u_{i} and v_{i}. It is guaranteed that graph with these edges is a tree. In the next line there are n integers a_1, a_2, …, a_n (1 ≀ a_{v} ≀ 10^{7}). In the next line there is one integer q (1 ≀ q ≀ 10^{5}) β€” the number of queries. And in the next q lines the queries are described. Each query is described with three integers u_{i}, v_{i} and x_{i} (1 ≀ u_{i}, v_{i} ≀ n, 1 ≀ x_{i} ≀ 10^{7}). Output Print q numbers β€” the answers to the queries in the order they are given in the input. Print each answer modulo 10^9+7 = 1000000007. Print each number on a separate line. Examples Input 4 1 2 1 3 1 4 6 4 9 5 3 2 3 6 2 3 2 3 4 7 Output 36 4 1 Input 6 1 2 2 3 2 4 1 5 5 6 100000 200000 500000 40000 800000 250000 3 3 5 10000000 6 2 3500000 4 1 64000 Output 196000 12250 999998215 Submitted Solution: ``` 1 ```
instruction
0
46,827
13
93,654
No
output
1
46,827
13
93,655
Provide a correct Python 3 solution for this coding contest problem. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3
instruction
0
47,004
13
94,008
"Correct Solution: ``` from sys import stdin from collections import defaultdict readline = stdin.readline def main(): v, e = map(int, readline().split()) g = defaultdict(set) residual = [[0] * v for _ in range(v)] source, sink = 0, v - 1 for _ in range(e): s, t, c = map(int, readline().split()) if 0 < c and s != sink and t != source: g[s] |= {t} g[t] |= {s} residual[s][t] = c while True: route, flow = search(g, residual, source, sink) if not route: break for s, t in zip(route, route[1:]): residual[s][t] -= flow residual[t][s] += flow print(sum(residual[sink][i] for i in g[sink])) def search(g, residual, source, sink): dfs_stack = [(source, None, float('inf'))] route = [None] visited = set() while dfs_stack: u, prev, flow = dfs_stack.pop() while route[-1] != prev: route.pop() route.append(u) visited |= {u} if u == sink: return route[1:], flow for v in g[u]: if v not in visited and 0 < residual[u][v]: dfs_stack.append((v, u, min(residual[u][v], flow))) return [], 0 main() ```
output
1
47,004
13
94,009
Provide a correct Python 3 solution for this coding contest problem. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3
instruction
0
47,005
13
94,010
"Correct Solution: ``` import sys from collections import deque class MaxFlow: class Edge: def __init__(self, to, cap, rev): self.to, self.cap, self.rev = to, cap, rev def __init__(self, node_size, inf): self._node = node_size self._inf = inf self._level = [-1]*self._node self._iter = [0]*self._node self._graph = [[] for _ in range(self._node)] def add_edge(self, from_, to, cap): self._graph[from_].append(self.Edge(to, cap, len(self._graph[to]))) self._graph[to].append(self.Edge(from_, 0, len(self._graph[from_])-1)) def bfs(self, start): self._level = [-1]*self._node que = deque() self._level[start] = 0 que.append(start) while que: cur_vertex = que.popleft() for e in self._graph[cur_vertex]: if e.cap > 0 > self._level[e.to]: self._level[e.to] = self._level[cur_vertex] + 1 que.append(e.to) def dfs(self, cur_vertex, end_vertex, flow): if cur_vertex == end_vertex: return flow while self._iter[cur_vertex] < len(self._graph[cur_vertex]): e = self._graph[cur_vertex][self._iter[cur_vertex]] if e.cap > 0 and self._level[cur_vertex] < self._level[e.to]: flowed = self.dfs(e.to, end_vertex, min(flow, e.cap)) if flowed > 0: e.cap -= flowed self._graph[e.to][e.rev].cap += flowed return flowed self._iter[cur_vertex] += 1 return 0 def solve(self, source, sink): flow = 0 while True: self.bfs(source) if self._level[sink] < 0: return flow self._iter = [0]*self._node while True: f = self.dfs(source, sink, self._inf) if f == 0: break flow += f if __name__ == '__main__': n, m = map(int, sys.stdin.readline().split()) mf = MaxFlow(n, 10**10) for _ in range(m): u, v, c = map(int, sys.stdin.readline().split()) mf.add_edge(u, v, c) print(mf.solve(0, n-1)) ```
output
1
47,005
13
94,011
Provide a correct Python 3 solution for this coding contest problem. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3
instruction
0
47,006
13
94,012
"Correct Solution: ``` INF = 10**12 N = 101 class FordFulkerson: def __init__(self): self.G = [[] for _ in range(N)] self.used = [False] * N def add_edge(self, s, t, c): self.G[s].append([t, c, len(self.G[t])]) self.G[t].append([s, 0, len(self.G[s])-1]) def dfs(self, s, t, f): if s == t: return f self.used[s] = True for i in range(len(self.G[s])): e = self.G[s][i] if not self.used[e[0]] and e[1] > 0: d = self.dfs(e[0], t, min(f, e[1])) if d > 0: self.G[s][i][1] -= d self.G[e[0]][e[2]][1] += d return d return 0 def max_flow(self, s, t): flow = 0 while True: self.used = [False]*N f = self.dfs(s, t, INF) if f == 0: return flow flow += f if __name__ == "__main__": V, E = map(int, input().split()) ff = FordFulkerson() for i in range(E): u, v, c = map(int, input().split()) ff.add_edge(u, v, c) print(ff.max_flow(0, V-1)) ```
output
1
47,006
13
94,013
Provide a correct Python 3 solution for this coding contest problem. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3
instruction
0
47,007
13
94,014
"Correct Solution: ``` import sys,collections sys.setrecursionlimit(10000) INF = float("inf") V,E = map(int,sys.stdin.readline().split()) uvc = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(E)) # multi line with multi param #uvc = [[0,1,1],[0,2,3],[1,2,1],[2,3,2]] G = {i:{} for i in range(V)} mG = {i:{} for i in range(V)} for u,v,c in uvc: G[u][v] = c G[v][u] = 0 mG[u][v] = 0 mG[v][u] = 0 #print(G) def dfs(current,flow): #print(current) if current == V-1: return flow visited.add(current) if not G[current]: return 0 for nex,nex_c in G[current].items(): if not nex in visited and nex_c != 0: f = dfs(nex,min(flow,nex_c)) if f != 0: #print(current,nex,nex_c,f) mG[current][nex] = mG[current][nex] + f G[current][nex] = G[current][nex] - f G[nex][current] = G[nex][current] + f return f return 0 visited = set() while dfs(0,INF) != 0: visited = set() #print("mG:",mG) #print("G:",G) pass print(sum(mG[0].values())) ```
output
1
47,007
13
94,015
Provide a correct Python 3 solution for this coding contest problem. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3
instruction
0
47,008
13
94,016
"Correct Solution: ``` import sys sys.setrecursionlimit(200000) n,e = map(int,input().split()) g = [[] for i in range(n)] for i in range(e): a,b,c = map(int,input().split()) g[a].append([b,c,len(g[b])]) g[b].append([a,0,len(g[a])-1]) def dfs(x,t,f): if x == t: return f global used used[x] = 1 for j in range(len(g[x])): y, cap, rev = g[x][j] if cap and not used[y]: d = dfs(y,t,min(f,cap)) if d: g[x][j][1] -= d g[y][rev][1] += d return d return 0 flow = 0 f = INF = float("inf") while f: used = [0]*n f = dfs(0,n-1,INF) flow += f print(flow) ```
output
1
47,008
13
94,017
Provide a correct Python 3 solution for this coding contest problem. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3
instruction
0
47,009
13
94,018
"Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 output: 3 """ import sys from collections import deque def bfs(source, target, parent): queue = deque() queue.appendleft(source) visited = [False] * v_num visited[source] = True while queue: current = queue.popleft() for adj, cp in adj_table[current].items(): if cp and not visited[adj]: queue.append(adj) visited[adj] = True parent[adj] = current return True if visited[target] else False def graph_FordFulkerson(source, sink): parent = [-1] * v_num max_flow = 0 while bfs(source, sink, parent): path_flow = float('inf') bk_1 = sink while bk_1 != source: parent_bk_1 = parent[bk_1] assert parent_bk_1 != -1 path_flow = min(path_flow, adj_table[parent_bk_1][bk_1]) bk_1 = parent[bk_1] max_flow += path_flow bk_2 = sink while bk_2 != source: parent_bk_2 = parent[bk_2] assert parent_bk_2 != -1 adj_table[bk_2].setdefault(parent_bk_2, 0) adj_table[parent_bk_2][bk_2] -= path_flow adj_table[bk_2][parent_bk_2] += path_flow bk_2 = parent[bk_2] return max_flow if __name__ == '__main__': _input = sys.stdin.readlines() v_num, e_num = map(int, _input[0].split()) edges = map(lambda x: x.split(), _input[1:]) adj_table = tuple(dict() for _ in range(v_num)) for edge in edges: s, t, c = map(int, edge) adj_table[s][t] = c print(graph_FordFulkerson(source=0, sink=v_num - 1)) ```
output
1
47,009
13
94,019
Provide a correct Python 3 solution for this coding contest problem. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3
instruction
0
47,010
13
94,020
"Correct Solution: ``` import collections def bfs(u, n): global level, network level = [-1] * n deq = collections.deque() level[u] = 0 deq.append(u) while deq: v = deq.popleft() for w, c, l in network[v]: if c > 0 and level[w] < 0: level[w] = level[v] + 1 deq.append(w) def dfs(u, t, f): global it, level, network if u == t: return f for i in range(it[u], len(network[u])): v, c, l = network[u][i] if c <= 0 or level[u] >= level[v]: continue d = dfs(v, t, min(f, c)) if d <= 0: continue network[u][i][1] -= d network[v][l][1] += d it[u] = i return d it[u] = len(network[u]) return 0 def max_flow(s, t, n): global it, level flow = 0 while True: bfs(s, n) if level[t] < 0: return flow it = [0] * n while True: f = dfs(s, t, 1e10) if f > 0: flow += f else: break return flow n, m = map(int, input().split()) network = [[] for _ in range(n)] for _ in range(m): u, v, c = map(int, input().split()) network[u].append([v, c, len(network[v])]) network[v].append([u, 0, len(network[u]) - 1]) level = [-1] * n it = [0] * n print(max_flow(0, n - 1, n)) ```
output
1
47,010
13
94,021
Provide a correct Python 3 solution for this coding contest problem. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3
instruction
0
47,011
13
94,022
"Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 output: 3 """ import sys from collections import deque def graph_bfs(source, target, parent): visited = [False] * v_num queue = deque() queue.appendleft(source) visited[source] = True while queue: current = queue.popleft() for adj, cp in adj_table[current].items(): if cp and not visited[adj]: queue.append(adj) visited[adj] = True parent[adj] = current return True if visited[target] else False def graphFordFulkerson(source, sink): parent = [-1] * v_num max_flow = 0 while graph_bfs(source, sink, parent): path_flow = float('inf') bk_1 = sink while bk_1 is not source: parent_bk_1 = parent[bk_1] assert parent_bk_1 != -1 path_flow = min(path_flow, adj_table[parent_bk_1][bk_1]) bk_1 = parent[bk_1] max_flow += path_flow bk_2 = sink while bk_2 is not source: parent_bk_2 = parent[bk_2] assert parent_bk_2 != -1 # adj_table[parent_bk_2].setdefault(bk_2, 0) adj_table[bk_2].setdefault(parent_bk_2, 0) # print(bk_2, parent_bk_2, path_flow, bk_1, parent[bk_1], parent, adj_table) adj_table[parent_bk_2][bk_2] -= path_flow adj_table[bk_2][parent_bk_2] += path_flow bk_2 = parent[bk_2] return max_flow def generate_adj_table(_edges): for edge in _edges: source, target, cp = map(int, edge) init_adj_table[source][target] = cp return init_adj_table if __name__ == '__main__': _input = sys.stdin.readlines() v_num, e_num = map(int, _input[0].split()) edges = map(lambda x: x.split(), _input[1:]) init_adj_table = [dict() for _ in range(v_num)] adj_table = generate_adj_table(edges) ans = graphFordFulkerson(source=0, sink=v_num - 1) print(ans) ```
output
1
47,011
13
94,023
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3 Submitted Solution: ``` # Acceptance of input import sys file_input = sys.stdin V, E = map(int, file_input.readline().split()) adj_mat = [[0] * V for i in range(V)] for line in file_input: u, v, c = map(int, line.split()) adj_mat[u][v] = c # Ford???Fulkerson algorithm import collections # BFS for residual capacity network def bfs(start, goal, parent): unvisited = [True] * V queue = collections.deque() queue.append(start) unvisited[start] = False while queue: u = queue.popleft() for v, r_capacity in enumerate(adj_mat[u]): if unvisited[v] and (r_capacity > 0): queue.append(v) unvisited[v] = False parent[v] = u if v == goal: return not unvisited[goal] def ford_fulkerson(source, sink): parent = [None] * V max_flow = 0 while bfs(source, sink, parent): aug_path_flow = 10000 v = sink while (v != source): aug_path_flow = min(aug_path_flow, adj_mat[parent[v]][v]) v = parent[v] max_flow += aug_path_flow v = sink while (v != source): u = parent[v] adj_mat[u][v] -= aug_path_flow adj_mat[v][u] += aug_path_flow v = u return max_flow # output print(ford_fulkerson(0, V - 1)) ```
instruction
0
47,012
13
94,024
Yes
output
1
47,012
13
94,025
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3 Submitted Solution: ``` import sys, re from collections import deque, defaultdict, Counter from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement from operator import itemgetter, mul from copy import deepcopy from string import ascii_lowercase, ascii_uppercase, digits from bisect import bisect, bisect_left from fractions import gcd from heapq import heappush, heappop from functools import reduce def input(): return sys.stdin.readline().strip() def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(): return list(map(int, input().split())) def ZIP(n): return zip(*(MAP() for _ in range(n))) sys.setrecursionlimit(10 ** 9) INF = float('inf') mod = 10 ** 9 + 7 class Dinic: def __init__(self,v, inf =10**10): self.v = v self.inf = inf self.G = [[] for _ in range(v)] self.level = [-1]*v self.ite = [0]*v def add_edge(self, fr, to, cap): self.G[fr].append([to,cap,len(self.G[to])]) self.G[to].append([fr,0,len(self.G[fr])-1]) def bfs(self,s): self.level = [-1]*self.v self.level[s] = 0 Q = deque() Q.append(s) while Q: v = Q.popleft() for i in range(len(self.G[v])): e = self.G[v][i] if e[1]>0 and self.level[e[0]]<0: self.level[e[0]] = self.level[v]+1 Q.append(e[0]) def dfs(self,v,t,f): if v==t: return f for i in range(self.ite[v],len(self.G[v])): self.ite[v] = i e = self.G[v][i] if e[1]>0 and self.level[v]<self.level[e[0]]: d = self.dfs(e[0],t,min(f,e[1])) if d>0: e[1] -= d self.G[e[0]][e[2]][1] += d return d return 0 def max_flow(self,s,t): flow = 0 while True: self.bfs(s) if self.level[t]<0: return flow self.ite = [0]*self.v f =self.dfs(s,t,self.inf) while f>0: flow+= f f = self.dfs(s,t,self.inf) V, E = MAP() D = Dinic(V) for _ in range(E): u, v, c = MAP() D.add_edge(u, v, c) ans = D.max_flow(0, V-1) print(ans) ```
instruction
0
47,013
13
94,026
Yes
output
1
47,013
13
94,027
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3 Submitted Solution: ``` V, E = map(int, input().split()) # -*- coding: utf-8 -*- import collections import queue class Dinic: def __init__(self, N): self.N = N self.edges = collections.defaultdict(list) self.level = [0 for _ in range(self.N)] self.iter = [0 for _ in range(self.N)] def add(self, u, v, c, directed=True): """ 0-indexed u = from, v = to, c = cap directed = Trueγͺγ‚‰γ€ζœ‰ε‘γ‚°γƒ©γƒ•γ§γ‚γ‚‹ """ if directed: self.edges[u].append([v, c, len(self.edges[v])]) self.edges[v].append([u, 0, len(self.edges[u])-1]) else: # TODO self.edges[u].append([v, c, len(self.edges[u])]) def bfs(self, s): self.level = [-1 for _ in range(self.N)] self.level[s] = 0 que = queue.Queue() que.put(s) while not que.empty(): v = que.get(s) for i in range(len(self.edges[v])): e = self.edges[v][i] if e[1] > 0 and self.level[e[0]] < 0: self.level[e[0]] = self.level[v] + 1 que.put(e[0]) def dfs(self, v, t, f): if v == t: return f for i in range(self.iter[v], len(self.edges[v])): self.iter[v] = i e = self.edges[v][i] if e[1] > 0 and self.level[v] < self.level[e[0]]: d = self.dfs(e[0], t, min(f, e[1])) if d > 0: e[1] -= d self.edges[e[0]][e[2]][1] += d return d return 0 def maxFlow(self, s, t): flow = 0 while True: self.bfs(s) if self.level[t] < 0: return flow self.iter = [0 for _ in range(self.N)] f = self.dfs(s, t, float('inf')) while f > 0: flow += f f = self.dfs(s, t, float('inf')) graph = Dinic(V) for i in range(E): u, v, c = map(int, input().split()) graph.add(u, v, c) print(graph.maxFlow(0, V-1)) ```
instruction
0
47,014
13
94,028
Yes
output
1
47,014
13
94,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3 Submitted Solution: ``` from collections import deque class Dinic: def __init__(self, N): self.N = N self.edges = [[] for _ in range(N)] self.level = None self.iter = None def add_edges(self, u, v, cap): self.edges[u].append([v, cap, len(self.edges[v])]) self.edges[v].append([u, 0, len(self.edges[u]) - 1]) def bfs(self, s): self.level = [-1] * self.N self.level[s] = 0 q = deque([s]) while q: cur = q.popleft() for nxt, cap, _ in self.edges[cur]: if cap > 0 > self.level[nxt]: self.level[nxt] = self.level[cur] + 1 q.append(nxt) def dfs(self, s, flow): if s == self.end: return flow for i in range(self.iter[s], len(self.edges[s])): self.iter[s] = i to, cap, opp = self.edges[s][i] if cap > 0 and self.level[s] < self.level[to]: d = self.dfs(to, cap if cap < flow else flow) if d > 0: self.edges[s][i][1] -= d self.edges[to][opp][1] += d return d return 0 def maximum_flow(self, source, end): self.end = end max_flow = 0 INF = float('inf') while True: self.bfs(source) if self.level[end] < 0: return max_flow self.iter = [0] * self.N flow = self.dfs(source, INF) while flow: max_flow += flow flow = self.dfs(source, INF) v, e, *L = map(int, open(0).read().split()) dinic = Dinic(v) for s, t, c in zip(*[iter(L)] * 3): dinic.add_edges(s, t, c) print(dinic.maximum_flow(0, v - 1)) ```
instruction
0
47,015
13
94,030
Yes
output
1
47,015
13
94,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3 Submitted Solution: ``` from collections import deque class Dinic: """Dinic Algorithm: find max-flow complexity: O(EV^2) """ class edge: def __init__(self, to, cap, rev): self.to, self.cap, self.rev = to, cap, rev def __init__(self, V, E, source, sink): """ V: the number of vertexes E: adjacency list source: start point sink: goal point """ self.V = V self.E = [[] for _ in range(V)] for fr in range(V): for to, cap in E[fr]: self.E[fr].append(self.edge(to, cap, len(self.E[to]))) self.E[to].append(self.edge(fr, 0, len(self.E[fr])-1)) self.maxflow = self.dinic(source, sink) def dinic(self, source, sink): """find max-flow""" INF = float('inf') maxflow = 0 while True: self.bfs(source) if self.level[sink] < 0: return maxflow self.itr = [0] * self.V while True: flow = self.dfs(source, sink, INF) if flow > 0: maxflow += flow else: break def dfs(self, vertex, sink, flow): """find augmenting path""" if vertex == sink: return flow for i in range(self.itr[v], len(self.E[vertex])): self.itr[v] = i e = self.E[vertex][i] if e.cap > 0 and self.level[vertex] < self.level[e.to]: d = self.dfs(e.to, sink, min(flow, e.cap)) if d > 0: self.E[vertex][i] -= d self.E[e.to][e.rev].cap += d return d return 0 def bfs(self, start): """find shortest path from start""" que = deque() self.level = [-1] * self.V que.append(start) self.level[start] = 0 while que: fr = que.popleft() for e in self.E[fr]: if e.cap > 0 and self.level[e.to] < 0: self.level[e.to] = self.level[fr] + 1 que.append(e.to) V, E = map(int, input().split()) edge = [[] for _ in range(V)] for _ in range(E): u, v, cap = map(int, input().split()) edge[u].append((v, cap)) print(Dinic(V, edge, 0, V-1).maxflow) ```
instruction
0
47,016
13
94,032
No
output
1
47,016
13
94,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3 Submitted Solution: ``` from sys import stdin from collections import defaultdict readline = stdin.readline #readline = open('???.txt').readline def main(): v, e = map(int, readline().split()) g = defaultdict(list) residual = [[0] * v for _ in range(v)] source, sink = 0, v - 1 for _ in range(e): s, t, c = map(int, readline().split()) if 0 < c: g[s].append(t) g[t].append(s) residual[s][t] = c capacity = sum(residual[source][i] for i in g[source]) while True: route, flow = search(g, residual, source, sink) if route is None: break for i in range(1, len(route)): residual[route[i - 1]][route[i]] -= flow residual[route[i]][route[i - 1]] += flow print(capacity - sum(residual[source][i] for i in g[source])) def search(g, residual, source, sink): dfs_stack = [(source, None, float('inf'))] route = [None] visited = set() while dfs_stack: u, prev, flow = dfs_stack.pop() while route[-1] != prev: route.pop() route.append(u) visited |= {u} if u == sink: return route[1:], flow for v in g[u]: if v in route: continue next_flow = min(residual[u][v], flow) if 0 < next_flow: dfs_stack.append((v, u, next_flow)) return None, None main() ```
instruction
0
47,017
13
94,034
No
output
1
47,017
13
94,035
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3 Submitted Solution: ``` from sys import stdin from collections import defaultdict readline = stdin.readline #readline = open('???.txt').readline def main(): v, e = map(int, readline().split()) g = defaultdict(list) residual = [[0] * v for _ in range(v)] source, sink = 0, v - 1 for _ in range(e): s, t, c = map(int, readline().split()) if 0 < c: g[s].append(t) g[t].append(s) residual[s][t] = c capacity = sum(residual[source][i] for i in g[source]) while True: route, flow = search(g, residual, source, sink) if route is None: break for i in range(1, len(route)): residual[route[i - 1]][route[i]] -= flow residual[route[i]][route[i - 1]] += flow print(capacity - sum(residual[source][i] for i in g[source])) def search(g, residual, source, sink): dfs_stack = [(source, None, float('inf'))] route = [None] visited = set() while dfs_stack: u, prev, flow = dfs_stack.pop() while route[-1] != prev: route.pop() route.append(u) visited |= {u} if u == sink: return route[1:], flow for v in g[u]: if v in visited: continue next_flow = min(residual[u][v], flow) if 0 < next_flow: dfs_stack.append((v, u, next_flow)) return None, None main() ```
instruction
0
47,018
13
94,036
No
output
1
47,018
13
94,037
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V| \leq 100$ * $1 \leq |E| \leq 1000$ * $0 \leq c_i \leq 10000$ Input A flow network is given in the following format. $|V|\;|E|$ $u_0\;v_0\;c_0$ $u_1\;v_1\;c_1$ : $u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$ $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network. A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Example Input 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 Output 3 Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 4 5 0 1 2 0 2 1 1 2 1 1 3 1 2 3 2 output: 3 """ import sys from collections import deque def graph_bfs(source, target, parent): visited = [False] * vertices queue = deque() queue.append(source) visited[source] = True while queue: current = queue.popleft() for adj, cp in adj_table[current].items(): if not visited[adj] and cp: queue.append(adj) visited[adj] = True parent[adj] = current return True if visited[target] else False def graphFordFulkerson(source, sink): parent = [-1] * vertices max_flow = 0 while graph_bfs(source, sink, parent): path_flow = float('inf') bk_1 = sink while bk_1 is not source: path_flow = min(path_flow, adj_table[parent[bk_1]][bk_1]) bk_1 = parent[bk_1] max_flow += path_flow bk_2 = sink while bk_2 is not source: parent_bk_2 = parent[bk_2] adj_table[parent_bk_2].setdefault(bk_2, path_flow) adj_table[bk_2].setdefault(parent_bk_2, path_flow) # print(bk_2, parent_bk_2, path_flow, bk_1, parent[bk_1], parent, adj_table) adj_table[parent_bk_2][bk_2] -= path_flow adj_table[bk_2][parent_bk_2] += path_flow bk_2 = parent[bk_2] return max_flow def generate_adj_table(v_table): for each in v_table: source, target, cp = map(int, each) init_adj_table[source][target] = cp return init_adj_table if __name__ == '__main__': _input = sys.stdin.readlines() vertices, edges = map(int, _input[0].split()) v_info = map(lambda x: x.split(), _input[1:]) init_adj_table = [dict() for _ in range(vertices)] adj_table = generate_adj_table(v_info) ans = graphFordFulkerson(source=0, sink=vertices - 1) print(ans) ```
instruction
0
47,019
13
94,038
No
output
1
47,019
13
94,039
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6
instruction
0
47,189
13
94,378
Tags: binary search, dfs and similar, greedy, sortings, trees, two pointers Correct Solution: ``` import sys, threading from math import inf input = sys.stdin.readline def put(): return map(int, input().split()) def dfs(tree,i, sum, p): if len(tree[i])==1 and i!=0: return 1 cnt=0 for j,w,c in tree[i]: if j!=p: z=dfs(tree,j, sum+w, i) cnt+=z if c==1:one.append((w, z)) else: two.append((w, z)) return cnt def solve(): t = int(input()) for _ in range(t): n, w = put() tree = [[] for i in range(n)] for i in range(n-1): x,y,z,c = put() x,y = x-1,y-1 tree[x].append((y,z,c)) tree[y].append((x,z,c)) dfs(tree, 0,0,-1) s,flag = 0, True diffone, difftwo = [],[] for arr in [one, two]: for i in range(len(arr)): s+= arr[i][0]*arr[i][1] while arr: i,j = arr.pop() while i>0: if flag: diffone.append((i-i//2)*j) else: difftwo.append((i-i//2)*j) i//=2 flag = False diffone.sort(reverse=True) difftwo.sort(reverse=True) s,cnt=s-w, inf for i in difftwo: s-= i p,q = len(diffone), len(difftwo) i,j=q-1,0 while i>=-1: while s>0 and j<p: s-=diffone[j] j+=1 if s<=0: cnt = min(cnt, 2*i+j+2) if i>-1: s+= difftwo[i] i-=1 print(cnt) one,two = [],[] max_recur_size = 10**5*2 + 1000 max_stack_size = max_recur_size*500 sys.setrecursionlimit(max_recur_size) threading.stack_size(max_stack_size) thread = threading.Thread(target=solve) thread.start() ```
output
1
47,189
13
94,379
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6
instruction
0
47,190
13
94,380
Tags: binary search, dfs and similar, greedy, sortings, trees, two pointers Correct Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import sys # sys.setrecursionlimit(5010) from heapq import * # from collections import deque as dq # from math import ceil,floor,sqrt,pow # import bisect as bs # from collections import Counter from collections import defaultdict as dc for _ in range(N()): n,s = RL() edges = [ RLL() for _ in range(n-1)] dic = [[] for _ in range(n+1)] gress,count,father,W,C = [0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1) gress[1]=-n-1 for u,v,_,_ in edges: dic[u].append(v) dic[v].append(u) gress[u]+=1 gress[v]+=1 leaf = [] for i in range(2,n+1): if gress[i]==1: leaf.append(i) count[i] = 1 now = [1] while now: node = now.pop() for child in dic[node]: if child!=father[node]: father[child] = node now.append(child) for u,v,w,c in edges: if father[u]==v: W[u] = w C[u] = c elif father[v]==u: W[v] = w C[v] = c weight1,weight2 = [],[] n1,n2 = 0,0 while leaf: node = leaf.pop() f = father[node] count[f]+=count[node] gress[f]-=1 if gress[f]==1: leaf.append(f) d = W[node]*count[node] dd = ((W[node]>>1)-W[node])*count[node] if C[node]==1: n1+=d weight1.append((dd,node)) else: n2+=d weight2.append((dd,node)) heapify(weight1) heapify(weight2) v1,v2 = [n1],[n2] t1,t2 = max(0,s-n2),max(0,s-n1) while n1>t1: delta,node = heappop(weight1) n1+=delta v1.append(n1) if W[node]>1: W[node]>>=1 heappush(weight1,(((W[node]>>1)-W[node])*count[node],node)) while n2>t2: delta,node = heappop(weight2) n2+=delta v2.append(n2) if W[node]>1: W[node]>>=1 heappush(weight2,(((W[node]>>1)-W[node])*count[node],node)) res = float('inf') j = len(v2)-1 for i in range(len(v1)): if v1[i]>s: continue while j>0 and v1[i]+v2[j-1]<=s: j-=1 res = min(res,i+2*j) if i>=res: break print(res) ```
output
1
47,190
13
94,381
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6
instruction
0
47,191
13
94,382
Tags: binary search, dfs and similar, greedy, sortings, trees, two pointers Correct Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import sys # sys.setrecursionlimit(5010) from heapq import * # from collections import deque as dq # from math import ceil,floor,sqrt,pow # import bisect as bs # from collections import Counter # from collections import defaultdict as dc for _ in range(N()): n,s = RL() edges = [ RLL() for _ in range(n-1)] dic = [[] for _ in range(n+1)] gress,count,father,W,C = [0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1) gress[1]=-n-1 for u,v,_,_ in edges: dic[u].append(v) dic[v].append(u) gress[u]+=1 gress[v]+=1 leaf = [] now = [1] while now: node = now.pop() if gress[node]==1: count[node] = 1 leaf.append(node) for child in dic[node]: if child!=father[node]: father[child] = node now.append(child) for u,v,w,c in edges: if father[u]==v: W[u] = w C[u] = c elif father[v]==u: W[v] = w C[v] = c weight1,weight2 = [],[] n1,n2 = 0,0 while leaf: node = leaf.pop() f = father[node] count[f]+=count[node] gress[f]-=1 if gress[f]==1: leaf.append(f) delta = ((W[node]>>1)-W[node])*count[node] if C[node]==1: n1+=W[node]*count[node] weight1.append((delta,node)) else: n2+=W[node]*count[node] weight2.append((delta,node)) heapify(weight1) heapify(weight2) v1,v2 = [n1],[n2] t1,t2 = max(0,s-n2),max(0,s-n1) while n1>t1: delta,node = heappop(weight1) n1+=delta v1.append(n1) if W[node]>1: W[node]>>=1 heappush(weight1,(((W[node]>>1)-W[node])*count[node],node)) while n2>t2: delta,node = heappop(weight2) n2+=delta v2.append(n2) if W[node]>1: W[node]>>=1 heappush(weight2,(((W[node]>>1)-W[node])*count[node],node)) res = float('inf') j = len(v2)-1 for i in range(len(v1)): if v1[i]>s: continue while j>0 and v1[i]+v2[j-1]<=s: j-=1 res = min(res,i+2*j) if i>=res: break print(res) ```
output
1
47,191
13
94,383
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6
instruction
0
47,192
13
94,384
Tags: binary search, dfs and similar, greedy, sortings, trees, two pointers Correct Solution: ``` from collections import * from sys import stdin, stdout input = stdin.buffer.readline print = stdout.write # "". join(strings) def ri(): return int(input()) def rl(): return list(map(int, input().split())) def topo_sort(tree, root, n): visited = [False]*(n+1) visited[root]=True stack = [root] result = [root] while stack: u = stack.pop() for v in tree[u]: if visited[v]==False: visited[v]=True result.append(v) stack.append(v) return result[::-1] t =ri() for _ in range(t): n,S = rl() edges=[] for i in range(n-1): edges.append(rl()) tree = defaultdict(list) # tree = [[] for i in range(n+1)] for u,v,w_ , c_ in edges: tree[u].append(v) tree[v].append(u) root = 1 topo = topo_sort(tree, root, n) cnt =[-1]*(n+1) for u in topo: this_cnt =0 for v in tree[u]: #only add value from the children if cnt[v]!=-1: this_cnt+=cnt[v] cnt[u]=this_cnt #put value at 1 for leaves (no children) if cnt[u]==0: cnt[u]=1 gains=[[],[]] sum_weights=0 for child, parent, weight, cost in edges: #make sure child is really the child: if cnt[child]> cnt[parent]: child, parent = parent, child sum_weights += weight * cnt[child] count = cnt[child] gain = count * (weight - weight//2) while gain>0: gains[cost-1].append(gain) weight = weight//2 gain = count * (weight - weight//2) gains[0].sort(reverse=True) gains[1].sort(reverse=True) idx1=0 idx2=1 idx22=0 ans=0 n1 = len(gains[0]) n2 = len(gains[1]) last_idx=-1 while sum_weights>S: if idx1<n1 and sum_weights - gains[0][idx1]<=S: ans+=1 last_idx=idx1 break if idx2< n1 and idx22<n2: if gains[0][idx1]+gains[0][idx2]>=gains[1][idx22]: # if sum_weights - gains[0][idx1] - gains[0][idx2] > S and sum_weights - gains[1][idx22] - gains[0][idx1]<=S: # ans+=3 # break ans+=2 sum_weights -= gains[0][idx1] + gains[0][idx2] last_idx=idx2 idx1+=2 idx2+=2 else: ans+=2 sum_weights -= gains[1][idx22] idx22+=1 elif idx22>=n2: ans+=1 sum_weights -= gains[0][idx1] last_idx=idx1 idx1+=1 idx2+=1 else: #idx2>=n1 and if idx1<n1 then sum_weights - gains[0][idx1]>S, so we need to take out a move of cost 2 anyway ans+=2 sum_weights -= gains[1][idx22] idx22+=1 if ans%2==0: if last_idx< n1 and last_idx>=0 and sum_weights+gains[0][last_idx]<=S: ans = max(0, ans-1) print(str(ans)+"\n") ```
output
1
47,192
13
94,385
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6
instruction
0
47,193
13
94,386
Tags: binary search, dfs and similar, greedy, sortings, trees, two pointers Correct Solution: ``` #!/usr/bin/env python3 import io import os import heapq input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_str(): return input().decode().strip() def rint(): return map(int, input().split()) def oint(): return int(input()) def make_item(i, ww=-1): if ww == -1: ww = w[i] return mul[i]*(ww//2) - mul[i]*ww, i def push_item(i): if w[i]: if c[i] == 1: pq = pq1 else: pq = pq2 heapq.heappush(pq, make_item(i)) def move(pq): global cost global sum_ diff, i = heapq.heappop(pq) sum_ += diff cost += c[i] w[i] //= 2 push_item(i) def dfs(): stack = [1] visit = [0] * (n + 1) while stack: i = stack[-1] if visit[i] == 0: visit[i] = 1 for ni, nw, nc in adj[i]: if visit[ni] == 0: w[ni] = nw c[ni] = nc stack.append(ni) else: visit[i] = 2 stack.pop() if len(adj[i]) == 1: mul[i] += 1 for ni, _, _ in adj[i]: mul[i] += mul[ni] push_item(i) t = oint() for _ in range(t): n, s = rint() adj = [[] for i in range(n + 1)] mul = [0] * (n + 1) w = [0] * (n + 1) c = [1] * (n + 1) pq1 = [] pq2 = [] for i in range(n-1): vv, uu, ww, cc = rint() adj[vv].append((uu, ww, cc)) adj[uu].append((vv, ww, cc)) dfs() sum_ = 0 for _, i in pq1 + pq2: sum_ += mul[i] * w[i] cost = 0 while sum_ > s: if not pq1: move(pq2) continue if not pq2: move(pq1) continue if pq1[0][0] + sum_ <= s: cost += 1 break if pq2[0][0] + sum_ <= s: cost += 2 break diff1, i1 = heapq.heappop(pq1) diff1r, _ = make_item(i1, w[i1]//2) if pq1: diff1n = min(diff1r, pq1[0][0]) else: diff1n = diff1r push_item(i1) diff2, i2 = pq2[0][0], pq2[0][1] if diff2 < diff1 + diff1n: move(pq2) else: move(pq1) print(cost) ```
output
1
47,193
13
94,387
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6
instruction
0
47,194
13
94,388
Tags: binary search, dfs and similar, greedy, sortings, trees, two pointers Correct Solution: ``` import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') from decimal import Decimal from fractions import Fraction #sys.setrecursionlimit(100000) INF = float('inf') mod = int(1e9)+7 def dfs(graph, start=0): n = len(graph) dp = [0] * n visited, finished = [False] * n, [False] * n sum1 = 0 stack = [start] while stack: start = stack[-1] # push unvisited children into stack if not visited[start]: visited[start] = True for child, w, c in graph[start]: if not visited[child]: stack.append(child) else: stack.pop() # base case if len(graph[start]) == 1 and start != 0: dp[start] += 1 # update with finished children for child, w, c in graph[start]: if finished[child]: dp[start] += dp[child] sum1 += w * dp[child] if c == 1: heappush(q1, ((w // 2 - w) * dp[child], child)) else: heappush(q2, ((w // 2 - w) * dp[child], child)) v[child] = w finished[start] = True return dp, sum1 for t in range(int(data())): n,s1=mdata() g=[[] for i in range(n)] for i in range(n-1): u,v,w,c=mdata() g[u-1].append((v-1,w,c)) g[v-1].append((u-1,w,c)) q1,q2 = [],[] v = [0] * n dp,sum1=dfs(g) while len(q1)<2: heappush(q1, (0, 0)) while len(q2)<1: heappush(q2, (0, 0)) cnt=0 while sum1>s1: dec_a,id_a=heappop(q1) dec_b,id_b=q1[0] dec_c, id_c = q2[0] dec = dec_a + min((v[id_a] // 4 - v[id_a] // 2) * dp[id_a],dec_b) if sum1+dec_a<=s1: cnt+=1 break if dec_c<dec: heappop(q2) sum1+=dec_c v[id_c] //= 2 dec_c=(v[id_c]//2-v[id_c])*dp[id_c] cnt+=2 heappush(q2,(dec_c,id_c)) else: sum1+=dec_a v[id_a] //= 2 dec_a = (v[id_a] // 2 - v[id_a]) * dp[id_a] cnt+=1 heappush(q1,(dec_a,id_a)) out(cnt) ```
output
1
47,194
13
94,389
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6
instruction
0
47,195
13
94,390
Tags: binary search, dfs and similar, greedy, sortings, trees, two pointers Correct Solution: ``` import sys,bisect from collections import deque input=sys.stdin.buffer.readline t=1 t=int(input()) for _ in range(t): n,S=map(int,input().split()) edge=[[] for i in range(n)] for i in range(n-1): u,v,w,c=map(int,input().split()) edge[u-1].append((v-1,w,float(c))) edge[v-1].append((u-1,w,float(c))) ans=[0] deq=deque(ans) parent=[-1]*n while deq: v=deq.popleft() for nv,w,c in edge[v]: if nv!=parent[v]: parent[nv]=v ans.append(nv) deq.append(nv) for v in range(n): edge[v]=[edge[v][i] for i in range(len(edge[v])) if edge[v][i][0]!=parent[v]] size=[0]*n ans=ans[::-1] for v in ans: for nv,w,c in edge[v]: size[v]+=size[nv] if len(edge[v])==0: size[v]=1 s=0 que1=[] que2=[] for v in range(n): for nv,w,c in edge[v]: s+=size[nv]*w if c==1: while w>=1: minus=size[nv]*(w-w//2) w//=2 que1.append(minus) else: while w>=1: minus=size[nv]*(w-w//2) w//=2 que2.append(minus) que1.sort(reverse=True) que2.sort(reverse=True) n,m=len(que1),len(que2) for i in range(1,m): que2[i]+=que2[i-1] que2=[0]+que2 que1=[0]+que1 ans=10**20 id=m+1 cum=0 for i in range(n+1): test=i cum+=que1[i] while id>0 and que2[id-1]>=s-S-cum: id-=1 if id!=m+1: test+=2*id ans=min(ans,test) print(int(ans)) ```
output
1
47,195
13
94,391
Provide tags and a correct Python 3 solution for this coding contest problem. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6
instruction
0
47,196
13
94,392
Tags: binary search, dfs and similar, greedy, sortings, trees, two pointers Correct Solution: ``` import sys,bisect from collections import deque input=sys.stdin.buffer.readline t=1 t=int(input()) for _ in range(t): n,S=map(int,input().split()) edge=[[] for i in range(n)] for i in range(n-1): u,v,w,c=map(int,input().split()) edge[u-1].append((v-1,w,c)) edge[v-1].append((u-1,w,c)) ans=[0] deq=deque(ans) parent=[-1]*n while deq: v=deq.popleft() for nv,w,c in edge[v]: if nv!=parent[v]: parent[nv]=v ans.append(nv) deq.append(nv) for v in range(n): edge[v]=[edge[v][i] for i in range(len(edge[v])) if edge[v][i][0]!=parent[v]] size=[0]*n ans=ans[::-1] for v in ans: for nv,w,c in edge[v]: size[v]+=size[nv] if len(edge[v])==0: size[v]=1 s=0 que1=[] que2=[] for v in range(n): for nv,w,c in edge[v]: s+=size[nv]*w if c==1: while w>=1: minus=size[nv]*(w-w//2) w//=2 que1.append(minus) else: while w>=1: minus=size[nv]*(w-w//2) w//=2 que2.append(minus) que1.sort(reverse=True) que2.sort(reverse=True) n,m=len(que1),len(que2) for i in range(1,m): que2[i]+=que2[i-1] que2=[0]+que2 que1=[0]+que1 ans=10**20 id=m+1 cum=0 for i in range(n+1): test=i cum+=que1[i] while id>0 and que2[id-1]>=s-S-cum: id-=1 if id!=m+1: test+=2*id ans=min(ans,test) print(ans) ```
output
1
47,196
13
94,393
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6 Submitted Solution: ``` from collections import deque from heapq import heappop, heappush import sys input = sys.stdin.buffer.readline def solve(): n,s = map(int,input().split()) e = [[] for i in range(n)] for i in range(n-1): u,v,w,c = map(int,input().split()) u -= 1 v -= 1 e[u].append((v,w,c)) e[v].append((u,w,c)) par = [-1]*n dep = [n]*n dep[0] = 0 topo = [] q = deque([0]) count = [0]*n while q: now= q.pop() topo.append(now) lea = 1 for nex,_,_ in e[now]: if dep[nex] < dep[now]: continue lea = 0 par[nex] = now dep[nex] = dep[now]+1 q.append(nex) if lea: count[now] = 1 cum = 0 h1 = [0] h2 = [] for now in topo[::-1]: num = count[now] for nex,w,c in e[now]: if dep[nex] > dep[now]: continue cum += num*w count[nex] += num if c == 2: while w: h2.append((w-w//2)*num) w //= 2 else: while w: h1.append((w-w//2)*num) w //= 2 if cum <= s: return 0 h1.sort(reverse=True) h2.sort(reverse=True) h2cum = [0]*(len(h2)+1) for i in range(len(h2)): h2cum[-2-i] = h2cum[-1-i]+h2[i] ans = 10**10 now = 0 le = len(h2cum) for i in range(len(h1)): h = h1[i] if cum-h2cum[0] > s: cum -= h continue while now < le and cum-h2cum[now] <= s: now += 1 if ans > i+(le-now)*2: ans = i+(le-now)*2 cum -= h return ans t = int(input()) for _ in range(t): print(solve()) ```
instruction
0
47,197
13
94,394
Yes
output
1
47,197
13
94,395
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6 Submitted Solution: ``` from heapq import * import sys input = sys.stdin.readline for _ in range(int(input())): n,s = map(int, input().split()) edges = [ list(map(int, input().split())) for _ in range(n-1)] dic = [[] for _ in range(n+1)] gress,count,father,W,C = [0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1) gress[1]=-n-1 for u,v,_,_ in edges: dic[u].append(v) dic[v].append(u) gress[u]+=1 gress[v]+=1 leaf = [] now = [1] while now: node = now.pop() if gress[node]==1: count[node] = 1 leaf.append(node) for child in dic[node]: if child!=father[node]: father[child] = node now.append(child) for u,v,w,c in edges: if father[u]==v: W[u] = w C[u] = c elif father[v]==u: W[v] = w C[v] = c weight1,weight2 = [],[] n1,n2 = 0,0 while leaf: node = leaf.pop() f = father[node] count[f]+=count[node] gress[f]-=1 if gress[f]==1: leaf.append(f) delta = ((W[node]>>1)-W[node])*count[node] if C[node]==1: n1+=W[node]*count[node] weight1.append((delta,node)) else: n2+=W[node]*count[node] weight2.append((delta,node)) heapify(weight1) heapify(weight2) v1,v2 = [n1],[n2] t1,t2 = max(0,s-n2),max(0,s-n1) while n1>t1: delta,node = heappop(weight1) n1+=delta v1.append(n1) if W[node]>1: W[node]>>=1 heappush(weight1,(((W[node]>>1)-W[node])*count[node],node)) while n2>t2: delta,node = heappop(weight2) n2+=delta v2.append(n2) if W[node]>1: W[node]>>=1 heappush(weight2,(((W[node]>>1)-W[node])*count[node],node)) res = float('inf') j = len(v2)-1 for i in range(len(v1)): if v1[i]>s: continue while j>0 and v1[i]+v2[j-1]<=s: j-=1 res = min(res,i+2*j) if i>=res: break print(res) ```
instruction
0
47,198
13
94,396
Yes
output
1
47,198
13
94,397
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight. The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0. You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\rightβŒ‹). Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins. Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make βˆ‘_{v ∈ leaves} w(root, v) ≀ S, where leaves is the list of all leaves. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and S (2 ≀ n ≀ 10^5; 1 ≀ S ≀ 10^{16}) β€” the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≀ v_i, u_i ≀ n; 1 ≀ w_i ≀ 10^6; 1 ≀ c_i ≀ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge. It is guaranteed that the sum of n does not exceed 10^5 (βˆ‘ n ≀ 10^5). Output For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S. Example Input 4 4 18 2 1 9 2 3 2 4 1 4 1 1 2 3 20 2 1 8 1 3 1 7 2 5 50 1 3 100 1 1 5 10 2 2 3 123 2 5 4 55 1 2 100 1 2 409 2 Output 0 0 11 6 Submitted Solution: ``` #!/usr/bin/env python3 import io import os import heapq input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_str(): return input().decode().strip() def rint(): return map(int, input().split()) def oint(): return int(input()) def dfs(cur): stack = [cur] while stack: cur = stack[-1] if v[cur] == 0: v[cur] = 1 for ni, nw, _ in adj[cur]: if v[ni]: continue stack.append(ni) else: if cur != 1 and len(adj[cur]) == 1: ret = 1 else: ret = 0 for ni, nw, cc in adj[cur]: if v[ni] == 1: w[cur] = nw c[cur] = cc continue ret += lc[ni] lc[cur] = ret if c[cur] == 1: if w[cur]: sl1.append(((lc[cur] * (w[cur] // 2) - lc[cur] * w[cur]), cur)) else: if w[cur]: sl2.append(((lc[cur] * (w[cur] // 2) - lc[cur] * w[cur]), cur)) v[cur] = 2 stack.pop() t = oint() for _ in range(t): n, s = rint() adj = [[] for i in range(n + 1)] v = [0] * (n + 1) lc = [0] * (n + 1) w = [0] * (n + 1) c = [1] * (n + 1) sl1 = [] sl2 = [] for i in range(n - 1): vv, uu, ww, cc = rint() adj[vv].append((uu, ww, cc)) adj[uu].append((vv, ww, cc)) dfs(1) sum_ = 0 for item in sl1: i = item[1] mul = lc[i] sum_ += mul * w[i] for item in sl2: i = item[1] mul = lc[i] sum_ += mul * w[i] heapq.heapify(sl1) heapq.heapify(sl2) cost = 0 while sum_ > s: if not sl1: item = heapq.heappop(sl2) i = item[1] mul = lc[i] cost += 2 sum_ = sum_ + item[0] w[i] //= 2 if w[i] != 0: heapq.heappush(sl2, ((mul * (w[i] // 2) - mul * w[i]), i)) continue if not sl2: item = heapq.heappop(sl1) i = item[1] mul = lc[i] cost += 1 sum_ = sum_ + item[0] w[i] //= 2 if w[i] != 0 or len(sl1) == 0: heapq.heappush(sl1, ((mul * (w[i] // 2) - mul * w[i]), i)) continue if sl1[0][0] + sum_ <= s: cost += 1 break if sl2[0][0] + sum_ <= s: cost += 2 break item1 = heapq.heappop(sl1) i = item1[1] mul = lc[i] diff2 = mul* ((w[i]//2)//2) - mul*(w[i]//2) if sl1: diff = min(diff2, sl1[0][0]) else: diff = diff2 item2 = sl2[0] if item2[0] < item1[0] + diff: cost += 2 heapq.heappush(sl1, item1) i = item2[1] mul = lc[i] sum_ = sum_ + item2[0] w[i] //= 2 heapq.heappop(sl2) if w[i] != 0: heapq.heappush(sl2, ((mul*(w[i]//2)- mul*w[i]), i)) else: cost += 1 sum_ = sum_ + item1[0] w[i] //= 2 if w[i] != 0: heapq.heappush(sl1, (diff2, i)) print(cost) ```
instruction
0
47,199
13
94,398
Yes
output
1
47,199
13
94,399