message
stringlengths
2
22.8k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
16
109k
cluster
float64
1
1
__index_level_0__
int64
32
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house. Output Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 3 3 2 3 Output 6 Input 4 3 2 3 3 Output 2 Note In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units. Submitted Solution: ``` n,m=input().split() m=int(m) n=int(n) Ar=[] for x in input().split(): Ar.append(int(x)) Cl=1 T=0 for i in Ar: t=i-Cl if t<0: t+=n Cl=i T+=t print(T) ```
instruction
0
2,783
1
5,566
Yes
output
1
2,783
1
5,567
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house. Output Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 3 3 2 3 Output 6 Input 4 3 2 3 3 Output 2 Note In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units. Submitted Solution: ``` n, m = map(int, input().split()) lst = list(map(int, input().split())) ans = lst[0] for i in range(1, m): if lst[i] > lst[i-1]: ans += lst[i] - lst[i-1] elif lst[i] < lst[i-1]: ans += n - lst[i-1] + lst[i] print(ans-1) ```
instruction
0
2,784
1
5,568
Yes
output
1
2,784
1
5,569
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house. Output Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 3 3 2 3 Output 6 Input 4 3 2 3 3 Output 2 Note In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units. Submitted Solution: ``` n,m=[int(i) for i in input().split()] a=[int(i) for i in input().split()] for i in range(len(a)): if i==0: time=a[i]-1 continue if a[i]<a[i-1]: time+=n-a[i-1]+a[i] else: time+=a[i]-a[i-1] print(time) ```
instruction
0
2,785
1
5,570
Yes
output
1
2,785
1
5,571
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house. Output Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 3 3 2 3 Output 6 Input 4 3 2 3 3 Output 2 Note In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units. Submitted Solution: ``` #https://codeforces.com/problemset/problem/339/B #runtime error ''' from sys import stdin n, m = [int(c) for c in stdin.readline().split()] d = [int(c) for c in stdin.readline().split()] t = 1 count = 0 i = 0 l = len(d) while i < l: if t == d[i]: i = i + 1 continue t = t % n + 1 count = count + 1 print(count) ''' from sys import stdin n, m = [int(c) for c in stdin.readline().split()] d = [int(c) for c in stdin.readline().split()] t = 1 count = 0 l = len(d) for x in d: if t == x: continue elif t<x: count = count + x - t else: count = count + n - t + x t = x print(count) ```
instruction
0
2,786
1
5,572
Yes
output
1
2,786
1
5,573
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house. Output Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 3 3 2 3 Output 6 Input 4 3 2 3 3 Output 2 Note In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units. Submitted Solution: ``` n,m=map(int, input().split(" ")) a=[1]+list(map(int, input().split(" "))) sum=0 for i in range(m-1): if a[i]>a[i-1]: sum=sum+(a[i] - a[i-1]) elif a[i] < a[i-1]: sum=sum+(n-(a[i-1]-a[i])) print(sum) ```
instruction
0
2,787
1
5,574
No
output
1
2,787
1
5,575
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house. Output Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 3 3 2 3 Output 6 Input 4 3 2 3 3 Output 2 Note In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units. Submitted Solution: ``` s=k=0 n,m=map(int,input().split()) trouble=[int(x) for x in input().split()] if sum(trouble)==m: print(0) else: for i in range(m-1): if trouble[i]==trouble[i+1]: trouble[i]=0 for i in range(1,n+1): if s<=trouble.count(i): s=trouble.count(i) k=i print(n*(s-1)+k-1) ```
instruction
0
2,788
1
5,576
No
output
1
2,788
1
5,577
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house. Output Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 3 3 2 3 Output 6 Input 4 3 2 3 3 Output 2 Note In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units. Submitted Solution: ``` n, m = map(int, input().split()) works = list(map(int, input().split())) ans = 0 current_home = 1 for i in works: ans += current_home - 1 + i - 1 if current_home > i else i - current_home current_home = i print(ans) ```
instruction
0
2,789
1
5,578
No
output
1
2,789
1
5,579
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house. Output Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 3 3 2 3 Output 6 Input 4 3 2 3 3 Output 2 Note In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units. Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 17 14:20:05 2018 @author: umang """ n, m = map(int, input().split()) a = list(map(int, input().split())) cur_time = 0 prev = a[0] for i in a[1:]: if i < prev: prev = i cur_time += n + i - 1 else: cur_time += i - prev prev = i print(cur_time) ```
instruction
0
2,790
1
5,580
No
output
1
2,790
1
5,581
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1).
instruction
0
2,860
1
5,720
Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` from queue import Queue import sys cost = [] #coo def readarray(): return map(int, input().split(' ')) n = int(input()) graph = [[] for i in range(n)] for i in range(n - 1): u, v, c = readarray() u, v = u - 1, v - 1 cost.append(c) graph[u].append((v, i)) graph[v].append((u, i)) order = [] used = [0] * n q = [0] * (n + n) qh = qt = 0 used[qh] = 1 qh += 1 while qt < qh: v = q[qt] qt += 1 order.append(v) for (to, e) in graph[v]: if used[to]: continue used[to] = 1 q[qh] = to qh += 1 order.reverse() sz = [0 for x in range(n)] for v in order: sz[v] = 1 for (to, e) in graph[v]: sz[v] += sz[to] """ sz = [0] * n sys.setrecursionlimit(100505) def dfs(v, p): sz[v] = 1 for (to, e) in graph[v]: if to != p: dfs(to, v) sz[v] += sz[to] dfs(0, -1) """ distanceSum = 0.0 edgeMult = [0] * n for v in range(n): for (to, e) in graph[v]: x = min(sz[v], sz[to]) edgeMult[e] = x distanceSum += 1.0 * cost[e] * x * (n - x) distanceSum /= 2.0 queryCnt = int(input()) ans = [] for i in range(queryCnt): x, y = readarray() x -= 1 distanceSum -= 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x]) cost[x] = y distanceSum += 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x]) ans.append('%.10lf' % (distanceSum / n / (n - 1) * 6.0)) print('\n'.join(ans)) ```
output
1
2,860
1
5,721
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1).
instruction
0
2,861
1
5,722
Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ 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()) #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa=ifa[::-1] def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def linc(f,t,l,r): while l<r: mid=(l+r)//2 if t>f(mid): l=mid+1 else: r=mid return l def rinc(f,t,l,r): while l<r: mid=(l+r+1)//2 if t<f(mid): r=mid-1 else: l=mid return l def ldec(f,t,l,r): while l<r: mid=(l+r)//2 if t<f(mid): l=mid+1 else: r=mid return l def rdec(f,t,l,r): while l<r: mid=(l+r+1)//2 if t>f(mid): r=mid-1 else: l=mid return l def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def binfun(x): c=0 for w in arr: c+=ceil(w/x) return c def lowbit(n): return n&-n def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class SMT: def __init__(self,arr): self.n=len(arr)-1 self.arr=[0]*(self.n<<2) self.lazy=[0]*(self.n<<2) def Build(l,r,rt): if l==r: self.arr[rt]=arr[l] return m=(l+r)>>1 Build(l,m,rt<<1) Build(m+1,r,rt<<1|1) self.pushup(rt) Build(1,self.n,1) def pushup(self,rt): self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1] def pushdown(self,rt,ln,rn):#lr,rn表区间数字数 if self.lazy[rt]: self.lazy[rt<<1]+=self.lazy[rt] self.lazy[rt<<1|1]=self.lazy[rt] self.arr[rt<<1]+=self.lazy[rt]*ln self.arr[rt<<1|1]+=self.lazy[rt]*rn self.lazy[rt]=0 def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间 if r==None: r=self.n if L<=l and r<=R: self.arr[rt]+=c*(r-l+1) self.lazy[rt]+=c return m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) if L<=m: self.update(L,R,c,l,m,rt<<1) if R>m: self.update(L,R,c,m+1,r,rt<<1|1) self.pushup(rt) def query(self,L,R,l=1,r=None,rt=1): if r==None: r=self.n #print(L,R,l,r,rt) if L<=l and R>=r: return self.arr[rt] m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) ans=0 if L<=m: ans+=self.query(L,R,l,m,rt<<1) if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1) return ans class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]<self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)] class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue for v in graph[u]: if v not in d or d[v]>d[u]+graph[u][v]: d[v]=d[u]+graph[u][v] heappush(heap,(d[v],v)) return d def GP(it): return [(ch,len(list(g))) for ch,g in groupby(it)] class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None @bootstrap def dfs(r,p): if len(g[r])==1 and p!=-1: yield 1 res=1 for child in g[r]: if child!=p: tmp=yield(dfs(child,r)) cnt[d[tuple(sorted([r,child]))]]=tmp*(n-tmp) res+=tmp yield res t=1 for i in range(t): n=N() edg=[] d={} cnt=[0]*(n-1) g=[[] for i in range(n)] for i in range(n-1): a,b,l=RL() a-=1 b-=1 g[a].append(b) g[b].append(a) if a>b: a,b=b,a d[a,b]=i edg.append(l) dfs(0,-1) #print(cnt) ans=sum(edg[i]*cnt[i] for i in range(n-1)) ans=ans*6/(n*(n-1)) #print(ans) q=N() for i in range(q): c,l=RL() dec=edg[c-1]-l edg[c-1]=l #print(dec) ans-=dec*cnt[c-1]*6/((n-1)*n) print(ans) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thread(target=main) t.start() t.join() ''' ```
output
1
2,861
1
5,723
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1).
instruction
0
2,862
1
5,724
Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` import sys sys.setrecursionlimit(1500) MAX = 100005; g = [[] for _ in range(MAX)] vis = [False] * MAX dp = [0] * MAX prod = [0] * MAX edges = [] order = [] def dfs(st): stack = [] stack.append((st, -1)) vis[st] = True while stack: st, parent = stack.pop() order.append(st) vis[st] = True if (st == parent): continue; for i in g[st]: if (vis[i[0]]): continue; stack.append((i[0], st)) n = int(input()) for i in range(n-1): a, b, w = map(int, sys.stdin.readline().split(' ')) g[a].append([b, w]) g[b].append([a,w]) edges.append([[a, b], w]) dfs(1); order.reverse() for st in order: dp[st] = 1; for i in g[st]: dp[st] += dp[i[0]]; tot = 0; curr = 1; div = n * (n-1) / 2; for i in edges: a = i[0][0]; b = i[0][1]; sa = dp[a]; sb = dp[b]; tot += min(sa, sb) * (n - min(sa, sb)) * i[1]; prod[curr] = min(sa, sb) * (n - min(sa, sb)); curr += 1; q = int(input()) for i in range(q): q1, q2 = map(int, sys.stdin.readline().split(' ')) tot -= prod[q1] * edges[q1-1][1]; edges[q1-1][1] = q2; tot += prod[q1] * edges[q1-1][1]; sys.stdout.write(str(tot*3/div)+"\n") ```
output
1
2,862
1
5,725
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1).
instruction
0
2,863
1
5,726
Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(10**5) 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 @bootstrap def dfs(u,p): global ans for j in adj[u]: if j!=p: yield dfs(j,u) sub[u]+=sub[j] p1=sub[u] p2=n-sub[u] d1[(u,p)]=p1*p2*(p1+p2-2) d1[(p, u)] = p1 * p2 * (p1 + p2 - 2) ans+=(p1*p2*(p1+p2-2))*d[(u,p)] yield n=int(input()) adj=[[] for i in range(n+1)] edges=[] d=defaultdict(lambda:0) d1=defaultdict(lambda:0) ans=0 for i in range(n-1): u,v,l=map(int,input().split()) d[(u,v)]=l d[(v,u)]=l edges.append([u,v]) adj[u].append(v) adj[v].append(u) sub=[1 for i in range(n+1)] dfs(1,0) val=n*(n-1)*(n-2) for q in range(int(input())): nu,new=map(int,input().split()) edge=edges[nu-1] u,v=edge[0],edge[1] old=d[(u,v)] tot=d1[(u,v)] ans+=tot*(new-old) d[(u,v)]=new d[(v,u)]=new print((6*ans)/val) ```
output
1
2,863
1
5,727
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1).
instruction
0
2,864
1
5,728
Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` from queue import Queue import sys cost = [] def readarray(): return map(int, input().split(' ')) n = int(input()) graph = [[] for i in range(n)] for i in range(n - 1): u, v, c = readarray() u, v = u - 1, v - 1 cost.append(c) graph[u].append((v, i)) graph[v].append((u, i)) order = [] used = [0] * n q = [0] * (n + n) qh = qt = 0 used[qh] = 1 qh += 1 while qt < qh: v = q[qt] qt += 1 order.append(v) for (to, e) in graph[v]: if used[to]: continue used[to] = 1 q[qh] = to qh += 1 order.reverse() sz = [0 for x in range(n)] for v in order: sz[v] = 1 for (to, e) in graph[v]: sz[v] += sz[to] """ sz = [0] * n sys.setrecursionlimit(100505) def dfs(v, p): sz[v] = 1 for (to, e) in graph[v]: if to != p: dfs(to, v) sz[v] += sz[to] dfs(0, -1) """ distanceSum = 0.0 edgeMult = [0] * n for v in range(n): for (to, e) in graph[v]: x = min(sz[v], sz[to]) edgeMult[e] = x distanceSum += 1.0 * cost[e] * x * (n - x) distanceSum /= 2.0 queryCnt = int(input()) ans = [] for i in range(queryCnt): x, y = readarray() x -= 1 distanceSum -= 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x]) cost[x] = y distanceSum += 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x]) ans.append('%.10lf' % (distanceSum / n / (n - 1) * 6.0)) print('\n'.join(ans)) ```
output
1
2,864
1
5,729
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Submitted Solution: ``` import sys MAX = 100005; g = [[] for _ in range(MAX)] vis = [False] * MAX dp = [0] * MAX prod = [0] * MAX edges = [] def dfs(st, parent = -1): vis[st] = True if (st == parent): return; for i in g[st]: if (vis[i[0]]): continue; dfs(i[0], st) dp[st] = 1; for i in g[st]: dp[st] += dp[i[0]]; n = int(input()) for i in range(n-1): a, b, w = map(int, sys.stdin.readline().split(' ')) g[a].append([b, w]) g[b].append([a,w]) edges.append([[a, b], w]) dfs(1); tot = 0; curr = 1; div = n * (n-1) / 2; for i in edges: a = i[0][0]; b = i[0][1]; sa = dp[a]; sb = dp[b]; tot += min(sa, sb) * (n - min(sa, sb)) * i[1]; prod[curr] = min(sa, sb) * (n - min(sa, sb)); curr += 1; q = int(input()) for i in range(q): q1, q2 = map(int, sys.stdin.readline().split(' ')) tot -= prod[q1] * edges[q1-1][1]; edges[q1-1][1] = q2; tot += prod[q1] * edges[q1-1][1]; sys.stdout.write(str(tot*3/div)) ```
instruction
0
2,865
1
5,730
No
output
1
2,865
1
5,731
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Submitted Solution: ``` n = int(input()) ni = [list(map(int,input().split())) for i in range(n-1)] q = int(input()) qi = [list(map(int,input().split())) for i in range(q)] summ = 0 for num in range(n-1): summ += ni[num][2]*(n-1) for num in range(q): summ -= (ni[qi[num][0]-1][2] - qi[num][1])*(n-1) ni[qi[num][0]-1][2] = qi[num][1] print(float(summ)/((n)*(n-1)*(n-2))) ```
instruction
0
2,866
1
5,732
No
output
1
2,866
1
5,733
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Submitted Solution: ``` import sys sys.setrecursionlimit(1500) MAX = 100005; g = [[] for _ in range(MAX)] vis = [False] * MAX dp = [0] * MAX prod = [0] * MAX edges = [] def dfs(st): stack = [] stack.append((st, -1)) vis[st] = True while stack: st, parent = stack.pop() vis[st] = True if (st == parent): continue; for i in g[st]: if (vis[i[0]]): continue; stack.append((i[0], st)) dp[st] = 1; for i in g[st]: dp[st] += dp[i[0]]; n = int(input()) for i in range(n-1): a, b, w = map(int, sys.stdin.readline().split(' ')) g[a].append([b, w]) g[b].append([a,w]) edges.append([[a, b], w]) dfs(1); tot = 0; curr = 1; div = n * (n-1) / 2; for i in edges: a = i[0][0]; b = i[0][1]; sa = dp[a]; sb = dp[b]; tot += min(sa, sb) * (n - min(sa, sb)) * i[1]; prod[curr] = min(sa, sb) * (n - min(sa, sb)); curr += 1; q = int(input()) for i in range(q): q1, q2 = map(int, sys.stdin.readline().split(' ')) tot -= prod[q1] * edges[q1-1][1]; edges[q1-1][1] = q2; tot += prod[q1] * edges[q1-1][1]; sys.stdout.write(str(tot*3/div)+"\n") ```
instruction
0
2,867
1
5,734
No
output
1
2,867
1
5,735
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Submitted Solution: ``` n = int(input()) g, l, e = [[] for x in range(n+1)], [0] * n, [0] * n for i in range(1,n): x, y, e[i] = map(int,input().split()) g[x] += [[y, i]] g[y] += [[x, i]] print(g) def dfs(i,p): d = 1 for z in g[i]: if z[0] != p: u = dfs(z[0],i) d += u l[z[1]] = u * (n-u) return d dfs(1,0) s = 0 for i in range(1,n): s += l[i] * e[i] m = int(input()) while m > 0: m -= 1 r, w = map(int,input().split()) s += (w - e[r]) * l[r] e[r] = w print("%.17f"%float(6*s/n/(n-1))) ```
instruction
0
2,868
1
5,736
No
output
1
2,868
1
5,737
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image>
instruction
0
2,869
1
5,738
Tags: dfs and similar, greedy, implementation Correct Solution: ``` n = int(input()) arr = list(map(int, input().split())) ans = 0 b = 2 ** (n + 1) - 3 while n != 0: n -= 1 #print(n) p = 2 ** (n + 1) - 3 while b != p: ans += abs(arr[b] - arr[b - 1]) arr[b // 2 - 1] += max(arr[b], arr[b - 1]) #print(arr) b -= 2 print(ans) ```
output
1
2,869
1
5,739
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image>
instruction
0
2,870
1
5,740
Tags: dfs and similar, greedy, implementation Correct Solution: ``` def main(): n, l, res = 2 ** (int(input()) + 1) - 2, [0, 0], 0 l.extend(map(int, input().split())) while n: a, b = l[n], l[n + 1] if a < b: l[n // 2] += b res += b - a else: l[n // 2] += a res += a - b n -= 2 print(res) if __name__ == '__main__': main() ```
output
1
2,870
1
5,741
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image>
instruction
0
2,871
1
5,742
Tags: dfs and similar, greedy, implementation Correct Solution: ``` # fin = open("input.txt") # n = int(fin.readline()) # A = [0] + list(map(int, fin.readline().split())) n = int(input()) A = [0] + list(map(int, input().split())) C = 0 for i in range(2 ** n - 2, -1, -1): C += abs(A[i * 2 + 1] - A[i * 2 + 2]) A[i] += max(A[i * 2 + 1], A[i * 2 + 2]) print(C) ```
output
1
2,871
1
5,743
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image>
instruction
0
2,872
1
5,744
Tags: dfs and similar, greedy, implementation Correct Solution: ``` s = 0 n = int(input()) k = (1 << (n + 1)) - 1 a = [0, 0] + list(map(int, input().split())) for i in range(k, 1, -2): u, v = a[i], a[i - 1] if u > v: u, v = v, u s += v - u a[i >> 1] += v print(s) ```
output
1
2,872
1
5,745
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image>
instruction
0
2,873
1
5,746
Tags: dfs and similar, greedy, implementation Correct Solution: ``` #!python3 n = int(input()) a = input().split() a = [int(i) for i in a] def solve(n, a, added): last = a[-2**n:] new = [] for i in range(0, 2**n-1, 2): #print(last[i]) x = last[i] y = last[i+1] new.append(max(x,y)) added = added + abs(x-y) a = a[:-2**n] if a==[]: a = [0] for i in range(1, 2**(n-1)+1): a[-i] = a[-i] + new[-i] n = n-1 if n==0: print(added) else: solve(n, a, added) solve(n, a, 0) ```
output
1
2,873
1
5,747
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image>
instruction
0
2,874
1
5,748
Tags: dfs and similar, greedy, implementation Correct Solution: ``` n = 2**(int(input())+1)-1; a = [0,0] + list(map(int,input().split())) r = 0 while n>1: a[n//2] += max(a[n], a[n-1]) r += abs(a[n]-a[n-1]) n -= 2 print(r) ```
output
1
2,874
1
5,749
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image>
instruction
0
2,875
1
5,750
Tags: dfs and similar, greedy, implementation Correct Solution: ``` n = int(input()) l = list(map(int,input().split())) l = [0]+l top = 1 lim = 2**(n+1)-1 count = 0 def solver(top): global count left = top*2+1 right = 2+ top*2 if(left>lim or right>lim): #print(top,"ret ",l[top]) return l[top] else: ll = solver(left) rr = solver(right) if(ll!=rr): count+= max(ll,rr)-min(ll,rr) #print("change ",max(ll,rr)-min(ll,rr)) #print("ret" , max(ll,rr)+l[top]) return max(ll,rr)+l[top] solver(0) print(count) ```
output
1
2,875
1
5,751
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image>
instruction
0
2,876
1
5,752
Tags: dfs and similar, greedy, implementation Correct Solution: ``` from math import floor def main(): n = int(input()) a = list(map(int, input().split())) streets = [] for i in range(2**n, 2**(n+1)): #print('---') idx = i #print(idx) if idx > 1: #print('Cost: %d' % a[idx-2]) res = a[idx-2] while idx > 0: idx = int(floor(idx/2)) if idx > 1: #print(idx) #print('Cost: %d' % a[idx-2]) res += a[idx-2] #print('res: %d' % res) streets.append(res) res = 0 #print(streets) while len(streets) > 2: new_streets = [] for i in range(0, len(streets), 2): #print('i: %d' % i) res += abs(streets[i]-streets[i+1]) new_streets.append(max(streets[i], streets[i+1])) #print(new_streets, cur_diff) streets = new_streets print(res+abs(streets[0]-streets[1])) if __name__ == '__main__': main() ```
output
1
2,876
1
5,753
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- # author: firolunis # version: 0.1 n = int(input()) park = input().split(' ') park = [int(i) for i in park] park.insert(0, 0) lights = [0 for i in range(2 ** (n + 1) - 1)] res = 0 for k in range(n, 0, -1): for i, j in tuple(enumerate(park))[(2 ** k) - 1:2 ** (k + 1) - 1:2]: res += abs(j + lights[i] - park[i + 1] - lights[i + 1]) lights[i // 2] = max(j + lights[i], park[i + 1] + lights[i + 1]) print(res) ```
instruction
0
2,877
1
5,754
Yes
output
1
2,877
1
5,755
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` n = int(input()) park = [0] * (2 ** (n + 1)) park[2: 2 ** (n + 1)] = [int(i) for i in input().split()] cnt = 0 for i in range(2 ** n - 1, 0, -1): cnt += abs(park[i * 2 + 1] - park[i * 2]) park[i] += max(park[i * 2 + 1], park[i * 2]) print(cnt) ```
instruction
0
2,878
1
5,756
Yes
output
1
2,878
1
5,757
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` # print ("Enter n") n = int(input()) alen = 2**(n+1) a = [0 for i in range(alen)] # print ("Enter all values on the same line") inp = input().split() for i in range(len(inp)): a[i+2] = int(inp[i]) answer = 0 while (n > 0): index = 2**n for i in range(index, index*2, 2): left = a[i] right = a[i+1] diff = abs(left-right) bigone = max(left, right) answer += diff a[i//2] += bigone n = n - 1 print (answer) ```
instruction
0
2,879
1
5,758
Yes
output
1
2,879
1
5,759
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` #!/usr/bin/python3 n = 2**(int(input())+1)-1 d = input().split(' ') for i in range(len(d)): d[i] = int(d[i]) p = 0 for i in range(len(d)-1, 0, -2): p += abs(d[i]-d[i-1]) d[i//2-1] += max(d[i], d[i-1]) print(p) ```
instruction
0
2,880
1
5,760
Yes
output
1
2,880
1
5,761
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` # fin = open("input.txt") # n = int(fin.readline()) # A = [0] + list(map(int, fin.readline().split())) n = int(input()) A = list(map(int, input().split())) C = 0 for i in range(n - 1, -1, -1): C += abs(A[i * 2] - A[i * 2 + 1]) A[i] += max(A[i * 2], A[i * 2 + 1]) print(C) ```
instruction
0
2,881
1
5,762
No
output
1
2,881
1
5,763
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` import math a = int(input()) b = list(map(int, input().split())) co = 2 sum1 = 0 sum2 = 0 j = co for i in b: if j == 0: co = co * 2 j = co if j <= co // 2: sum2 += i else: sum1 += i j -= 1 print(int(math.fabs(sum2-sum1))) ```
instruction
0
2,882
1
5,764
No
output
1
2,882
1
5,765
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` import sys, os import fileinput n = int(input()) + 1 a = [int(x) for x in input().split()] all_count = 2 ** n - 1 b = [0] * all_count counter = 0 for i in range(n, 1, -1): lcnt = 2 ** (i - 1) first = 2 ** (i - 1) - 2 #print(lcnt, first) level = a[first:first + lcnt] # print(level) for j in range(0, lcnt, 2): index = first + 2 + j if i == n: # print(i) # print("-" * 10) diff = abs(level[j] - level[j + 1]) # print(j, level[j], level[j+1], diff) counter += diff # print(index//2 - 1, level[j] + level[j + 1] + diff) b[index//2 - 1] += level[j] + level[j + 1] + diff # print("=" * 10) else: # print(i) # print("*" * 10) # print(index) # print(b) # print(level) diff = abs(abs(b[index - 1]//2 + level[j]) - abs(b[index]//2 + level[j + 1])) counter += diff b[index//2 - 1] += b[index-1] + b[index] + level[j] + level[j + 1] + diff # print("+" * 10) print(counter) # print(b) ```
instruction
0
2,883
1
5,766
No
output
1
2,883
1
5,767
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` import math a = input() b = list(map(int, input().split())) co = 2 sum1 = 0 sum2 = 0 j = co if b == [1, 2, 3, 3, 2, 2]: print(0) exit(0) for i in b: if j == 0: co = co * 2 j = co if j <= co // 2: sum2 += i else: sum1 += i j -= 1 print(int(math.fabs(sum2-sum1))) ```
instruction
0
2,884
1
5,768
No
output
1
2,884
1
5,769
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspace™ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hyperspace™ highways, has been completely fulfilled. Unfortunately, lots of space contractors had friends and cousins in the Space Board of Directors of the company, so the company decided to do much more than just connecting all planets. In order to make spending enormous amounts of space money for Hyperspace™ highways look neccessary, they decided to enforce a strict rule on the Hyperspace™ highway network: whenever there is a way to travel through some planets and return to the starting point without travelling through any planet twice, every pair of planets on the itinerary should be directly connected by a Hyperspace™ highway. In other words, the set of planets in every simple cycle induces a complete subgraph. You are designing a Hyperspace™ navigational app, and the key technical problem you are facing is finding the minimal number of Hyperspace™ highways one needs to use to travel from planet A to planet B. As this problem is too easy for Bubble Cup, here is a harder task: your program needs to do it for Q pairs of planets. Input The first line contains three positive integers N (1≤ N≤ 100 000), M (1≤ M≤ 500 000) and Q (1≤ Q≤ 200 000), denoting the number of planets, the number of Hyperspace™ highways, and the number of queries, respectively. Each of the following M lines contains a highway: highway i is given by two integers u_i and v_i (1 ≤ u_i < v_i ≤ N), meaning the planets u_i and v_i are connected by a Hyperspace™ highway. It is guaranteed that the network of planets and Hyperspace™ highways forms a simple connected graph. Each of the following Q lines contains a query: query j is given by two integers a_j and b_j (1 ≤ a_j < b_j ≤ N ), meaning we are interested in the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j. Output Output Q lines: the j-th line of output should contain the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j. Examples Input 5 7 2 1 2 1 3 1 4 2 3 2 4 3 4 1 5 1 4 2 5 Output 1 2 Input 8 11 4 1 2 2 3 3 4 4 5 1 3 1 6 3 5 3 7 4 7 5 7 6 8 1 5 2 4 6 7 3 8 Output 2 2 3 3 Note The graph from the second sample: <image> Submitted Solution: ``` N = 301000 n = 0 m = 0 q = 0 cnt = [0]*1 Num = [0] * N Up = [0] * N chk = [0] * N ppp = [0] * N par = [[0] * 20 for i in range(N)] Dep = [0] * N T = [None] * N G = [None] * N E = [None] * N def main(): n,m,q = map(int,input().split()) #E = [None] * (n+1) print(n) for i in range(1,m+1): u,v = map(int,input().split()) if E[u] is None: E[u] = [] if E[v] is None: E[v] = [] E[u].append(v) E[v].append(u) result = [] DFS(1,0,E) cnt = [0]*1 BuildTree(1,0) FindDepth(1,0) while q > 0: a,b = map(int,input().split()) result.append(int((Dep[a] + Dep[b] - Dep[LCA(a,b)]*2)/2)) #print(result) q-= 1 for r in result: print(r) def DFS(a,pp,E): cnt[0] = cnt[0]+1 Num[a] = cnt[0] ppp[a] = pp r = Num[a] for v in E[a]: if Num[v]!=0: r = min(r,Num[v]) continue if T[a] is None: T[a] = [] T[a].append(v) DFS(v,a,E) if Up[v] >= Num[a]: chk[v]=1 r = min(r,Up[v]) Up[a] = r def AddEdge(a,b): if G[a] is None: G[a] = [] if G[b] is None: G[b] = [] G[a].append(b) G[b].append(a) def BuildTree(a,c): if c != 0: AddEdge(n+c,a) if T[a] is None: T[a] = [] for v in T[a]: if chk[v] !=0: cnt[0] = cnt[0]+1 AddEdge(n + cnt[0],a) BuildTree(v,cnt[0]) else: BuildTree(v,c) def FindDepth(a,pp): par[a][0] = pp for i in range(0,19): par[a][i+1] = par[par[a][i]][i] for v in G[a]: if v != pp: Dep[v] = Dep[a] + 1 FindDepth(v,a) def LCA(a,b): if Dep[a] < Dep[b]: return LCA(b,a) d = Dep[a] - Dep[b] i = 0 while d != 0: if not (d % 2 == 0): a = par[a][i] d = int(d/2) i += 1 i = 18 while i>=0: if par[a][i] != par[b][i]: a = par[a][i] b = par[b][i] i-=1 if a != b: a = par[a][0] return a main() ```
instruction
0
3,359
1
6,718
No
output
1
3,359
1
6,719
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspace™ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hyperspace™ highways, has been completely fulfilled. Unfortunately, lots of space contractors had friends and cousins in the Space Board of Directors of the company, so the company decided to do much more than just connecting all planets. In order to make spending enormous amounts of space money for Hyperspace™ highways look neccessary, they decided to enforce a strict rule on the Hyperspace™ highway network: whenever there is a way to travel through some planets and return to the starting point without travelling through any planet twice, every pair of planets on the itinerary should be directly connected by a Hyperspace™ highway. In other words, the set of planets in every simple cycle induces a complete subgraph. You are designing a Hyperspace™ navigational app, and the key technical problem you are facing is finding the minimal number of Hyperspace™ highways one needs to use to travel from planet A to planet B. As this problem is too easy for Bubble Cup, here is a harder task: your program needs to do it for Q pairs of planets. Input The first line contains three positive integers N (1≤ N≤ 100 000), M (1≤ M≤ 500 000) and Q (1≤ Q≤ 200 000), denoting the number of planets, the number of Hyperspace™ highways, and the number of queries, respectively. Each of the following M lines contains a highway: highway i is given by two integers u_i and v_i (1 ≤ u_i < v_i ≤ N), meaning the planets u_i and v_i are connected by a Hyperspace™ highway. It is guaranteed that the network of planets and Hyperspace™ highways forms a simple connected graph. Each of the following Q lines contains a query: query j is given by two integers a_j and b_j (1 ≤ a_j < b_j ≤ N ), meaning we are interested in the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j. Output Output Q lines: the j-th line of output should contain the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j. Examples Input 5 7 2 1 2 1 3 1 4 2 3 2 4 3 4 1 5 1 4 2 5 Output 1 2 Input 8 11 4 1 2 2 3 3 4 4 5 1 3 1 6 3 5 3 7 4 7 5 7 6 8 1 5 2 4 6 7 3 8 Output 2 2 3 3 Note The graph from the second sample: <image> Submitted Solution: ``` N = 301001 n = 0 m = 0 q = 0 cnt = [0]*1 Num = [0] * N Up = [0] * N chk = [0] * N ppp = [0] * N par = [[0] * 20 for i in range(N)] Dep = [0] * N T = [None] * N G = [None] * N E = [None] * N def main(): n,m,q = map(int,input().split()) #E = [None] * (n+1) print(n) for i in range(1,m+1): u,v = map(int,input().split()) if E[u] is None: E[u] = [] if E[v] is None: E[v] = [] E[u].append(v) E[v].append(u) result = [] DFS(1,0,E) cnt = [0]*1 BuildTree(1,0) FindDepth(1,0) while q > 0: a,b = map(int,input().split()) result.append(int((Dep[a] + Dep[b] - Dep[LCA(a,b)]*2)/2)) #print(result) q-= 1 for r in result: print(r) def DFS(a,pp,E): cnt[0] = cnt[0]+1 Num[a] = cnt[0] ppp[a] = pp r = Num[a] for v in E[a]: if Num[v]!=0: r = min(r,Num[v]) continue if T[a] is None: T[a] = [] T[a].append(v) DFS(v,a,E) if Up[v] >= Num[a]: chk[v]=1 r = min(r,Up[v]) Up[a] = r def AddEdge(a,b): if G[a] is None: G[a] = [] if G[b] is None: G[b] = [] G[a].append(b) G[b].append(a) def BuildTree(a,c): if c != 0: AddEdge(n+c,a) if T[a] is None: T[a] = [] for v in T[a]: if chk[v] !=0: cnt[0] = cnt[0]+1 AddEdge(n + cnt[0],a) BuildTree(v,cnt[0]) else: BuildTree(v,c) def FindDepth(a,pp): par[a][0] = pp for i in range(0,19): par[a][i+1] = par[par[a][i]][i] for v in G[a]: if v != pp: Dep[v] = Dep[a] + 1 FindDepth(v,a) def LCA(a,b): if Dep[a] < Dep[b]: return LCA(b,a) d = Dep[a] - Dep[b] i = 0 while d != 0: if not (d % 2 == 0): a = par[a][i] d = int(d/2) i += 1 i = 18 while i>=0: if par[a][i] != par[b][i]: a = par[a][i] b = par[b][i] i-=1 if a != b: a = par[a][0] return a main() ```
instruction
0
3,360
1
6,720
No
output
1
3,360
1
6,721
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspace™ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hyperspace™ highways, has been completely fulfilled. Unfortunately, lots of space contractors had friends and cousins in the Space Board of Directors of the company, so the company decided to do much more than just connecting all planets. In order to make spending enormous amounts of space money for Hyperspace™ highways look neccessary, they decided to enforce a strict rule on the Hyperspace™ highway network: whenever there is a way to travel through some planets and return to the starting point without travelling through any planet twice, every pair of planets on the itinerary should be directly connected by a Hyperspace™ highway. In other words, the set of planets in every simple cycle induces a complete subgraph. You are designing a Hyperspace™ navigational app, and the key technical problem you are facing is finding the minimal number of Hyperspace™ highways one needs to use to travel from planet A to planet B. As this problem is too easy for Bubble Cup, here is a harder task: your program needs to do it for Q pairs of planets. Input The first line contains three positive integers N (1≤ N≤ 100 000), M (1≤ M≤ 500 000) and Q (1≤ Q≤ 200 000), denoting the number of planets, the number of Hyperspace™ highways, and the number of queries, respectively. Each of the following M lines contains a highway: highway i is given by two integers u_i and v_i (1 ≤ u_i < v_i ≤ N), meaning the planets u_i and v_i are connected by a Hyperspace™ highway. It is guaranteed that the network of planets and Hyperspace™ highways forms a simple connected graph. Each of the following Q lines contains a query: query j is given by two integers a_j and b_j (1 ≤ a_j < b_j ≤ N ), meaning we are interested in the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j. Output Output Q lines: the j-th line of output should contain the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j. Examples Input 5 7 2 1 2 1 3 1 4 2 3 2 4 3 4 1 5 1 4 2 5 Output 1 2 Input 8 11 4 1 2 2 3 3 4 4 5 1 3 1 6 3 5 3 7 4 7 5 7 6 8 1 5 2 4 6 7 3 8 Output 2 2 3 3 Note The graph from the second sample: <image> Submitted Solution: ``` N = 100 n = 0 m = 0 q = 0 cnt = [0]*1 Num = [0] * N Up = [0] * N chk = [0] * N ppp = [0] * N par = [[0] * 20 for i in range(N)] Dep = [0] * N T = [None] * N G = [None] * N E = [None] * N def main(): n,m,q = map(int,input().split()) E = [None] * (n+1) for i in range(1,m+1): u,v = map(int,input().split()) if E[u] is None: E[u] = [] if E[v] is None: E[v] = [] E[u].append(v) E[v].append(u) DFS(1,0,E) cnt = [0]*1 BuildTree(1,0) FindDepth(1,0) while q > 0: a,b = map(int,input().split()) result =int((Dep[a] + Dep[b] - Dep[LCA(a,b)]*2)/2) print(result) q-= 1 def DFS(a,pp,E): cnt[0] = cnt[0]+1 Num[a] = cnt[0] ppp[a] = pp r = Num[a] for v in E[a]: if Num[v]!=0: r = min(r,Num[v]) continue if T[a] is None: T[a] = [] T[a].append(v) DFS(v,a,E) if Up[v] >= Num[a]: chk[v]=1 r = min(r,Up[v]) Up[a] = r def AddEdge(a,b): if G[a] is None: G[a] = [] if G[b] is None: G[b] = [] G[a].append(b) G[b].append(a) def BuildTree(a,c): if c != 0: AddEdge(n+c,a) if T[a] is None: T[a] = [] for v in T[a]: if chk[v] !=0: cnt[0] = cnt[0]+1 AddEdge(n + cnt[0],a) BuildTree(v,cnt[0]) else: BuildTree(v,c) def FindDepth(a,pp): par[a][0] = pp for i in range(0,19): par[a][i+1] = par[par[a][i]][i] for v in G[a]: if v != pp: Dep[v] = Dep[a] + 1 FindDepth(v,a) def LCA(a,b): if Dep[a] < Dep[b]: return LCA(b,a) d = Dep[a] - Dep[b] i = 0 while d != 0: if not (d % 2 == 0): a = par[a][i] d = int(d/2) i += 1 i = 18 while i>=0: if par[a][i] != par[b][i]: a = par[a][i] b = par[b][i] i-=1 if a != b: a = par[a][0] return a ```
instruction
0
3,361
1
6,722
No
output
1
3,361
1
6,723
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspace™ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hyperspace™ highways, has been completely fulfilled. Unfortunately, lots of space contractors had friends and cousins in the Space Board of Directors of the company, so the company decided to do much more than just connecting all planets. In order to make spending enormous amounts of space money for Hyperspace™ highways look neccessary, they decided to enforce a strict rule on the Hyperspace™ highway network: whenever there is a way to travel through some planets and return to the starting point without travelling through any planet twice, every pair of planets on the itinerary should be directly connected by a Hyperspace™ highway. In other words, the set of planets in every simple cycle induces a complete subgraph. You are designing a Hyperspace™ navigational app, and the key technical problem you are facing is finding the minimal number of Hyperspace™ highways one needs to use to travel from planet A to planet B. As this problem is too easy for Bubble Cup, here is a harder task: your program needs to do it for Q pairs of planets. Input The first line contains three positive integers N (1≤ N≤ 100 000), M (1≤ M≤ 500 000) and Q (1≤ Q≤ 200 000), denoting the number of planets, the number of Hyperspace™ highways, and the number of queries, respectively. Each of the following M lines contains a highway: highway i is given by two integers u_i and v_i (1 ≤ u_i < v_i ≤ N), meaning the planets u_i and v_i are connected by a Hyperspace™ highway. It is guaranteed that the network of planets and Hyperspace™ highways forms a simple connected graph. Each of the following Q lines contains a query: query j is given by two integers a_j and b_j (1 ≤ a_j < b_j ≤ N ), meaning we are interested in the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j. Output Output Q lines: the j-th line of output should contain the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j. Examples Input 5 7 2 1 2 1 3 1 4 2 3 2 4 3 4 1 5 1 4 2 5 Output 1 2 Input 8 11 4 1 2 2 3 3 4 4 5 1 3 1 6 3 5 3 7 4 7 5 7 6 8 1 5 2 4 6 7 3 8 Output 2 2 3 3 Note The graph from the second sample: <image> Submitted Solution: ``` N = 100 n = 0 m = 0 q = 0 cnt = [0]*1 Num = [0] * N Up = [0] * N chk = [0] * N ppp = [0] * N par = [[0] * 20 for i in range(N)] Dep = [0] * N T = [None] * N G = [None] * N E = [None] * N def main(): n,m,q = map(int,input().split()) E = [None] * (n+1) for i in range(1,m+1): u,v = map(int,input().split()) if E[u] is None: E[u] = [] if E[v] is None: E[v] = [] E[u].append(v) E[v].append(u) result = [] DFS(1,0,E) cnt = [0]*1 BuildTree(1,0) FindDepth(1,0) while q > 0: a,b = map(int,input().split()) result.append(int((Dep[a] + Dep[b] - Dep[LCA(a,b)]*2)/2)) #print(result) q-= 1 for r in result: print(r) def DFS(a,pp,E): cnt[0] = cnt[0]+1 Num[a] = cnt[0] ppp[a] = pp r = Num[a] for v in E[a]: if Num[v]!=0: r = min(r,Num[v]) continue if T[a] is None: T[a] = [] T[a].append(v) DFS(v,a,E) if Up[v] >= Num[a]: chk[v]=1 r = min(r,Up[v]) Up[a] = r def AddEdge(a,b): if G[a] is None: G[a] = [] if G[b] is None: G[b] = [] G[a].append(b) G[b].append(a) def BuildTree(a,c): if c != 0: AddEdge(n+c,a) if T[a] is None: T[a] = [] for v in T[a]: if chk[v] !=0: cnt[0] = cnt[0]+1 AddEdge(n + cnt[0],a) BuildTree(v,cnt[0]) else: BuildTree(v,c) def FindDepth(a,pp): par[a][0] = pp for i in range(0,19): par[a][i+1] = par[par[a][i]][i] for v in G[a]: if v != pp: Dep[v] = Dep[a] + 1 FindDepth(v,a) def LCA(a,b): if Dep[a] < Dep[b]: return LCA(b,a) d = Dep[a] - Dep[b] i = 0 while d != 0: if not (d % 2 == 0): a = par[a][i] d = int(d/2) i += 1 i = 18 while i>=0: if par[a][i] != par[b][i]: a = par[a][i] b = par[b][i] i-=1 if a != b: a = par[a][0] return a ```
instruction
0
3,362
1
6,724
No
output
1
3,362
1
6,725
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image>
instruction
0
3,499
1
6,998
Tags: brute force, graphs, greedy, shortest paths, sortings Correct Solution: ``` from collections import deque import sys from array import array # noqa: F401 import typing as Tp # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def bfs(n, adj, start): cost = [-1] * n cost[start] = 0 dq = deque([start]) while dq: v = dq.popleft() for dest in adj[v]: if cost[dest] != -1: continue cost[dest] = cost[v] + 1 dq.append(dest) return cost def main(): t = int(input()) ans = [''] * t for ti in range(t): from itertools import accumulate n, m, a, b, c = map(int, input().split()) a, b, c = a - 1, b - 1, c - 1 p = (0, ) + tuple(accumulate(sorted(map(int, input().split())))) adj = [[] for _ in range(n)] for u, v in (map(int, input().split()) for _ in range(m)): adj[u - 1].append(v - 1) adj[v - 1].append(u - 1) a_to_x = bfs(n, adj, a) b_to_x = bfs(n, adj, b) c_to_x = bfs(n, adj, c) mincost = 10**18 for x in range(n): if a_to_x[x] + b_to_x[x] + c_to_x[x] > m: continue mincost = min( mincost, p[b_to_x[x]] + p[a_to_x[x] + b_to_x[x] + c_to_x[x]] ) ans[ti] = str(mincost) sys.stdout.buffer.write(('\n'.join(ans) + '\n').encode('utf-8')) if __name__ == '__main__': main() ```
output
1
3,499
1
6,999
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image>
instruction
0
3,500
1
7,000
Tags: brute force, graphs, greedy, shortest paths, sortings Correct Solution: ``` import math import random import sys from bisect import bisect_left, bisect_right from collections import Counter, UserDict, defaultdict, deque, namedtuple from functools import cmp_to_key, lru_cache, reduce from heapq import heapify, heappop, heappush # sys.setrecursionlimit(10**6 + 1) input = sys.stdin.buffer.readline MOD = 10**9 + 7 INT_MAX = (1 << 63) - 1 def calc_distance(frm, graph, n): pq = [(0, frm)] dist = [INT_MAX] * (n+1) dist[frm] = 0 while pq: d, node = heappop(pq) if d > dist[node]: continue for nb in graph[node]: if 1 + d < dist[nb]: dist[nb] = 1 + d heappush(pq, (1 + d, nb)) return dist if __name__ == "__main__": T = int(input()) for _ in range(T): n, m, a, b, c = map(int, input().split()) prices = [int(s) for s in input().split()] prices.sort() edge = {} graph = defaultdict(list) for _ in range(m): u, v = map(int, input().split()) graph[u].append(v) graph[v].append(u) to_a = calc_distance(a, graph, n) to_b = calc_distance(b, graph, n) to_c = calc_distance(c, graph, n) prefix = [0] * (m+1) for i, p in enumerate(prices): prefix[i+1] = p + prefix[i] # print(prefix) ans = INT_MAX for v in range(1, n+1): d_a, d_b, d_c = to_a[v], to_b[v], to_c[v] if d_a + d_b + d_c <= m: # print('cur:', v, 'd:', d_a+d_b+d_c) ans = min(ans, prefix[d_a+d_b+d_c] + prefix[d_b]) print(ans) ```
output
1
3,500
1
7,001
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image>
instruction
0
3,501
1
7,002
Tags: brute force, graphs, greedy, shortest paths, sortings Correct Solution: ``` from itertools import accumulate from collections import deque def BFS(adj,level,s): queue=deque([s]) level[s]=0 while queue: s=queue.popleft() for i in adj[s]: if level[i]==-1: queue.append(i) level[i]=level[s]+1 def addEdge(adj, v, w): adj[v].append(w) adj[w].append(v) t=int(input()) for _ in range(t): n,m,a,b,c = map(int,input().split(" ")) a,b,c=a-1,b-1,c-1 p=[int(x) for x in input().split()] p.sort() cost=[0]+list(accumulate(p)) adj=[[] for i in range(n)] for i in range(m): u,v = map(int,input().split(" ")) addEdge(adj,u-1,v-1) da,db,dc=[-1]*(n),[-1]*(n),[-1]*(n) BFS(adj,da,a) BFS(adj,db,b) BFS(adj,dc,c) ans=10**18 for i in range(n): x=da[i]+db[i]+dc[i] if x<=m: cx=cost[x]+cost[db[i]] ans=min(ans,cx) print(ans) ```
output
1
3,501
1
7,003
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image>
instruction
0
3,502
1
7,004
Tags: brute force, graphs, greedy, shortest paths, sortings Correct Solution: ``` """ Template written to be used by Python Programmers. Use at your own risk!!!! Owned by adi0311(5 star at CodeChef and Specialist at Codeforces). """ # import io, os import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf from collections import defaultdict as dd, deque, Counter as c from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect # sys.setrecursionlimit(2*pow(10, 6)) # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") mod = pow(10, 9) + 7 mod2 = 998244353 # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def data(): return sys.stdin.readline().strip() def out(var): sys.stdout.write(str(var)) def outln(var): sys.stdout.write(str(var)+"\n") def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] def bfs(source): d = deque() d.append(source) dist = dd(lambda: mod) dist[source] = 0 while d: temp = d.popleft() for child in graph[temp]: if dist[child] > dist[temp] + 1: d.append(child) dist[child] = dist[temp] + 1 return dist for _ in range(int(data())): n, m, a, b, z = sp() arr = l() arr.sort() for i in range(1, m): arr[i] += arr[i-1] arr.insert(0, 0) graph = dd(set) for i in range(m): u, v = sp() graph[u].add(v) graph[v].add(u) dista, distb, distc = bfs(a), bfs(b), bfs(z) answer = pow(10, 19) for i in range(1, n+1): if dista[i] + distb[i] + distc[i] <= m: answer = min(answer, arr[distb[i]] + arr[dista[i] + distb[i] + distc[i]]) outln(answer) ```
output
1
3,502
1
7,005
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image>
instruction
0
3,503
1
7,006
Tags: brute force, graphs, greedy, shortest paths, sortings Correct Solution: ``` import bisect import os from collections import Counter import bisect from collections import defaultdict import math import random import heapq as hq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from itertools import combinations from io import BytesIO, IOBase from itertools import accumulate # sys.setrecursionlimit(200000) # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def tinput(): return input().split() def rinput(): return map(int, tinput()) def rlinput(): return list(rinput()) # mod = int(1e9)+7 def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) # ---------------------------------------------------- # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') def bfs(start): inf = float('inf') dist = [inf]*(n+1) q = deque() dist[start] = 0 q.append(start) while q: node = q.popleft() for child in g[node]: if dist[child] == inf: dist[child] = dist[node]+1 q.append(child) return dist if __name__ == "__main__": for _ in range(iinput()): n, m, a, b, c = rinput() val = list(accumulate(sorted(rlinput()+[0]))) g = defaultdict(list) for i in range(m): u, v = rinput() g[u].append(v) g[v].append(u) d1 = bfs(a) d2 = bfs(b) d3 = bfs(c) # print(d1,d2,d3) # print(val) ans = float('inf') for i in range(1, n+1): s = d1[i]+d2[i]+d3[i] if s <= m: ans = min(ans, val[s]+val[d2[i]]) print(ans) ```
output
1
3,503
1
7,007
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image>
instruction
0
3,504
1
7,008
Tags: brute force, graphs, greedy, shortest paths, sortings Correct Solution: ``` import sys from collections import deque from itertools import accumulate def bfs(n, s, links): q = deque([(0, s)]) visited = set() distances = [0] * n while q: d, v = q.popleft() if v in visited: continue visited.add(v) distances[v] = d q.extend((d + 1, u) for u in links[v] if u not in visited) return distances ipt = list(map(int, sys.stdin.buffer.read().split())) buf = [] t = ipt[0] k = 1 INF = 10 ** 18 for _ in range(t): n, m, a, b, c = ipt[k:k + 5] ppp = ipt[k + 5:k + 5 + m] uv = ipt[k + 5 + m:k + 5 + 3 * m] k += 5 + 3 * m ppp.sort() ppp_acc = [0] + list(accumulate(ppp)) links = [set() for _ in range(n)] for u, v in zip(uv[0::2], uv[1::2]): u -= 1 v -= 1 links[u].add(v) links[v].add(u) # print(links) from_a = bfs(n, a - 1, links) from_b = bfs(n, b - 1, links) from_c = bfs(n, c - 1, links) # print(from_a) # print(from_b) # print(from_c) ans = INF for fa, fb, fc in zip(from_a, from_b, from_c): fs = fa + fb + fc # print(fa, fb, fc, fs, ppp_acc[fb] + ppp_acc[fs] if fs <= m else '-') if fs > m: continue ans = min(ans, ppp_acc[fb] + ppp_acc[fs]) buf.append(ans) print('\n'.join(map(str, buf))) ```
output
1
3,504
1
7,009
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image>
instruction
0
3,505
1
7,010
Tags: brute force, graphs, greedy, shortest paths, sortings Correct Solution: ``` import sys from collections import deque def input(): return sys.stdin.readline()[:-1] INF = 10**6 t = int(input()) for _ in range(t): n, m, a, b, c = map(int, input().split()) a, b, c = a-1, b-1, c-1 p = list(map(int, input().split())) p.sort() cum = [0 for _ in range(m+1)] for i, x in enumerate(p): cum[i+1] = cum[i] + x adj = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) adj[u-1].append(v-1) adj[v-1].append(u-1) a_dist, b_dist, c_dist = [INF for _ in range(n)], [INF for _ in range(n)], [INF for _ in range(n)] a_dist[a] = 0 q = deque([a]) while q: l = q.popleft() for v in adj[l]: if a_dist[v] > a_dist[l]+1: a_dist[v] = a_dist[l]+1 q.append(v) b_dist[b] = 0 q = deque([b]) while q: l = q.popleft() for v in adj[l]: if b_dist[v] > b_dist[l]+1: b_dist[v] = b_dist[l]+1 q.append(v) c_dist[c] = 0 q = deque([c]) while q: l = q.popleft() for v in adj[l]: if c_dist[v] > c_dist[l]+1: c_dist[v] = c_dist[l]+1 q.append(v) #print(a_dist) #print(b_dist) #print(c_dist) ans = 10**20 for i in range(n): aa, bb, cc = a_dist[i], b_dist[i], c_dist[i] #print(aa, bb, cc) if aa+bb+cc > m: continue ans = min(ans, cum[aa+bb+cc] + cum[bb]) print(ans) ```
output
1
3,505
1
7,011
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image>
instruction
0
3,506
1
7,012
Tags: brute force, graphs, greedy, shortest paths, sortings Correct Solution: ``` from sys import stdin input=stdin.readline def bfs(g,r): it=-1 p=[0]*len(g) q=[r] v=[0]*len(g) while(it<len(q)-1): it+=1 v[q[it]]=1 for i in range(len(g[q[it]])): if v[g[q[it]][i]]==0: v[g[q[it]][i]]=1 q.append(g[q[it]][i]) p[g[q[it]][i]]=p[q[it]]+1 return p for _ in range (int(input())): n,k,a,b,c=map(int, input().split()) ax=list(map(int, input().split())) g=[[] for i in range(n)] a-=1 b-=1 c-=1 d={} for i in range(k): l,r=map(int, input().split()) g[l-1].append(r-1) g[r-1].append(l-1) d[(min(l-1,r-1),max(l-1,r-1))]=0 aa=bfs(g,a) bb=bfs(g,b) cc=bfs(g,c) ax.sort() x=[0] y=0 for i in range(k): y+=ax[i] x.append(y) ans=10**19 for i in range(n): if aa[i]+bb[i]+cc[i] > k: continue ans=min(ans,(x[bb[i]])+x[aa[i]+bb[i]+cc[i]]) print(ans) ```
output
1
3,506
1
7,013
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image> Submitted Solution: ``` # cook your dish here from sys import stdin import sys from collections import deque def bfs(x,d): d[x]=0 q = deque() q.append(x) while (len(q)!=0): z=q.popleft() for i in dictt[z]: if d[i]==mm: d[i]=d[z]+1 q.append(i) if __name__=="__main__": mm=100000000000000000000 for _ in range (int(stdin.readline())): n,m,a,b,c=map(int,(stdin.readline().split())) a-=1 b-=1 c-=1 p=sorted(list(map(int,(stdin.readline().split())))) dictt={} for i in range (m): u,v=map(int,stdin.readline().split()) if u-1 in dictt: dictt[u-1].append(v-1) else: dictt[u-1]=[v-1] if v-1 in dictt: dictt[v-1].append(u-1) else: dictt[v-1]=[u-1] pref=[0]*(m+1) pref[0]=0 for i in range (1,m+1): pref[i]=pref[i-1]+p[i-1] da=[mm]*(n) db=[mm]*(n) dc=[mm]*(n) bfs(a,da) bfs(b,db) bfs(c,dc) # print(da,db,dc) ans=mm # print(ans) for i in range (n): if da[i]+db[i]+dc[i]>m: continue ans=min(ans,pref[db[i]]+pref[da[i]+db[i]+dc[i]]) print(ans) ```
instruction
0
3,507
1
7,014
Yes
output
1
3,507
1
7,015
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image> Submitted Solution: ``` from collections import deque from itertools import accumulate for _ in range(int(input())): n, m, a, b, c = [int(x) for x in input().split()] p = list(accumulate([0, *sorted(int(x) for x in input().split()), *(10 ** 9 for i in range(3 * n - 3 - m))])) adj = [[] for i in range(n + 1)] for e in range(m): u, v = [int(x) for x in input().split()] adj[u].append(v) adj[v].append(u) da = [-1 for i in range(n + 1)] db = [-1 for i in range(n + 1)] dc = [-1 for i in range(n + 1)] for s, d in ((a, da), (b, db), (c, dc)): q = deque([s]) d[s] = 0 while len(q) > 0: u = q.popleft() for v in adj[u]: if d[v] == -1: d[v] = d[u] + 1 q.append(v) def rsq(L, R): return p[R] - p[L - 1] print(min(2 * rsq(1, db[x]) + rsq(db[x] + 1, db[x] + da[x] + dc[x]) for x in range(1, n + 1))) ```
instruction
0
3,508
1
7,016
Yes
output
1
3,508
1
7,017
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image> Submitted Solution: ``` from collections import deque def readGraph(n,m): adj=[set() for i in range(n+1)] for i in range(m): v1,v2=[int(x) for x in input().split()] adj[v1].add(v2) adj[v2].add(v1) return adj def bfs(adj,src,n): q=deque() q.append(src) visited=[False]*(n+1) distance=[0]*(n+1) visited[src]=True while q: ele=q.popleft() for a in adj[ele]: if visited[a]==False: q.append(a) distance[a]=distance[ele]+1 visited[a]=True return distance def solve(): n,m,a,b,c=[int(x) for x in input().split()] p=[0]+[int(x) for x in input().split()] adj=readGraph(n,m) dA=bfs(adj,a,n) dB=bfs(adj,b,n) dC=bfs(adj,c,n) p.sort() psum=[0]*(m+1) psum[1]=p[0] for i in range(1,m+1): psum[i]=psum[i-1]+p[i] pay=99999999999999999999999999999999 for D in range(1,n+1): DA=dA[D] DB=dB[D] DC=dC[D] if DA+DB+DC<=m: pay=min(pay,psum[DB]+psum[DA+DB+DC]) print(pay) t=int(input()) for i in range(t): solve() ```
instruction
0
3,509
1
7,018
Yes
output
1
3,509
1
7,019
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image> Submitted Solution: ``` import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') #from decimal import Decimal from fractions import Fraction #sys.setrecursionlimit(100000) INF = float('inf') mod = int(1e9)+7 def dijkstra(n, graph, start): dist = [float("inf")] * n dist[start] = 0 edge_len=1 queue = [(0, start)] while queue: path_len, v = heappop(queue) if path_len == dist[v]: for w in graph[v]: if edge_len + path_len < dist[w]: dist[w] = edge_len + path_len heappush(queue, (edge_len + path_len, w)) return dist for t in range(int(data())): n,m,a,b,c=mdata() a-=1 b-=1 c-=1 g=[[] for i in range(n)] P=[0] P+=sorted(mdata()) for i in range(1,m+1): P[i]=P[i-1]+P[i] for i in range(m): u,v=mdata() u,v=u-1,v-1 g[u].append(v) g[v].append(u) dist_a=dijkstra(n,g,a) dist_b = dijkstra(n, g, b) dist_c = dijkstra(n, g, c) ans=INF for i in range(n): if dist_b[i]+dist_a[i]+dist_c[i]>m: continue ans=min(ans,P[dist_b[i]]+P[dist_b[i]+dist_a[i]+dist_c[i]]) out(ans) ```
instruction
0
3,510
1
7,020
Yes
output
1
3,510
1
7,021
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image> Submitted Solution: ``` from sys import stdin, exit from collections import * input = stdin.readline lmi = lambda: list(map(int, input().split())) mi = lambda: map(int, input().split()) si = lambda: input().strip('\n') ssi = lambda: input().strip('\n').split() for _ in range(int(input())): n, m, a, b, c = mi() arr = sorted(lmi()) graph = [[] for i in range(n+1)] for i in range(m): x, y = mi() graph[x].append(y) graph[y].append(x) dis1 = [float("inf")]*(n+1) q = deque([a]) dis1[a] = 0 while q: node = q.popleft() for i in graph[node]: if dis1[i] > dis1[node] + 1: dis1[i] = dis1[node] + 1 q.append(i) dis2 = [float("inf")] * (n + 1) q = deque([c]) dis2[c] = 0 while q: node = q.popleft() for i in graph[node]: if dis2[i] > dis2[node] + 1: dis2[i] = dis2[node] + 1 q.append(i) tot = dis2[b] + dis1[b] tmp = 0 if dis1[c] + dis2[b] == dis1[b]: tmp = dis2[b] if dis2[a] + dis1[b] == dis2[b]: tmp = dis1[b] tot = dis2[b] + dis1[b] ans =0 for i in range(tmp): ans += arr[i] * 2 for i in range(tmp, tot-tmp): ans += arr[i % m] print(ans) ```
instruction
0
3,511
1
7,022
No
output
1
3,511
1
7,023