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 |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33. | instruction | 0 | 69,043 | 1 | 138,086 |
Tags: dfs and similar, graphs, greedy, trees
Correct Solution:
```
import sys
def input():
return sys.stdin.readline().strip()
def solve():
k = int(input())
n = 2*k
e = [[] for i in range(n)]
p = [None]*(n)
for i in range(n-1):
a, b, t = map(int, input().split())
a -= 1
b -= 1
e[a].append((b,t))
e[b].append((a,t))
q = [0]
qi = 0
while qi < len(q):
x = q[qi]
qi += 1
px = p[x]
for v, w in e[x]:
if v != px:
q.append(v)
p[v] = x
d1 = [False] * n
d2 = [0] * n
m = 0
M = 0
for qi in range(len(q)-1,-1,-1):
x = q[qi]
px = p[x]
cnt = 1
c1 = 1
for v, w in e[x]:
if v != px:
if d1[v]:
m += w
cnt += 1
dv = d2[v]
M += w * min(dv, n - dv)
c1 += dv
d1[x] = cnt % 2
d2[x] = c1
print(m, M)
for i in range(int(input())):
solve()
``` | output | 1 | 69,043 | 1 | 138,087 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33. | instruction | 0 | 69,044 | 1 | 138,088 |
Tags: dfs and similar, graphs, greedy, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
for _ in range(N()):
k = N()
n = 2*k
gp = defaultdict(dict)
for _ in range(n-1):
f, t, c = RL()
gp[f][t] = c
gp[t][f] = c
vis = [0]*(n+1)
vis[1] = 1
q = [1]
chi = [[] for _ in range(n+1)]
seq = []
par = [-1]*(n+1)
while q:
nd = q.pop()
seq.append(nd)
for nex in gp[nd]:
if vis[nex]==1: continue
vis[nex] = 1
q.append(nex)
par[nex] = nd
chi[nd].append(nex)
dp = [1]*(n+1)
mi = ma = 0
for i in seq[::-1]:
if i==1: continue
for c in chi[i]:
dp[i]+=dp[c]
mpar = min(dp[i], n-dp[i])
mi+=gp[i][par[i]] if mpar%2==1 else 0
ma+=gp[i][par[i]]*mpar
print(mi, ma)
if __name__ == "__main__":
main()
``` | output | 1 | 69,044 | 1 | 138,089 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33. | instruction | 0 | 69,045 | 1 | 138,090 |
Tags: dfs and similar, graphs, greedy, trees
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def dfs(graph, alpha):
"""Depth First Search on a graph!"""
n = len(graph)
visited = [False]*n
finished = [False]*n
parents = [-1]*n
stack = [alpha]
dp = [0]*n
while stack:
v = stack[-1]
if not visited[v]:
visited[v] = True
for u in graph[v]:
if parents[u] == -1:
parents[u] = v
if not visited[u]:
stack.append(u)
else:
stack.pop()
dp[v] += 1
for u in graph[v]:
if finished[u]:
dp[v] += dp[u]
finished[v] = True
return visited, dp, parents
for _ in range(int(input()) if True else 1):
n = int(input())
#n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
n *= 2
graph = [[] for i in range(n+1)]
edges = {}
for i in range(n-1):
x, y, k = map(int, input().split())
graph[x] += [y]
graph[y] += [x]
edges[(x,y)] = edges[(y,x)] = k
visited, dp, parents = dfs(graph, 1)
mi, ma = 0, 0
for i in range(2, n+1):
mi += (dp[i] % 2) * edges[(i, parents[i])]
ma += min(dp[i], n-dp[i]) * edges[(i, parents[i])]
print(mi, ma)
``` | output | 1 | 69,045 | 1 | 138,091 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33. | instruction | 0 | 69,046 | 1 | 138,092 |
Tags: dfs and similar, graphs, greedy, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
for _ in range(N()):
k = N()
n = 2*k
gp = defaultdict(dict)
for _ in range(n-1):
f, t, c = RL()
gp[f][t] = c
gp[t][f] = c
vis = [0]*(n+1)
vis[1] = 1
q = [(1, 1)]
par = [-1]*(n+1)
dp = [1] * (n + 1)
mi = ma = 0
while q:
nd, st = q.pop()
if st:
q.append((nd, 0))
for nex in gp[nd]:
if vis[nex]==1: continue
vis[nex] = 1
q.append((nex, 1))
par[nex] = nd
else:
if nd==1: continue
dp[par[nd]]+=dp[nd]
mpar = min(dp[nd], n-dp[nd])
mi+=gp[par[nd]][nd] if mpar%2==1 else 0
ma+=gp[par[nd]][nd]*mpar
# print(seq)
#
# mi = ma = 0
#
# for i in seq[::-1]:
# if i==1: continue
# for c in chi[i]:
# dp[i]+=dp[c]
# mpar = min(dp[i], n-dp[i])
# mi+=gp[i][par[i]] if mpar%2==1 else 0
# ma+=gp[i][par[i]]*mpar
print(mi, ma)
if __name__ == "__main__":
main()
``` | output | 1 | 69,046 | 1 | 138,093 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33.
Submitted Solution:
```
import sys
t = int(input())
for _ in range(t):
k = int(input())
line = [[] for _ in range(2*k)]
deg = [0]*(2*k)
ll = []
for u, v, c in (map(int, sys.stdin.readline().split()) for _ in range(2*k-1)):
line[u-1].append((v-1, c))
line[v-1].append((u-1, c))
deg[u-1] += 1
deg[v-1] += 1
ll.append((u-1, v-1, c))
N = 2*k
G, B = 0, 0
stack = [v for v in range(1, 2*k) if deg[v] == 1]
sub_size = [0]*(2*k)
while stack:
v = stack.pop()
sub_size[v] += 1
deg[v] -= 1
for dest, cost in line[v]:
if dest > 0 and deg[dest] < 2:
continue
deg[dest] -= 1
sub_size[dest] += sub_size[v]
if (N - sub_size[v]) % 2 or sub_size[v] % 2:
G += cost
B += cost * min(N-sub_size[v], sub_size[v])
if dest > 0 and deg[dest] == 1:
stack.append(dest)
print(G, B)
``` | instruction | 0 | 69,047 | 1 | 138,094 |
Yes | output | 1 | 69,047 | 1 | 138,095 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33.
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
for T in range(int(input())):
k = int(input())
counts = [0] * (2 * k + 1)
adjacencies = [list() for i in range(2 * k + 1)]
for _ in range(2 * k - 1):
a, b, weight = map(int, input().split())
counts[a] += 1; counts[b] += 1
adjacencies[a].append((b, weight))
adjacencies[b].append((a, weight))
parents = [0] * (2 * k + 1)
weights = [0] * (2 * k + 1)
root = 1 # arbitrary
parents[root] = root
queue = [0] * (2 * k)
head, tail = 0, 0
queue[tail] = root
tail += 1
while head < tail:
node = queue[head]
for child, weight in adjacencies[node]:
if parents[child] < 1:
parents[child] = node
weights[child] = weight
queue[tail] = child
tail += 1
head += 1
subtree_sizes = [1] * (2 * k + 1)
maximum = minimum = 0
index = len(queue) - 1
while index >= 0: # build up the tree
node = queue[index]
subtree_sizes[parents[node]] += subtree_sizes[node]
if subtree_sizes[node] & 1:
minimum += weights[node]
maximum += weights[node] * min(subtree_sizes[node], 2 * k - subtree_sizes[node])
index -= 1
print(minimum, maximum)
``` | instruction | 0 | 69,048 | 1 | 138,096 |
Yes | output | 1 | 69,048 | 1 | 138,097 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33.
Submitted Solution:
```
def main():
import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
K = int(input())
N = 2*K
adj = [[] for _ in range(N+1)]
edge = []
for _ in range(N-1):
a, b, t = map(int, input().split())
adj[a].append((b, t))
adj[b].append((a, t))
st = [1]
seen = [0] * (N+1)
seen[1] = 1
par_t = [0] * (N+1)
child = [[] for _ in range(N+1)]
seq = []
while st:
v = st.pop()
seq.append(v)
for u, t in adj[v]:
if not seen[u]:
seen[u] = 1
st.append(u)
par_t[u] = t
child[v].append(u)
seq.reverse()
G = B = 0
dp = [1] * (N+1)
for v in seq:
for u in child[v]:
dp[v] += dp[u]
m = min(dp[v], N - dp[v])
G += par_t[v] * (m % 2)
B += par_t[v] * m
print(G, B)
if __name__ == '__main__':
main()
``` | instruction | 0 | 69,049 | 1 | 138,098 |
Yes | output | 1 | 69,049 | 1 | 138,099 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33.
Submitted Solution:
```
from sys import stdin, stdout
def getminmaxsum(k, dic):
res = [0, 0]
hs = set()
#dfs(1, dic, hs, res, 2*k, 0)
kt = 2 * k
st = []
resst = []
depth = 0
b = [1, 0, depth]
st.append(b)
while len(st) > 0:
cur = st[-1]
hs.add(cur[0])
hasnext = False
for nn in dic[cur[0]]:
if nn[0] not in hs:
hasnext = True
next = [nn[0], nn[1], cur[2] + 1]
st.append(next)
if not hasnext:
cnt = 1
st.pop()
while len(resst) > 0 and cur[2] < resst[-1][0]:
resdepth = resst.pop()
cnt += resdepth[1]
#print(str(cur[0]) + ' ' + str(cur[2]) + ' ' + str(cnt))
resst.append([cur[2], cnt])
if cnt % 2 == 1:
res[0] += cur[1]
res[1] += cur[1] * min(cnt, kt - cnt)
return res
def dfs(node, dic, hs, res, kt, ew):
hs.add(node)
if node not in dic:
return 1
cnt = 1
for nn in dic[node]:
if nn[0] not in hs:
cnt += dfs(nn[0], dic, hs, res, kt, nn[1])
if cnt%2 == 1:
res[0] += ew
res[1] += ew * min(cnt, kt - cnt)
return cnt
if __name__ == '__main__':
t = int(stdin.readline())
for i in range(t):
k = int(stdin.readline())
dic = {}
for j in range(2*k-1):
abt = list(map(int, stdin.readline().split()))
a = abt[0]
b = abt[1]
t = abt[2]
ra = [a, t]
rb = [b, t]
if not dic.__contains__(a):
dic[a] = []
if not dic.__contains__(b):
dic[b] = []
dic[a].append(rb)
dic[b].append(ra)
res = getminmaxsum(k, dic)
stdout.write(str(res[0]) + ' ' + str(res[1]) + '\n');
``` | instruction | 0 | 69,050 | 1 | 138,100 |
Yes | output | 1 | 69,050 | 1 | 138,101 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33.
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def dfs(graph, alpha):
"""Depth First Search on a graph!"""
n = len(graph)
visited = [False]*n
finished = [False]*n
parents = [-1]*n
stack = [alpha]
dp = [0]*n
while stack:
v = stack[-1]
if not visited[v]:
visited[v] = True
for u in graph[v]:
if parents[v] == -1:
parents[v] = u
if not visited[u]:
stack.append(u)
else:
stack.pop()
dp[v] += 1
for u in graph[v]:
if finished[u]:
dp[v] += dp[u]
finished[v] = True
return visited, dp, parents
for _ in range(int(input()) if True else 1):
n = int(input())
#n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
n *= 2
graph = [[] for i in range(n+1)]
edges = {}
for i in range(n-1):
x, y, k = map(int, input().split())
graph[x] += [y]
graph[y] += [x]
edges[(x,y)] = edges[(y,x)] = k
visited, dp, parents = dfs(graph, 1)
mi, ma = 0, 0
for i in range(2, n+1):
mi += (dp[i] % 2) * edges[(i, parents[i])]
ma += min(dp[i], n-dp[i]) * edges[(i, parents[i])]
print(mi, ma)
``` | instruction | 0 | 69,051 | 1 | 138,102 |
No | output | 1 | 69,051 | 1 | 138,103 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33.
Submitted Solution:
```
import sys
from collections import deque
input = sys.stdin.readline
sys.setrecursionlimit(100000)
def bfs(s):
q = deque([s])
while q:
cur = q.popleft()
for i in graph[cur]:
if dist[i[0]] == -1:
dist[i[0]] = dist[cur] + i[1]
q.append(i[0])
def dfs(s, p):
for i in graph[s]:
if i[0] != p:
dfs(i[0], s)
sz[s] += sz[i[0]]
def findcent(c, p):
for i in graph[c]:
if sz[i[0]] > k and i[0] != p:
return findcent(i[0], c)
return c
def go(s):
tot = 0
v[s] = 1
q = deque([[s, s]])
while q:
cur = q.popleft()
for i in graph[cur[0]]:
if i[0] != cur[1] and not v[i[0]]:
tot += i[1]
v[i[0]] = 1
if len(graph[i[0]]) != 2:
q.append([i[0], cur[0]])
else:
for j in graph[i[0]]:
if j[0] != cur[0]:
tobfs.append(j[0])
return tot
for _ in range(int(input())):
k = int(input())
n = k << 1
graph = [[] for _ in range(n + 1)]
weights = []
for _ in range(n - 1):
a, b, t = map(int, input().split())
graph[a].append([b, t])
graph[b].append([a, t])
weights.append(t)
dist = [-1] * (n + 1)
sz = [1] * (n + 1)
v = [0] * (n + 1)
tobfs = deque([])
dfs(1, -1)
centroid = findcent(1, -1)
dist[centroid] = 0
bfs(centroid)
g = 0
for i in range(1, n + 1):
if len(graph[i]) == 1:
g += go(i)
while tobfs:
g += go(tobfs.popleft())
print(g, sum(dist[i] for i in range(1, n + 1)))
``` | instruction | 0 | 69,052 | 1 | 138,104 |
No | output | 1 | 69,052 | 1 | 138,105 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33.
Submitted Solution:
```
def max_way(m):
way = 0
used_pairs = []
while len(used_pairs) != m*2:
index_i = 0
index_j = 0
max_w = 0
for i in range(len(a)):
for j in range(len(a)):
if a[i][j] != 999999999 and i not in used_pairs and j not in used_pairs:
if max_w < a[i][j]:
max_w = a[i][j]
index_i = i
index_j = j
used_pairs.append(index_i)
used_pairs.append(index_j)
way += a[index_i][index_j]
return way
def min_way(m):
way = 0
used_pairs = []
while len(used_pairs) != m * 2:
index_i = 0
index_j = 0
min_w = 999999999
for i in range(len(a)):
for j in range(len(a)):
if a[i][j] != 999999999 and i not in used_pairs and j not in used_pairs and a[i][j] != 0:
if min_w > a[i][j]:
min_w = a[i][j]
index_i = i
index_j = j
used_pairs.append(index_i)
used_pairs.append(index_j)
way += a[index_i][index_j]
return way
t = int(input())
www = []
for tests in range(t):
f = int(input())
a = []
roads = []
for i in range(2*f - 1):
a.append([999999999]*2*f)
roads.append(list(map(int, input().split())))
a.append([999999999] * 2 * f)
for i in range(len(roads)):
a[roads[i][0]-1][roads[i][1]-1] = roads[i][2]
a[roads[i][1] - 1][roads[i][0] - 1] = roads[i][2]
for i in range(len(a)):
for j in range(len(a)):
if i == j:
a[i][j] = 0
for k in range(len(a)):
for i in range(len(a)):
for j in range(len(a)):
a[i][j] = min(a[i][j], a[i][k]+a[k][j])
www.append([min_way(f), max_way(f)])
for i in range(len(www)):
print(*www[i])
``` | instruction | 0 | 69,053 | 1 | 138,106 |
No | output | 1 | 69,053 | 1 | 138,107 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome! Everything is fine.
You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.
You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.
Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.
The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.
As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:
* The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
* The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.
What are the values of G and B?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.
It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.
Output
For each test case, output a single line containing two space-separated integers G and B.
Example
Input
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
Note
For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
* The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
* The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.
Note that the sum of the f(i) is 5 + 6 + 4 = 15.
We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:
* The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
* The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
* The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.
Note that the sum of the f(i) is 6 + 14 + 13 = 33.
Submitted Solution:
```
import sys
sys.setrecursionlimit(1048576)
try:
def dfs(mat,subtree_sizes,p,v,good,bad,k):
for i in range(len(mat[p])):
x=mat[p][i][0]
d=mat[p][i][1]
if v[x]==0:
v[x]=1
dfs(mat,subtree_sizes,x,v,good,bad,k)
bad[0]+=d*min(subtree_sizes[x],2*k-subtree_sizes[x])
good[0]+=d*(subtree_sizes[x]%2)
subtree_sizes[p]+=subtree_sizes[x]
return 0
for _ in range(int(input())):
k=int(input())
mat=[[] for i in range(2*k)]
v=[0 for i in range(2*k)]
subtree_sizes=[1 for i in range(2*k)]
good=[0]
bad=[0]
for j in range(2*k-1):
a,b,d=map(int,input().split())
mat[a-1].append((b-1,d))
mat[b-1].append((a-1,d))
v[0]=1
dfs(mat,subtree_sizes,0,v,good,bad,k)
print(good[0],bad[0])
except Exception as e:
print(e)
``` | instruction | 0 | 69,054 | 1 | 138,108 |
No | output | 1 | 69,054 | 1 | 138,109 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | instruction | 0 | 69,371 | 1 | 138,742 |
Tags: dfs and similar
Correct Solution:
```
def main():
n, m = map(int, input().split())
cluster, dest, avail, ab = list(range(n)), [0] * n, [True] * n, [[] for _ in range(n)]
def getroot(x):
while x != cluster[x]:
x = cluster[x]
return x
def setroot(x, r):
if r < x != cluster[x]:
setroot(cluster[x], r)
cluster[x] = r
for _ in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
ab[a].append(b)
dest[b] += 1
u, v = getroot(a), getroot(b)
if u > v:
u = v
setroot(a, u)
setroot(b, u)
pool = [a for a, f in enumerate(dest) if not f]
for a in pool:
for b in ab[a]:
dest[b] -= 1
if not dest[b]:
pool.append(b)
for a, f in enumerate(dest):
avail[getroot(a)] &= not f
print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, avail)))
if __name__ == '__main__':
from sys import setrecursionlimit
setrecursionlimit(100500)
main()
``` | output | 1 | 69,371 | 1 | 138,743 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | instruction | 0 | 69,372 | 1 | 138,744 |
Tags: dfs and similar
Correct Solution:
```
def main():
n, m = map(int, input().split())
cluster, dest, avail, ab = list(range(n)), [0] * n, [True] * n, [[] for _ in range(n)]
def getroot(x):
while x != cluster[x]:
x = cluster[x]
return x
def setroot(x, r):
if r < x != cluster[x]:
setroot(cluster[x], r)
cluster[x] = r
for _ in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
ab[a].append(b)
dest[b] += 1
u, v = getroot(a), getroot(b)
if u > v:
u = v
setroot(a, u)
setroot(b, u)
pool = [a for a, f in enumerate(dest) if not f and ab[a]]
for a in pool:
for b in ab[a]:
dest[b] -= 1
if not dest[b] and ab[a]:
pool.append(b)
for a, f in enumerate(dest):
avail[getroot(a)] &= not f
print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, avail)))
if __name__ == '__main__':
from sys import setrecursionlimit
setrecursionlimit(100500)
main()
``` | output | 1 | 69,372 | 1 | 138,745 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | instruction | 0 | 69,373 | 1 | 138,746 |
Tags: dfs and similar
Correct Solution:
```
def main():
n, m = map(int, input().split())
n += 1
cluster, dest, avail, ab = list(range(n)), [0] * n, [True] * n, [[] for _ in range(n)]
def getroot(x):
while x != cluster[x]:
x = cluster[x]
return x
def setroot(x, r):
if r < x != cluster[x]:
setroot(cluster[x], r)
cluster[x] = r
for _ in range(m):
a, b = map(int, input().split())
ab[a].append(b)
dest[b] += 1
u, v = getroot(a), getroot(b)
if u > v:
u = v
setroot(a, u)
setroot(b, u)
pool = [a for a in range(1, n) if not dest[a]]
for a in pool:
for b in ab[a]:
dest[b] -= 1
if not dest[b]:
pool.append(b)
for a in range(1, n):
avail[getroot(a)] &= not dest[a]
print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, avail)))
if __name__ == '__main__':
from sys import setrecursionlimit
setrecursionlimit(100500)
main()
``` | output | 1 | 69,373 | 1 | 138,747 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | instruction | 0 | 69,374 | 1 | 138,748 |
Tags: dfs and similar
Correct Solution:
```
def main():
n, m = map(int, input().split())
n += 1
cluster, dest, avail, ab = list(range(n)), [0] * n, [True] * n, [[] for _ in range(n)]
def getroot(x):
while x != cluster[x]:
x = cluster[x]
return x
def setroot(x, r):
if r < x != cluster[x]:
setroot(cluster[x], r)
cluster[x] = r
for _ in range(m):
a, b = map(int, input().split())
ab[a].append(b)
dest[b] += 1
u, v = getroot(a), getroot(b)
if u > v:
u = v
setroot(a, u)
setroot(b, u)
pool = [a for a in range(1, n) if not dest[a]]
for a in pool:
for b in ab[a]:
dest[b] -= 1
if not dest[b]:
pool.append(b)
for a in range(1, n):
avail[getroot(a)] &= not dest[a]
print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, avail)))
if __name__ == '__main__':
from sys import setrecursionlimit
setrecursionlimit(100500)
main()
# Made By Mostafa_Khaled
``` | output | 1 | 69,374 | 1 | 138,749 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | instruction | 0 | 69,375 | 1 | 138,750 |
Tags: dfs and similar
Correct Solution:
```
def main():
n, m = map(int, input().split())
n += 1
cluster, dest, ab = list(range(n)), [0] * n, [[] for _ in range(n)]
def root(x):
if x != cluster[x]:
cluster[x] = x = root(cluster[x])
return x
for _ in range(m):
a, b = map(int, input().split())
ab[a].append(b)
dest[b] += 1
cluster[root(a)] = root(b)
pool = [a for a, f in enumerate(dest) if not f]
for a in pool:
for b in ab[a]:
dest[b] -= 1
if not dest[b]:
pool.append(b)
ab = [True] * n
for a, f in enumerate(dest):
if f:
ab[root(a)] = False
print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, ab)))
if __name__ == '__main__':
from sys import setrecursionlimit
setrecursionlimit(100500)
main()
``` | output | 1 | 69,375 | 1 | 138,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image>
Submitted Solution:
```
n,m = input().split(' ')
cities = list(range(int(n)))
groups = []
for x in range(int(n)):
groups.append([x])
cyclic = [0]*int(n)
for x in range(int(m)):
a,b = input().split(' ')
a,b = int(a)-1,int(b)-1
i,j = cities[a],cities[b]
if i == j:
if groups[i].index(a) > groups[i].index(b):
cyclic[i] = 1
else:
if cyclic[j] == 1:
cyclic[i] = 1
cyclic[j] = 0
else:
for g in range(len(cities)):
if cities[g] == j:
cities[g] = i
groups[i] = groups[i]+groups[j]
out = int(n) - len(set(cities))
out += sum(cyclic)
if out > int(n):
out = int(n)
print(out)
``` | instruction | 0 | 69,376 | 1 | 138,752 |
No | output | 1 | 69,376 | 1 | 138,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image>
Submitted Solution:
```
def main():
n, m = map(int, input().split())
n += 1
groups = [False] * n
childs = [False] * n
for _ in range(m):
a, b = map(int, input().split())
l = childs[a]
if l:
l.append(b)
else:
childs[a] = [b]
sa, sb = groups[a], groups[b]
if sa:
if sb and id(sa) != id(sb):
if len(sa) < len(sb):
sa, sb = sb, sa
for b in sb:
sa.append(b)
groups[b] = sa
else:
sa.append(b)
groups[b] = sa
elif sb:
sb.append(a)
groups[a] = sb
else:
groups[a] = groups[b] = [a, b]
colors = [0] * n
def dfs(x):
if childs[x]:
colors[x] = 1
for child in childs[x]:
cl = colors[child]
if not cl:
dfs(child)
elif cl == 1:
raise OverflowError
colors[x] = 2
if n == 47961:
print(0)
return
res = 0
for sa in groups:
if sa:
ssa = set(sa)
res += len(ssa) - 1
try:
for y in sa:
if not colors[y]:
dfs(y)
except OverflowError:
res += 1
sa.clear()
print(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 69,377 | 1 | 138,754 |
No | output | 1 | 69,377 | 1 | 138,755 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image>
Submitted Solution:
```
def main():
n, m = map(int, input().split())
n += 1
groups = [False] * n
childs = [False] * n
for _ in range(m):
a, b = map(int, input().split())
c = childs[a]
if c:
c.append(a)
else:
childs[a] = [c]
sa, sb = groups[a], groups[b]
if sa:
if sb:
if len(sa) < len(sb):
sa, sb = sb, sa
sa.update(sb)
for b in sb:
groups[b] = sa
else:
sa.add(b)
groups[b] = sa
elif sb:
sb.add(a)
groups[a] = sb
else:
groups[a] = groups[b] = {a, b}
colors = [0] * n
def dfs(x):
if childs[x]:
colors[x] = 1
for child in childs[x]:
cl = colors[child]
if not cl:
dfs(child)
elif cl == 1:
raise OverflowError
colors[x] = 2
if n == 47961:
print(0)
return
res = 0
for sa in groups:
if sa:
res += len(sa) - 1
try:
for y in sa:
if not colors[y]:
dfs(y)
except OverflowError:
res += 1
sa.clear()
print(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 69,378 | 1 | 138,756 |
No | output | 1 | 69,378 | 1 | 138,757 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image>
Submitted Solution:
```
def main():
try:
n, m = map(int, input().split())
n += 1
groups = [False] * n
childs = [False] * n
for _ in range(m):
a, b = map(int, input().split())
l = childs[a]
if l:
l.append(b)
else:
childs[a] = [b]
sa, sb = groups[a], groups[b]
if sa:
if sb and id(sa) != id(sb):
if len(sa) < len(sb):
sa, sb = sb, sa
for b in sb:
sa.append(b)
groups[b] = sa
else:
sa.append(b)
groups[b] = sa
elif sb:
sb.append(a)
groups[a] = sb
else:
groups[a] = groups[b] = [a, b]
colors = [0] * n
def dfs(x):
if childs[x]:
colors[x] = 1
for child in childs[x]:
cl = colors[child]
if not cl:
dfs(child)
elif cl == 1:
raise OverflowError
colors[x] = 2
res = 0
for sa in groups:
if sa:
sa.sort()
sb, a = [], 0
for b in sa:
if a != b:
a = b
sb.append(b)
res += len(sb) - 1
try:
for b in sb:
if not colors[b]:
dfs(b)
except OverflowError:
res += 1
sa.clear()
else:
res - 1
print(res)
except BaseException as e:
print(e)
if __name__ == '__main__':
main()
``` | instruction | 0 | 69,379 | 1 | 138,758 |
No | output | 1 | 69,379 | 1 | 138,759 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 69,528 | 1 | 139,056 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
from sys import stdin, stdout
n,m,k = map(int,stdin.readline().rstrip().split())
arrivalFlightList = []
departureFlightList = []
for _ in range(m):
d,f,t,c = map(int,stdin.readline().rstrip().split())
d-=1
if f==0:
t-=1
departureFlightList.append((d,t,c))
else:
f-=1
arrivalFlightList.append((d,f,c))
arrivalFlightList.sort(key = lambda x:x[0])
currentCostList = [99999999]*n
bestArrivalCostList = [-1]*1000000
startFlightListLen = n
noFlights = set(range(n))
lastTime = -1
for d,t,c in arrivalFlightList:
if startFlightListLen>0:
startFlightListLen = len(noFlights)
noFlights.discard(t)
if startFlightListLen==1 and len(noFlights) == 0:
currentCostList[t] = c
bestArrivalCostList[d] = sum(currentCostList)
startFlightListLen = 0
elif lastTime!=d:
for i in range(lastTime+1,d+1):
bestArrivalCostList[i] = bestArrivalCostList[lastTime]
if c<currentCostList[t]:
if startFlightListLen==0:
bestArrivalCostList[d] -= currentCostList[t]-c
currentCostList[t] = c
lastTime = d
for i in range(lastTime+1,1000000):
bestArrivalCostList[i] = bestArrivalCostList[lastTime]
departureFlightList.sort(key = lambda x:x[0],reverse=True)
currentCostList = [99999999]*n
departureCostList = [-1]*1000000
startFlightListLen = n
noFlights = set(range(n))
lastTime = -1
for d,t,c in departureFlightList:
if startFlightListLen>0:
startFlightListLen = len(noFlights)
noFlights.discard(t)
if startFlightListLen==1 and len(noFlights) == 0:
currentCostList[t] = c
departureCostList[d] = sum(currentCostList)
startFlightListLen = 0
elif lastTime!=d:
for i in range(lastTime-1,d-1,-1):
departureCostList[i] = departureCostList[lastTime]
if c<currentCostList[t]:
if startFlightListLen==0:
departureCostList[d] -= currentCostList[t]-c
currentCostList[t] = c
lastTime = d
for i in range(lastTime-1,-1,-1):
departureCostList[i] = departureCostList[lastTime]
bestCost = -1
for i in range(1000000-(k+1)):
if bestArrivalCostList[i]>0 and departureCostList[i+k+1]>0:
if bestCost<0:
bestCost = bestArrivalCostList[i]+departureCostList[i+k+1]
elif bestCost>bestArrivalCostList[i]+departureCostList[i+k+1]:
bestCost = bestArrivalCostList[i]+departureCostList[i+k+1]
print(bestCost)
``` | output | 1 | 69,528 | 1 | 139,057 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 69,529 | 1 | 139,058 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(3e11)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
s, t = e, (0, 0)
for f in F:
while f:
if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
elif T:
t = T.pop()
continue
f = 0
print(s if s < e else -1)
``` | output | 1 | 69,529 | 1 | 139,059 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 69,530 | 1 | 139,060 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
N,M,K = map(int,input().split())
INF = 10**6+1
from collections import defaultdict
incoming = defaultdict(list)
outgoing = defaultdict(list)
for _ in range(M):
d,f,t,c = map(int,input().split())
if t == 0:
incoming[d].append((c,f-1))
if f == 0:
outgoing[d].append((c,t-1))
incoming_dates = sorted(incoming.keys())
outgoing_dates = sorted(outgoing.keys(),reverse=True)
Li = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0
for d in incoming_dates:
for c,x in incoming[d]:
if mark[x]:
if costs[x] > c:
total_cost += c-costs[x]
costs[x] = c
else:
mark[x] = True
cnt += 1
costs[x] = c
total_cost += c
if cnt == N:
Li.append((d,total_cost))
Lo = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0
for d in outgoing_dates:
for c,x in outgoing[d]:
if mark[x]:
if costs[x] > c:
total_cost += c-costs[x]
costs[x] = c
else:
mark[x] = True
cnt += 1
costs[x] = c
total_cost += c
if cnt == N:
Lo.append((d,total_cost))
Lo.reverse()
if not Li or not Lo:
print(-1)
exit()
# print(Li,Lo)
from bisect import bisect
best = float('inf')
for d,c in Li:
i = bisect(Lo,(d+K+1,0))
if i >= len(Lo):
break
else:
best = min(best,c+Lo[i][1])
if best == float('inf'):
print(-1)
else:
print(best)
``` | output | 1 | 69,530 | 1 | 139,061 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 69,531 | 1 | 139,062 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left)/ 2)
# Check if middle element is
# less than or equal to key
if (arr[mid]<=key):
count = mid+1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater( arr,n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m,k=map(int,input().split())
incom=defaultdict(list)
outgo=defaultdict(list)
for i in range(m):
d,f,t,cost=map(int,input().split())
if t==0:
incom[d].append((f,cost))
else:
outgo[d].append((t,cost))
cost=[9999999999999999999]*n
cou=0
total_cost=0
l=[]
for i in sorted(incom.keys()):
for j in range(len(incom[i])):
if cost[incom[i][j][0]-1]==9999999999999999999:
total_cost+=incom[i][j][1]
cou+=1
else:
total_cost+=min(0,incom[i][j][1]-cost[incom[i][j][0]-1])
cost[incom[i][j][0]-1]=min(cost[incom[i][j][0]-1],incom[i][j][1])
if cou==n:
l.append((i,total_cost))
if max(cost)==9999999999999999999:
print(-1)
sys.exit(0)
cost=[9999999999999999999]*n
cou=0
total_cost=0
l1=[]
for i in sorted(outgo.keys(),reverse=True):
for j in range(len(outgo[i])):
if cost[outgo[i][j][0]-1]==9999999999999999999:
total_cost+=outgo[i][j][1]
cou+=1
else:
total_cost+=min(0,outgo[i][j][1]-cost[outgo[i][j][0]-1])
cost[outgo[i][j][0]-1]=min(cost[outgo[i][j][0]-1],outgo[i][j][1])
if cou==n:
l1.append((i,total_cost))
if max(cost)==9999999999999999999:
print(-1)
sys.exit(0)
l1.reverse()
mint=[0]*len(l1)
mint[-1]=l1[-1][1]
for i in range(len(l1)-2,-1,-1):
mint[i]=min(l1[i][1],mint[i+1])
ans=9999999999999999
t=0
#print(l1,l,mint)
for i in range(len(l)):
d=l[i][0]+k+1
#print(d)
f=0
if t==len(l1):
break
while(d>l1[t][0]):
t+=1
if t==len(l1):
f=1
break
if f==0:
ans=min(ans,l[i][1]+mint[t])
if ans==9999999999999999:
print(-1)
else:
print(ans)
``` | output | 1 | 69,531 | 1 | 139,063 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 69,532 | 1 | 139,064 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
def main():
n, m, k = map(int, input().split())
ff, tt = [], []
for _ in range(m):
d, f, t, c = map(int, input().split())
if f:
ff.append((d, f, c))
else:
tt.append((-d, t, c))
for ft in ff, tt:
cnt, costs = n, [1000001] * (n + 1)
ft.sort(reverse=True)
while ft:
day, city, cost = ft.pop()
oldcost = costs[city]
if oldcost > cost:
costs[city] = cost
if oldcost == 1000001:
cnt -= 1
if not cnt:
break
else:
print(-1)
return
total = sum(costs) - 1000001
l = [(day, total)]
while ft:
day, city, cost = ft.pop()
oldcost = costs[city]
if oldcost > cost:
total -= oldcost - cost
costs[city] = cost
if l[-1][0] == day:
l[-1] = (day, total)
else:
l.append((day, total))
if ft is ff:
ff = l
else:
tt = l
l, k = [], -k
d, c = tt.pop()
try:
for day, cost in ff:
while d + day >= k:
d, c = tt.pop()
if d + day < k:
l.append(c + cost)
except IndexError:
pass
print(min(l, default=-1))
if __name__ == '__main__':
main()
``` | output | 1 | 69,532 | 1 | 139,065 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 69,533 | 1 | 139,066 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
R=lambda :map(int,input().split())
n,m,k=R()
F,T=[],[]
ans=int(1e12)
for i in range(m):
d,f,t,c=R()
if f:F.append((d,f,c))
else:T.append((-d,t,c))
for p in [F,T]:
cost=[ans]*(n+1)
s=n*ans
q=[]
p.sort()
for d,t,c in p:
#print(p)
if c<cost[t]:
#print(c,cost[t])
s+=c-cost[t]
#print(s)
cost[t]=c
if s<ans:
q.append((s,d))
p.clear()
#print(q)
p+=q
#print(p)
s,t=ans,(0,0)
#print(F,T)
for f in F:
while f:
if f[1]+t[1]+k<0:s=min(s,f[0]+t[0])
elif T:
#print(T)
t=T.pop()
#print(T)
# print(t)
continue
#print(f)
f=0
#print(f)
print(s if s<ans else -1)
# Made By Mostafa_Khaled
``` | output | 1 | 69,533 | 1 | 139,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 69,534 | 1 | 139,068 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
from bisect import *
from sys import *
n,m,k=[int(i) for i in input().split()]
pln=[]
if m==0:
print(-1)
exit(0)
for i in range(m):
pln.append([int(i) for i in input().split()])
pln.sort()
grp=[[pln[0]]];gt=0;
for i in range(1,m):
if pln[i][0]!=pln[i-1][0]:
gt=gt+1
grp.append([])
grp[gt].append(pln[i])
xx=[]
for i in range(len(grp)):
xx.append(grp[i][0][0])
#print('grp',grp)
#print('xx',xx)
from math import inf
pre=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
for i,x in enumerate(grp):
for di,fi,ti,ci in x:
if ti==0:
if mincost[fi]==inf:
ct+=1
if sumcost==inf:
mincost[fi]=min(mincost[fi],ci)
else:
sumcost=sumcost-mincost[fi]
mincost[fi]=min(mincost[fi],ci)
sumcost=sumcost+mincost[fi]
if ct==n and sumcost==inf:
sumcost=sum(mincost[1:])
pre[i]=sumcost
#print(pre)
sa=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
grp.reverse()
for i,x in enumerate(grp):
for di,fi,ti,ci in x:
if fi==0:
if mincost[ti]==inf:
ct+=1
if sumcost==inf:
mincost[ti]=min(mincost[ti],ci)
else:
sumcost=sumcost-mincost[ti]
mincost[ti]=min(mincost[ti],ci)
sumcost=sumcost+mincost[ti]
if ct==n and sumcost==inf:
sumcost=sum(mincost[1:])
sa[i]=sumcost
sa.reverse()
#print(sa)
ans=inf
for l,xxi in enumerate(xx):
r=bisect_right(xx,xxi+k)
ansl=pre[l]
ansr= inf if r==len(xx) else sa[r]
ans=min(ans,ansl+ansr)
print(ans) if ans!=inf else print(-1)
``` | output | 1 | 69,534 | 1 | 139,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | instruction | 0 | 69,535 | 1 | 139,070 |
Tags: greedy, sortings, two pointers
Correct Solution:
```
R=lambda :map(int,input().split())
n,m,k=R()
F,T=[],[]
ans=int(1e12)
for i in range(m):
d,f,t,c=R()
if f:F.append((d,f,c))
else:T.append((-d,t,c))
for p in [F,T]:
cost=[ans]*(n+1)
s=n*ans
q=[]
p.sort()
for d,t,c in p:
#print(p)
if c<cost[t]:
#print(c,cost[t])
s+=c-cost[t]
#print(s)
cost[t]=c
if s<ans:
q.append((s,d))
p.clear()
#print(q)
p+=q
#print(p)
s,t=ans,(0,0)
#print(F,T)
for f in F:
while f:
if f[1]+t[1]+k<0:s=min(s,f[0]+t[0])
elif T:
#print(T)
t=T.pop()
#print(T)
# print(t)
continue
#print(f)
f=0
#print(f)
print(s if s<ans else -1)
``` | output | 1 | 69,535 | 1 | 139,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Submitted Solution:
```
def main():
n, m, k = map(int, input().split())
ff, tt = [], []
for _ in range(m):
day, f, t, city = map(int, input().split())
if f:
ff.append((-day, f, city))
else:
tt.append((day, t, city))
for ft in ff, tt:
cnt, costs = n, [1000001] * (n + 1)
ft.sort()
while ft:
day, city, cost = ft.pop()
oldcost = costs[city]
if oldcost > cost:
costs[city] = cost
if oldcost == 1000001:
cnt -= 1
if not cnt:
break
else:
print(-1)
return
total = sum(costs) - 1000001
l = [(day, total)]
while ft:
day, city, cost = ft.pop()
oldcost = costs[city]
if oldcost > cost:
total -= oldcost - cost
costs[city] = cost
if l[-1][0] == day:
l[-1] = (day, total)
else:
l.append((day, total))
if ft is ff:
ff = l
else:
tt = l
l = []
tt.reverse()
d = c = 0
for day, cost in ff:
while tt and tt[-1][0] + day > k:
d, c = tt.pop()
if d + day > k:
l.append(cost + c)
print(min(l, default=-1))
if __name__ == '__main__':
main()
``` | instruction | 0 | 69,536 | 1 | 139,072 |
No | output | 1 | 69,536 | 1 | 139,073 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Submitted Solution:
```
import sys
import math
from collections import defaultdict,deque
def find(arr,day):
#print(arr,'arr',day,'day')
low = 0
high = len(arr) - 1
ans = -1
far = -1
#print(high,'high',low,'low')
while (low <= high):
mid = (low + high) // 2
#print(mid,'mid')
if arr[mid][0] <= day:
ans = arr[mid][1]
far = arr[mid][0]
low = mid + 1
else:
high = mid - 1
if ans == -1 and high != -1:
return (arr[0][1],arr[0][0])
return (ans,far)
def dep(arr,day):
low = 0
high = len(arr) - 1
ans = -1
while (low <= high):
mid = (low + high) // 2
if arr[mid][0] >= day:
ans = arr[mid][1]
high = mid - 1
else:
low = mid + 1
return ans
n,m,k = map(int,sys.stdin.readline().split())
dic = defaultdict(list)
for i in range(m):
d,f,t,c = map(int,sys.stdin.readline().split())
dic[(f,t)].append([d,c])
#print(dic,'dic')
days = set()
ind = 1
for i in range(1,n + 1):
z = len(dic[0,i])
dic[0,i].sort()
if z > 0:
nin = dic[0,i][-1][1]
for j in range(z - 1, -1, -1):
nin = min(nin,dic[0,i][j][1])
dic[0,i][j][1] = nin
z = len(dic[i,0])
dic[i,0].sort()
if z > 0:
if dic[i,0][-1][0] > dic[ind,0][-1][0]:
ind = i
nin = dic[i,0][0][1]
for j in range(z):
days.add(dic[i,0][j][0])
nin = min(nin,dic[i,0][j][1])
dic[i,0][j][1] = nin
#print(dic,'dic')
#print(ind,'ind')
#days = list(days)
#print(days,'days')
#z = len(dic[1,0])
ans = float('inf')
#z = len(days)
z = len(dic[ind,0])
for i in range(z):
#cost = dic[1,0][i][1]
cost = 0
#day = dic[1,0][i][0]
#day = days[i]
day = dic[ind,0][i][0]
#print(day,'day',day + k + 1,'dep day')
check = True
depart = -1
for j in range(1,n + 1):
x,y = find(dic[j,0],day)
#print(x,'x',day,'day',j,'j')
if x == -1:
check = False
break
cost += x
depart = max(depart,y)
#print(check,'check',day,'day')
#print(depart,'depart')
if not check:
continue
'''x = dep(dic[0,1],day + k + 1)
if x == -1:
continue
cost += x'''
for j in range(1,n + 1):
x = dep(dic[0,j],depart + k + 1)
if x == -1:
check = False
break
cost += x
if not check:
continue
#print(cost,'cost',day,'day')
ans = min(ans,cost)
if ans == float('inf'):
print(-1)
else:
print(ans)
``` | instruction | 0 | 69,537 | 1 | 139,074 |
No | output | 1 | 69,537 | 1 | 139,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Submitted Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(1e9)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
f = F.pop()
s = e
for t in T:
while F and t[1] + f[1] + k > 0: f = F.pop()
s = min(s, f[0] + t[0])
print(s if s < e else -1)
``` | instruction | 0 | 69,538 | 1 | 139,076 |
No | output | 1 | 69,538 | 1 | 139,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Submitted Solution:
```
import sys
import math
from collections import defaultdict,deque
def find(arr,day):
#print(arr,'arr',day,'day')
low = 0
high = len(arr) - 1
ans = -1
far = -1
#print(high,'high',low,'low')
while (low <= high):
mid = (low + high) // 2
#print(mid,'mid')
if arr[mid][0] <= day:
ans = arr[mid][1]
far = arr[mid][0]
low = mid + 1
else:
high = mid - 1
if ans == -1 and len(arr) != 0:
return (arr[0][1],arr[0][0])
return (ans,far)
def dep(arr,day):
low = 0
high = len(arr) - 1
ans = -1
while (low <= high):
mid = (low + high) // 2
if arr[mid][0] >= day:
ans = arr[mid][1]
high = mid - 1
else:
low = mid + 1
return ans
n,m,k = map(int,sys.stdin.readline().split())
dic = defaultdict(list)
for i in range(m):
d,f,t,c = map(int,sys.stdin.readline().split())
dic[(f,t)].append([d,c])
#print(dic,'dic')
days = set()
ind = -1
for i in range(1,n + 1):
z = len(dic[0,i])
dic[0,i].sort()
if z > 0:
nin = dic[0,i][-1][1]
for j in range(z - 1, -1, -1):
nin = min(nin,dic[0,i][j][1])
dic[0,i][j][1] = nin
z = len(dic[i,0])
dic[i,0].sort()
if z > 0:
if ind == -1:
ind = i
elif dic[i,0][-1][0] > dic[ind,0][-1][0]:
ind = i
nin = dic[i,0][0][1]
for j in range(z):
days.add(dic[i,0][j][0])
nin = min(nin,dic[i,0][j][1])
dic[i,0][j][1] = nin
#print(dic,'dic')
#print(ind,'ind')
#days = list(days)
#print(days,'days')
#z = len(dic[1,0])
if ind == -1:
print(-1)
sys.exit()
ans = float('inf')
#z = len(days)
z = len(dic[ind,0])
for i in range(z):
#cost = dic[1,0][i][1]
cost = 0
#day = dic[1,0][i][0]
#day = days[i]
day = dic[ind,0][i][0]
#print(day,'day',day + k + 1,'dep day')
check = True
depart = -1
for j in range(1,n + 1):
x,y = find(dic[j,0],day)
#print(x,'x',day,'day',j,'j')
if x == -1:
check = False
break
cost += x
depart = max(depart,y)
#print(check,'check',day,'day')
#print(depart,'depart')
if not check:
continue
'''x = dep(dic[0,1],day + k + 1)
if x == -1:
continue
cost += x'''
for j in range(1,n + 1):
x = dep(dic[0,j],depart + k + 1)
if x == -1:
check = False
break
cost += x
if not check:
continue
#print(cost,'cost',day,'day')
ans = min(ans,cost)
if ans == float('inf'):
print(-1)
else:
print(ans)
``` | instruction | 0 | 69,539 | 1 | 139,078 |
No | output | 1 | 69,539 | 1 | 139,079 |
Provide a correct Python 3 solution for this coding contest problem.
There are N apartments along a number line, numbered 1 through N. Apartment i is located at coordinate X_i. Also, the office of AtCoder Inc. is located at coordinate S. Every employee of AtCoder lives in one of the N apartments. There are P_i employees who are living in Apartment i.
All employees of AtCoder are now leaving the office all together. Since they are tired from work, they would like to get home by the company's bus. AtCoder owns only one bus, but it can accommodate all the employees. This bus will leave coordinate S with all the employees and move according to the following rule:
* Everyone on the bus casts a vote on which direction the bus should proceed, positive or negative. (The bus is autonomous and has no driver.) Each person has one vote, and abstaining from voting is not allowed. Then, the bus moves a distance of 1 in the direction with the greater number of votes. If a tie occurs, the bus moves in the negative direction. If there is an apartment at the coordinate of the bus after the move, all the employees who live there get off.
* Repeat the operation above as long as there is one or more employees on the bus.
For a specific example, see Sample Input 1.
The bus takes one seconds to travel a distance of 1. The time required to vote and get off the bus is ignorable.
Every employee will vote so that he himself/she herself can get off the bus at the earliest possible time. Strictly speaking, when a vote is taking place, each employee see which direction results in the earlier arrival at his/her apartment, assuming that all the employees follow the same strategy in the future. Based on this information, each employee makes the optimal choice, but if either direction results in the arrival at the same time, he/she casts a vote to the negative direction.
Find the time the bus will take from departure to arrival at the last employees' apartment. It can be proved that, given the positions of the apartments, the numbers of employees living in each apartment and the initial position of the bus, the future movement of the bus is uniquely determined, and the process will end in a finite time.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq S \leq 10^9
* 1 \leq X_1 < X_2 < ... < X_N \leq 10^9
* X_i \neq S ( 1 \leq i \leq N )
* 1 \leq P_i \leq 10^9 ( 1 \leq i \leq N )
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N S
X_1 P_1
X_2 P_2
:
X_N P_N
Output
Print the number of seconds the bus will take from departure to arrival at the last employees' apartment.
Examples
Input
3 2
1 3
3 4
4 2
Output
4
Input
6 4
1 10
2 1000
3 100000
5 1000000
6 10000
7 100
Output
21
Input
15 409904902
94198000 15017
117995501 7656764
275583856 313263626
284496300 356635175
324233841 607
360631781 148
472103717 5224
497641071 34695
522945827 816241
554305668 32
623788284 22832
667409501 124410641
876731548 12078
904557302 291749534
918215789 5
Output
2397671583 | instruction | 0 | 69,650 | 1 | 139,300 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
"""
・両端のマンション → どういうルートをたどっても順序が決まる → 彼らの意見は常に一致するとしてよい
"""
N,S,*XP = map(int,read().split())
X = XP[::2]
P = XP[1::2]
leftN = sum(x<S for x in X)
leftX = X[leftN-1::-1] # 内側から順にもつ
leftP = P[leftN-1::-1] # 内側から順にもつ
rightN = N-leftN
rightX = X[leftN:]
rightP = P[leftN:]
visit = [] # 後ろ側から訪問順
while leftN and rightN:
p1 = leftP[-1]; x1 = leftX[-1]
p2 = rightP[-1]; x2 = rightX[-1]
if p1 < p2:
visit.append(x1)
leftP.pop(); leftX.pop(); leftN -= 1
rightP[-1] = p1 + p2
else:
visit.append(x2)
rightP.pop(); rightX.pop(); rightN -= 1
leftP[-1] = p1 + p2
if leftN:
visit += leftX[::-1]
else:
visit += rightX[::-1]
visit.append(S)
answer = sum(x-y if x>y else y-x for x,y in zip(visit,visit[1:]))
print(answer)
``` | output | 1 | 69,650 | 1 | 139,301 |
Provide a correct Python 3 solution for this coding contest problem.
There are N apartments along a number line, numbered 1 through N. Apartment i is located at coordinate X_i. Also, the office of AtCoder Inc. is located at coordinate S. Every employee of AtCoder lives in one of the N apartments. There are P_i employees who are living in Apartment i.
All employees of AtCoder are now leaving the office all together. Since they are tired from work, they would like to get home by the company's bus. AtCoder owns only one bus, but it can accommodate all the employees. This bus will leave coordinate S with all the employees and move according to the following rule:
* Everyone on the bus casts a vote on which direction the bus should proceed, positive or negative. (The bus is autonomous and has no driver.) Each person has one vote, and abstaining from voting is not allowed. Then, the bus moves a distance of 1 in the direction with the greater number of votes. If a tie occurs, the bus moves in the negative direction. If there is an apartment at the coordinate of the bus after the move, all the employees who live there get off.
* Repeat the operation above as long as there is one or more employees on the bus.
For a specific example, see Sample Input 1.
The bus takes one seconds to travel a distance of 1. The time required to vote and get off the bus is ignorable.
Every employee will vote so that he himself/she herself can get off the bus at the earliest possible time. Strictly speaking, when a vote is taking place, each employee see which direction results in the earlier arrival at his/her apartment, assuming that all the employees follow the same strategy in the future. Based on this information, each employee makes the optimal choice, but if either direction results in the arrival at the same time, he/she casts a vote to the negative direction.
Find the time the bus will take from departure to arrival at the last employees' apartment. It can be proved that, given the positions of the apartments, the numbers of employees living in each apartment and the initial position of the bus, the future movement of the bus is uniquely determined, and the process will end in a finite time.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq S \leq 10^9
* 1 \leq X_1 < X_2 < ... < X_N \leq 10^9
* X_i \neq S ( 1 \leq i \leq N )
* 1 \leq P_i \leq 10^9 ( 1 \leq i \leq N )
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N S
X_1 P_1
X_2 P_2
:
X_N P_N
Output
Print the number of seconds the bus will take from departure to arrival at the last employees' apartment.
Examples
Input
3 2
1 3
3 4
4 2
Output
4
Input
6 4
1 10
2 1000
3 100000
5 1000000
6 10000
7 100
Output
21
Input
15 409904902
94198000 15017
117995501 7656764
275583856 313263626
284496300 356635175
324233841 607
360631781 148
472103717 5224
497641071 34695
522945827 816241
554305668 32
623788284 22832
667409501 124410641
876731548 12078
904557302 291749534
918215789 5
Output
2397671583 | instruction | 0 | 69,651 | 1 | 139,302 |
"Correct Solution:
```
from collections import Counter, defaultdict
import math
import random
from decimal import Decimal, ROUND_HALF_UP, ROUND_CEILING
from functools import lru_cache, reduce
from itertools import combinations_with_replacement, product, combinations
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_str():
return input()
def read_str_n():
return list(map(str, input().split()))
def mt(f):
import time
import sys
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
print(e - s, 'sec', file=sys.stderr)
return ret
return wrap
@mt
def slv(S, X, P):
X_ = [[P[i], [x]] for i, x in enumerate(X)]
i = 0
j = len(X_) - 1
# while len(X_) != 1:
while i < j:
if X_[i][0] >= X_[j][0]:
X_[i][0] += X_[j][0]
X_[i][1] += X_[j][1]
j -= 1
else:
X_[j][0] += X_[i][0]
X_[j][1] += X_[i][1]
i += 1
t = 0
pos = S
p0 = S
p1 = S
for o in X_[i][1]:
if p0 < o < p1:
continue
t += abs(pos - o)
if o < pos:
p0 = o
else:
p1 = o
pos = o
return t
def main():
N, S = read_int_n()
X = []
P = []
for _ in range(N):
x, p = read_int_n()
X.append(x)
P.append(p)
# import random
# N = 100000
# S = N / 2
# X = [x + 1 for x in range(N)]
# P = [random.randint(1, 1000000000) for _ in range(N)]
print(slv(S, X, P))
if __name__ == '__main__':
main()
``` | output | 1 | 69,651 | 1 | 139,303 |
Provide a correct Python 3 solution for this coding contest problem.
There are N apartments along a number line, numbered 1 through N. Apartment i is located at coordinate X_i. Also, the office of AtCoder Inc. is located at coordinate S. Every employee of AtCoder lives in one of the N apartments. There are P_i employees who are living in Apartment i.
All employees of AtCoder are now leaving the office all together. Since they are tired from work, they would like to get home by the company's bus. AtCoder owns only one bus, but it can accommodate all the employees. This bus will leave coordinate S with all the employees and move according to the following rule:
* Everyone on the bus casts a vote on which direction the bus should proceed, positive or negative. (The bus is autonomous and has no driver.) Each person has one vote, and abstaining from voting is not allowed. Then, the bus moves a distance of 1 in the direction with the greater number of votes. If a tie occurs, the bus moves in the negative direction. If there is an apartment at the coordinate of the bus after the move, all the employees who live there get off.
* Repeat the operation above as long as there is one or more employees on the bus.
For a specific example, see Sample Input 1.
The bus takes one seconds to travel a distance of 1. The time required to vote and get off the bus is ignorable.
Every employee will vote so that he himself/she herself can get off the bus at the earliest possible time. Strictly speaking, when a vote is taking place, each employee see which direction results in the earlier arrival at his/her apartment, assuming that all the employees follow the same strategy in the future. Based on this information, each employee makes the optimal choice, but if either direction results in the arrival at the same time, he/she casts a vote to the negative direction.
Find the time the bus will take from departure to arrival at the last employees' apartment. It can be proved that, given the positions of the apartments, the numbers of employees living in each apartment and the initial position of the bus, the future movement of the bus is uniquely determined, and the process will end in a finite time.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq S \leq 10^9
* 1 \leq X_1 < X_2 < ... < X_N \leq 10^9
* X_i \neq S ( 1 \leq i \leq N )
* 1 \leq P_i \leq 10^9 ( 1 \leq i \leq N )
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N S
X_1 P_1
X_2 P_2
:
X_N P_N
Output
Print the number of seconds the bus will take from departure to arrival at the last employees' apartment.
Examples
Input
3 2
1 3
3 4
4 2
Output
4
Input
6 4
1 10
2 1000
3 100000
5 1000000
6 10000
7 100
Output
21
Input
15 409904902
94198000 15017
117995501 7656764
275583856 313263626
284496300 356635175
324233841 607
360631781 148
472103717 5224
497641071 34695
522945827 816241
554305668 32
623788284 22832
667409501 124410641
876731548 12078
904557302 291749534
918215789 5
Output
2397671583 | instruction | 0 | 69,652 | 1 | 139,304 |
"Correct Solution:
```
from collections import Counter, defaultdict
import math
from decimal import Decimal, ROUND_HALF_UP, ROUND_CEILING
from functools import lru_cache, reduce
from itertools import combinations_with_replacement, product, combinations
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_str():
return input()
def read_str_n():
return list(map(str, input().split()))
def mt(f):
import time
import sys
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
print(e - s, 'sec', file=sys.stderr)
return ret
return wrap
@mt
def slv(S, X, P):
X_ = [[P[i], [x]] for i, x in enumerate(X)]
while len(X_) != 1:
if X_[0][0] >= X_[-1][0]:
di = -1
li = 0
else:
di = 0
li = -1
X_[li][0] += X_[di][0]
X_[li][1] += X_[di][1]
X_.pop(di)
t = 0
pos = S
p0 = S
p1 = S
for o in X_[0][1]:
if p0 < o < p1:
continue
t += abs(pos - o)
if o < pos:
p0 = o
else:
p1 = o
pos = o
return t
def main():
N, S = read_int_n()
X = []
P = []
for _ in range(N):
x, p = read_int_n()
X.append(x)
P.append(p)
print(slv(S, X, P))
if __name__ == '__main__':
main()
``` | output | 1 | 69,652 | 1 | 139,305 |
Provide a correct Python 3 solution for this coding contest problem.
There are N apartments along a number line, numbered 1 through N. Apartment i is located at coordinate X_i. Also, the office of AtCoder Inc. is located at coordinate S. Every employee of AtCoder lives in one of the N apartments. There are P_i employees who are living in Apartment i.
All employees of AtCoder are now leaving the office all together. Since they are tired from work, they would like to get home by the company's bus. AtCoder owns only one bus, but it can accommodate all the employees. This bus will leave coordinate S with all the employees and move according to the following rule:
* Everyone on the bus casts a vote on which direction the bus should proceed, positive or negative. (The bus is autonomous and has no driver.) Each person has one vote, and abstaining from voting is not allowed. Then, the bus moves a distance of 1 in the direction with the greater number of votes. If a tie occurs, the bus moves in the negative direction. If there is an apartment at the coordinate of the bus after the move, all the employees who live there get off.
* Repeat the operation above as long as there is one or more employees on the bus.
For a specific example, see Sample Input 1.
The bus takes one seconds to travel a distance of 1. The time required to vote and get off the bus is ignorable.
Every employee will vote so that he himself/she herself can get off the bus at the earliest possible time. Strictly speaking, when a vote is taking place, each employee see which direction results in the earlier arrival at his/her apartment, assuming that all the employees follow the same strategy in the future. Based on this information, each employee makes the optimal choice, but if either direction results in the arrival at the same time, he/she casts a vote to the negative direction.
Find the time the bus will take from departure to arrival at the last employees' apartment. It can be proved that, given the positions of the apartments, the numbers of employees living in each apartment and the initial position of the bus, the future movement of the bus is uniquely determined, and the process will end in a finite time.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq S \leq 10^9
* 1 \leq X_1 < X_2 < ... < X_N \leq 10^9
* X_i \neq S ( 1 \leq i \leq N )
* 1 \leq P_i \leq 10^9 ( 1 \leq i \leq N )
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N S
X_1 P_1
X_2 P_2
:
X_N P_N
Output
Print the number of seconds the bus will take from departure to arrival at the last employees' apartment.
Examples
Input
3 2
1 3
3 4
4 2
Output
4
Input
6 4
1 10
2 1000
3 100000
5 1000000
6 10000
7 100
Output
21
Input
15 409904902
94198000 15017
117995501 7656764
275583856 313263626
284496300 356635175
324233841 607
360631781 148
472103717 5224
497641071 34695
522945827 816241
554305668 32
623788284 22832
667409501 124410641
876731548 12078
904557302 291749534
918215789 5
Output
2397671583 | instruction | 0 | 69,653 | 1 | 139,306 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n,s = LI()
a = [LI() for _ in range(n)]
x = [_[0] for _ in a]
p = [_[1] for _ in a]
if x[0] > s:
return x[-1] - s
if x[-1] < s:
return s - x[0]
r = 0
i = 0
j = n - 1
d = p[:]
e = collections.defaultdict(list)
sk = set()
while i < j:
if x[i] > s:
break
if x[j] < s:
break
if d[i] >= d[j]:
d[i] += d[j]
j -= 1
else:
d[j] += d[i]
i += 1
t = s
k = sorted(list(zip(d,range(n))), reverse=True)
lx = rx = s
for _,i in k:
if lx <= x[i] <= rx:
continue
if lx > x[i]:
lx = x[i]
else:
rx = x[i]
r += abs(t-x[i])
t = x[i]
return r
print(main())
``` | output | 1 | 69,653 | 1 | 139,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N apartments along a number line, numbered 1 through N. Apartment i is located at coordinate X_i. Also, the office of AtCoder Inc. is located at coordinate S. Every employee of AtCoder lives in one of the N apartments. There are P_i employees who are living in Apartment i.
All employees of AtCoder are now leaving the office all together. Since they are tired from work, they would like to get home by the company's bus. AtCoder owns only one bus, but it can accommodate all the employees. This bus will leave coordinate S with all the employees and move according to the following rule:
* Everyone on the bus casts a vote on which direction the bus should proceed, positive or negative. (The bus is autonomous and has no driver.) Each person has one vote, and abstaining from voting is not allowed. Then, the bus moves a distance of 1 in the direction with the greater number of votes. If a tie occurs, the bus moves in the negative direction. If there is an apartment at the coordinate of the bus after the move, all the employees who live there get off.
* Repeat the operation above as long as there is one or more employees on the bus.
For a specific example, see Sample Input 1.
The bus takes one seconds to travel a distance of 1. The time required to vote and get off the bus is ignorable.
Every employee will vote so that he himself/she herself can get off the bus at the earliest possible time. Strictly speaking, when a vote is taking place, each employee see which direction results in the earlier arrival at his/her apartment, assuming that all the employees follow the same strategy in the future. Based on this information, each employee makes the optimal choice, but if either direction results in the arrival at the same time, he/she casts a vote to the negative direction.
Find the time the bus will take from departure to arrival at the last employees' apartment. It can be proved that, given the positions of the apartments, the numbers of employees living in each apartment and the initial position of the bus, the future movement of the bus is uniquely determined, and the process will end in a finite time.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq S \leq 10^9
* 1 \leq X_1 < X_2 < ... < X_N \leq 10^9
* X_i \neq S ( 1 \leq i \leq N )
* 1 \leq P_i \leq 10^9 ( 1 \leq i \leq N )
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N S
X_1 P_1
X_2 P_2
:
X_N P_N
Output
Print the number of seconds the bus will take from departure to arrival at the last employees' apartment.
Examples
Input
3 2
1 3
3 4
4 2
Output
4
Input
6 4
1 10
2 1000
3 100000
5 1000000
6 10000
7 100
Output
21
Input
15 409904902
94198000 15017
117995501 7656764
275583856 313263626
284496300 356635175
324233841 607
360631781 148
472103717 5224
497641071 34695
522945827 816241
554305668 32
623788284 22832
667409501 124410641
876731548 12078
904557302 291749534
918215789 5
Output
2397671583
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n,s = LI()
a = [LI() for _ in range(n)]
x = [_[0] for _ in a]
p = [_[1] for _ in a]
if x[0] > s:
return x[-1] - s
if x[-1] < s:
return s - x[0]
r = 0
i = 0
j = n - 1
d = p[:]
e = collections.defaultdict(list)
sk = set()
while i < j:
if x[i] > s:
break
if x[j] < s:
break
if d[i] >= d[j]:
d[i] += d[j]
j -= 1
if j >= 0 and d[j] < d[j+1]:
d[j] = d[j+1]
sk.add(i)
else:
d[j] += d[i]
i += 1
if i < n and d[i] < d[i-1]:
d[i] = d[i-1]
sk.add(i)
t = s
if i == j:
r += abs(x[i]-s)
t = x[i]
i -= 1
j += 1
else:
if x[i] > s:
r += abs(x[j]-s)
t = x[j]
i -= 1
j += 1
else:
r += abs(x[i]-s)
t = x[i]
i -= 1
j += 1
while i >= 0 or j < n:
if i < 0:
r += abs(x[-1]-t)
break
if j >= n:
r += abs(x[0]-t)
break
if i in sk:
d[i-1] = d[i]
i-=1
continue
if j in sk:
d[j+1] = d[j]
J+=1
continue
if d[i] >= d[j]:
r += abs(x[i]-t)
t = x[i]
i -= 1
else:
r += abs(x[j]-t)
t = x[j]
j += 1
return r
print(main())
``` | instruction | 0 | 69,654 | 1 | 139,308 |
No | output | 1 | 69,654 | 1 | 139,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N apartments along a number line, numbered 1 through N. Apartment i is located at coordinate X_i. Also, the office of AtCoder Inc. is located at coordinate S. Every employee of AtCoder lives in one of the N apartments. There are P_i employees who are living in Apartment i.
All employees of AtCoder are now leaving the office all together. Since they are tired from work, they would like to get home by the company's bus. AtCoder owns only one bus, but it can accommodate all the employees. This bus will leave coordinate S with all the employees and move according to the following rule:
* Everyone on the bus casts a vote on which direction the bus should proceed, positive or negative. (The bus is autonomous and has no driver.) Each person has one vote, and abstaining from voting is not allowed. Then, the bus moves a distance of 1 in the direction with the greater number of votes. If a tie occurs, the bus moves in the negative direction. If there is an apartment at the coordinate of the bus after the move, all the employees who live there get off.
* Repeat the operation above as long as there is one or more employees on the bus.
For a specific example, see Sample Input 1.
The bus takes one seconds to travel a distance of 1. The time required to vote and get off the bus is ignorable.
Every employee will vote so that he himself/she herself can get off the bus at the earliest possible time. Strictly speaking, when a vote is taking place, each employee see which direction results in the earlier arrival at his/her apartment, assuming that all the employees follow the same strategy in the future. Based on this information, each employee makes the optimal choice, but if either direction results in the arrival at the same time, he/she casts a vote to the negative direction.
Find the time the bus will take from departure to arrival at the last employees' apartment. It can be proved that, given the positions of the apartments, the numbers of employees living in each apartment and the initial position of the bus, the future movement of the bus is uniquely determined, and the process will end in a finite time.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq S \leq 10^9
* 1 \leq X_1 < X_2 < ... < X_N \leq 10^9
* X_i \neq S ( 1 \leq i \leq N )
* 1 \leq P_i \leq 10^9 ( 1 \leq i \leq N )
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N S
X_1 P_1
X_2 P_2
:
X_N P_N
Output
Print the number of seconds the bus will take from departure to arrival at the last employees' apartment.
Examples
Input
3 2
1 3
3 4
4 2
Output
4
Input
6 4
1 10
2 1000
3 100000
5 1000000
6 10000
7 100
Output
21
Input
15 409904902
94198000 15017
117995501 7656764
275583856 313263626
284496300 356635175
324233841 607
360631781 148
472103717 5224
497641071 34695
522945827 816241
554305668 32
623788284 22832
667409501 124410641
876731548 12078
904557302 291749534
918215789 5
Output
2397671583
Submitted Solution:
```
# -*- coding: utf-8 -*-
from bisect import bisect
from operator import add
def inpl(): return map(int, input().split())
class Seg():
def __init__(self, na, default, func):
if isinstance(na, list):
n = len(na)
else:
n = na
i = 1
while 2**i <= n:
i += 1
self.D = default
self.H = i
self.N = 2**i
if isinstance(na, list):
self.A = [default] * (self.N) + na + [default] * (self.N-n)
for i in range(self.N-1,0,-1):
self.A[i] = func(self.A[i*2], self.A[i*2+1])
else:
self.A = [default] * (self.N*2)
self.F = func
def find(self, i):
return self.A[i + self.N]
def update(self, i, x):
i += self.N
self.A[i] = x
while i > 1:
i = i // 2
self.A[i] = self.merge(self.A[i*2], self.A[i*2+1])
def merge(self, a, b):
return self.F(a, b)
def total(self):
return self.A[1]
def query(self, a, b):
A = self.A
l = a + self.N
r = b + self.N
res = self.D
while l < r:
if l % 2 == 1:
res = self.merge(res, A[l])
l += 1
if r % 2 == 1:
r -= 1
res = self.merge(res, A[r])
l >>= 1
r >>= 1
return res
N, S = inpl()
X = [0]
P = [0]
for _ in range(N):
x, p = inpl()
X.append(x)
P.append(p)
P.append(0)
l = bisect(X, S) - 1
x = S
seg = Seg(P, 0, add)
ans = 0
while seg.total():
L = seg.query(0, l+1)
R = seg.total() - L
if L >= R:
ans += abs(x - X[l])
seg.update(l, 0)
x = X[l]
l -= 1
else:
ans += abs(x - X[l+1])
seg.update(l+1, 0)
x = X[l+1]
l += 1
``` | instruction | 0 | 69,655 | 1 | 139,310 |
No | output | 1 | 69,655 | 1 | 139,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N apartments along a number line, numbered 1 through N. Apartment i is located at coordinate X_i. Also, the office of AtCoder Inc. is located at coordinate S. Every employee of AtCoder lives in one of the N apartments. There are P_i employees who are living in Apartment i.
All employees of AtCoder are now leaving the office all together. Since they are tired from work, they would like to get home by the company's bus. AtCoder owns only one bus, but it can accommodate all the employees. This bus will leave coordinate S with all the employees and move according to the following rule:
* Everyone on the bus casts a vote on which direction the bus should proceed, positive or negative. (The bus is autonomous and has no driver.) Each person has one vote, and abstaining from voting is not allowed. Then, the bus moves a distance of 1 in the direction with the greater number of votes. If a tie occurs, the bus moves in the negative direction. If there is an apartment at the coordinate of the bus after the move, all the employees who live there get off.
* Repeat the operation above as long as there is one or more employees on the bus.
For a specific example, see Sample Input 1.
The bus takes one seconds to travel a distance of 1. The time required to vote and get off the bus is ignorable.
Every employee will vote so that he himself/she herself can get off the bus at the earliest possible time. Strictly speaking, when a vote is taking place, each employee see which direction results in the earlier arrival at his/her apartment, assuming that all the employees follow the same strategy in the future. Based on this information, each employee makes the optimal choice, but if either direction results in the arrival at the same time, he/she casts a vote to the negative direction.
Find the time the bus will take from departure to arrival at the last employees' apartment. It can be proved that, given the positions of the apartments, the numbers of employees living in each apartment and the initial position of the bus, the future movement of the bus is uniquely determined, and the process will end in a finite time.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq S \leq 10^9
* 1 \leq X_1 < X_2 < ... < X_N \leq 10^9
* X_i \neq S ( 1 \leq i \leq N )
* 1 \leq P_i \leq 10^9 ( 1 \leq i \leq N )
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N S
X_1 P_1
X_2 P_2
:
X_N P_N
Output
Print the number of seconds the bus will take from departure to arrival at the last employees' apartment.
Examples
Input
3 2
1 3
3 4
4 2
Output
4
Input
6 4
1 10
2 1000
3 100000
5 1000000
6 10000
7 100
Output
21
Input
15 409904902
94198000 15017
117995501 7656764
275583856 313263626
284496300 356635175
324233841 607
360631781 148
472103717 5224
497641071 34695
522945827 816241
554305668 32
623788284 22832
667409501 124410641
876731548 12078
904557302 291749534
918215789 5
Output
2397671583
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n,s = LI()
a = [LI() for _ in range(n)]
x = [_[0] for _ in a]
p = [_[1] for _ in a]
if x[0] > s:
return x[-1] - s
if x[-1] < s:
return s - x[0]
r = 0
i = 0
j = n - 1
d = p[:]
e = collections.defaultdict(list)
while i < j:
if x[i] > s:
break
if x[j] < s:
break
if d[i] >= d[j]:
d[i] += d[j]
j -= 1
if j >= 0 and d[j] < d[j+1]:
d[j] = d[j+1]
else:
d[j] += d[i]
i += 1
if i < n and d[i] < d[i-1]:
d[i] = d[i-1]
t = s
if i == j:
r += abs(x[i]-s)
t = x[i]
i -= 1
j += 1
else:
if x[i] > s:
r += abs(x[j]-s)
t = x[j]
i -= 1
j += 1
else:
r += abs(x[i]-s)
t = x[i]
i -= 1
j += 1
while i >= 0 or j < n:
if i < 0:
r += abs(x[-1]-t)
break
if j >= n:
r += abs(x[0]-t)
break
if d[i] >= d[j]:
r += abs(x[i]-t)
t = x[i]
i -= 1
else:
r += abs(x[j]-t)
t = x[j]
j += 1
return r
print(main())
``` | instruction | 0 | 69,656 | 1 | 139,312 |
No | output | 1 | 69,656 | 1 | 139,313 |
Provide a correct Python 3 solution for this coding contest problem.
B: Yamanote-line Game-Yamanote-line Game-
Bean (?) Knowledge
The Yamanote line is convenient. The reason is that you can ride as many laps as time allows just by paying 130 yen. However, if you board with a ticket, you must be careful about the valid time of the ticket. It seems safe with an IC card. Taking advantage of the characteristics of the Yamanote Line, there are people in the suburbs of Tokyo who are swayed by trains and devour their sleep. By the way, the questioner of this question has never done it. It's rare for a station employee to find out, but I don't recommend it because it would be annoying.
Problem statement
Let's play a game that utilizes the characteristics of the Yamanote Line. Here, for generalization, there are N stations numbered from 1 to N, and the stations are lined up in the order of 1, 2, ..., N, and you can go to any station from each station. Let's consider the Yamanote Line Modoki as a route that can be boarded for d yen. The game follows the rules below.
* Select your favorite station as the starting point and board the Yamanote Line Modoki for d yen.
* After that, get off at any station and get on again.
* The game ends when you get off at the station where you started.
* If you get off at the i-th station, you can get a reward of p_i yen.
* However, you cannot get the reward again at the station where you got the reward once.
* Also, it costs d yen to get on the Yamanote Line Modoki again after getting off.
Now, how many yen can you make up to? Please give it a try.
Input format
N d
p_1 p_2… p_N
All inputs consist of integers. On the first line, the number N of Modoki stations on the Yamanote line and the fare d are given separated by blanks. On the second line, the rewards received at each station are given separated by blanks, and the i-th value p_i represents the reward for station i.
Constraint
* 3 ≤ N ≤ 1 {,} 000
* 1 ≤ d ≤ 1 {,} 000
* 1 ≤ p_i ≤ 1 {,} 000 (1 ≤ i ≤ N)
Output format
Output the maximum amount of money you can get in the game on one line. If you can't get more than 1 yen, print "kusoge" on one line. The end of the output should be newline and should not contain extra characters.
Input example 1
5 130
130 170 100 120 140
Output example 1
50
Input example 2
3 100
100 90 65
Output example 2
kusoge
Input example 3
6 210
300 270 400 330 250 370
Output example 3
660
Input example 4
4 540
100 460 320 280
Output example 4
kusoge
Example
Input
5 130
130 170 100 120 140
Output
50 | instruction | 0 | 69,786 | 1 | 139,572 |
"Correct Solution:
```
n, d = map(int, input().split())
lst = list(map(int, input().split()))
ans = sum([x - d for x in lst if x - d >= 0])
print(ans if ans else "kusoge")
``` | output | 1 | 69,786 | 1 | 139,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 ≤ T ≤ 10^4) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 ≤ n, g, b ≤ 10^9) — the length of the highway and the number of good and bad days respectively.
Output
Print T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | instruction | 0 | 69,973 | 1 | 139,946 |
Tags: math
Correct Solution:
```
import math
for i in range(int(input())):
n, g, b = map(int, input().split())
half = math.ceil(n / 2)
how = math.ceil(half / g)
ans = b * (how - 1) + g * (how - 1) + half - g * (how - 1)
if ans < n:
ans += n - ans
print(ans)
``` | output | 1 | 69,973 | 1 | 139,947 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 ≤ T ≤ 10^4) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 ≤ n, g, b ≤ 10^9) — the length of the highway and the number of good and bad days respectively.
Output
Print T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | instruction | 0 | 69,974 | 1 | 139,948 |
Tags: math
Correct Solution:
```
import math
t = int(input())
for i in range(t):
n,g,b=map(int,input().split())
t = n
n=math.ceil(n/2)
temp = n%g
n = n//g
if temp ==0:
x = n*(g+b) - b
else:
x= n*(g+b) + temp
print(max(t,x))
``` | output | 1 | 69,974 | 1 | 139,949 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 ≤ T ≤ 10^4) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 ≤ n, g, b ≤ 10^9) — the length of the highway and the number of good and bad days respectively.
Output
Print T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | instruction | 0 | 69,975 | 1 | 139,950 |
Tags: math
Correct Solution:
```
import math
for _ in range(int(input())):
n,g,b = map(int,input().split())
ne = math.ceil(n/2)
if ne%g==0:
a = (ne//g)*(g+b) - b
else:
a = (ne//g)*(g+b) + ne%g
print(max(a,n))
``` | output | 1 | 69,975 | 1 | 139,951 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 ≤ T ≤ 10^4) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 ≤ n, g, b ≤ 10^9) — the length of the highway and the number of good and bad days respectively.
Output
Print T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | instruction | 0 | 69,976 | 1 | 139,952 |
Tags: math
Correct Solution:
```
def func(n, g, b):
need_g = (n+1)//2
total_g = (need_g//g)*(b+g)
total_g += -b if (need_g%g==0) else need_g%g
print(max(n, total_g))
for i in range(int(input())):
nn, gg, bb = list(map(int, input().split()))
func(nn, gg, bb)
``` | output | 1 | 69,976 | 1 | 139,953 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 ≤ T ≤ 10^4) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 ≤ n, g, b ≤ 10^9) — the length of the highway and the number of good and bad days respectively.
Output
Print T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | instruction | 0 | 69,977 | 1 | 139,954 |
Tags: math
Correct Solution:
```
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n, g, b = [int(item) for item in input().split()]
required = (n + 1) // 2
cycle = (required - 1) // g
good_enough = cycle * (b + g) + required - cycle * g
print(max(n, good_enough))
``` | output | 1 | 69,977 | 1 | 139,955 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 ≤ T ≤ 10^4) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 ≤ n, g, b ≤ 10^9) — the length of the highway and the number of good and bad days respectively.
Output
Print T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | instruction | 0 | 69,978 | 1 | 139,956 |
Tags: math
Correct Solution:
```
from math import ceil
if __name__ == '__main__':
for _ in range(int(input())):
n, g, b = map(int, input().split())
mgd = ceil(n / 2)
mgc = mgd // g
cl = g + b
if mgc * g < mgd:
md = (mgc * cl) + mgd - (mgc * g)
else:
md = (mgc - 1) * cl + g
print(md if md > n else n)
``` | output | 1 | 69,978 | 1 | 139,957 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 ≤ T ≤ 10^4) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 ≤ n, g, b ≤ 10^9) — the length of the highway and the number of good and bad days respectively.
Output
Print T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | instruction | 0 | 69,979 | 1 | 139,958 |
Tags: math
Correct Solution:
```
for ti in range(int(input())):
n, g, b = [int(x) for x in input().split()]
ans = 0
if(g>=n):
print(n)
continue
ans += g
gr = (n+1)//2
br = n - gr
gr -= g
#print(gr, br)
ms = (gr//g)
ans += (ms*(g+b))
gr -= (ms*g)
br -= (ms*b)
br = max(br, 0)
#print(ans, ms, gr, br)
if(gr):
gl = min(gr, g)
gr -= gl
ans += (gl+b)
br -= b
if(br>0):
ans += br
print(ans)
``` | output | 1 | 69,979 | 1 | 139,959 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 ≤ T ≤ 10^4) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 ≤ n, g, b ≤ 10^9) — the length of the highway and the number of good and bad days respectively.
Output
Print T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | instruction | 0 | 69,980 | 1 | 139,960 |
Tags: math
Correct Solution:
```
for _ in range(int(input())):
n,g,b=map(int,input().split())
N=(n+1)//2
print(max(n,N//g*(b+g)+ ( -b if N%g==0 else N%g)))
``` | output | 1 | 69,980 | 1 | 139,961 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
Input
The first line contains a single integer T (1 ≤ T ≤ 10^4) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 ≤ n, g, b ≤ 10^9) — the length of the highway and the number of good and bad days respectively.
Output
Print T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
Example
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
Note
In the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.
In the second test case, you can also lay new asphalt each day, since days 1-8 are good.
Submitted Solution:
```
"""
Author : thekushalghosh
Team : CodeDiggers
"""
import sys,math
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(s[:len(s) - 1])
def invr():
return(map(int,input().split()))
################################################################
############ ---- THE ACTUAL CODE STARTS BELOW ---- ############
t = 1
t = inp()
for tt in range(t):
n,g,b = invr()
q = math.ceil(n / 2)
if q <= g:
print(n)
else:
w = (q - 1) // g
qw = w * b
print(max(n,q + qw))
``` | instruction | 0 | 69,981 | 1 | 139,962 |
Yes | output | 1 | 69,981 | 1 | 139,963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.