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.
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers.
Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East".
Limak isn’t sure whether the description is valid. You must help him to check the following conditions:
* If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South.
* If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North.
* The journey must end on the North Pole.
Check if the above conditions are satisfied and print "YES" or "NO" on a single line.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 50).
The i-th of next n lines contains an integer ti and a string diri (1 ≤ ti ≤ 106, <image>) — the length and the direction of the i-th part of the journey, according to the description Limak got.
Output
Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes.
Examples
Input
5
7500 South
10000 East
3500 North
4444 West
4000 North
Output
YES
Input
2
15000 South
4000 East
Output
NO
Input
5
20000 South
1000 North
1000000 West
9000 North
10000 North
Output
YES
Input
3
20000 South
10 East
20000 North
Output
NO
Input
2
1000 North
1000 South
Output
NO
Input
4
50 South
50 North
15000 South
15000 North
Output
YES
Note
Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole.
<image> | instruction | 0 | 6,262 | 1 | 12,524 |
Tags: geometry, implementation
Correct Solution:
```
n=int(input())
w=0
e=0
y=0
r=0
for i in range(n):
d,v=input().split(" ")
d=int(d)
if v=='North':
y-=d
elif v=='South':
y+=d
elif (v=='West' or v=='East') and (y==0 or y==20000):
r=-1
if y<0 or y>20000:
r=-1
if r==0 and y==0:
print("YES")
else:
print("NO")
``` | output | 1 | 6,262 | 1 | 12,525 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers.
Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East".
Limak isn’t sure whether the description is valid. You must help him to check the following conditions:
* If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South.
* If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North.
* The journey must end on the North Pole.
Check if the above conditions are satisfied and print "YES" or "NO" on a single line.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 50).
The i-th of next n lines contains an integer ti and a string diri (1 ≤ ti ≤ 106, <image>) — the length and the direction of the i-th part of the journey, according to the description Limak got.
Output
Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes.
Examples
Input
5
7500 South
10000 East
3500 North
4444 West
4000 North
Output
YES
Input
2
15000 South
4000 East
Output
NO
Input
5
20000 South
1000 North
1000000 West
9000 North
10000 North
Output
YES
Input
3
20000 South
10 East
20000 North
Output
NO
Input
2
1000 North
1000 South
Output
NO
Input
4
50 South
50 North
15000 South
15000 North
Output
YES
Note
Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole.
<image> | instruction | 0 | 6,263 | 1 | 12,526 |
Tags: geometry, implementation
Correct Solution:
```
n = int(input())
y = 0
maxlen = 20000
for i in range(n):
raw = input().split()
cur = int(raw[0])
dir = raw[1]
if y == 0 and dir != 'South':
print('NO')
quit()
if y == maxlen and dir != 'North':
print('NO')
quit()
if (dir == 'South'):
y += cur
elif (dir == 'North'):
y -= cur
if (y < 0 or y > maxlen):
print('NO')
quit()
if y == 0:
print('YES')
else:
print('NO')
``` | output | 1 | 6,263 | 1 | 12,527 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers.
Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East".
Limak isn’t sure whether the description is valid. You must help him to check the following conditions:
* If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South.
* If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North.
* The journey must end on the North Pole.
Check if the above conditions are satisfied and print "YES" or "NO" on a single line.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 50).
The i-th of next n lines contains an integer ti and a string diri (1 ≤ ti ≤ 106, <image>) — the length and the direction of the i-th part of the journey, according to the description Limak got.
Output
Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes.
Examples
Input
5
7500 South
10000 East
3500 North
4444 West
4000 North
Output
YES
Input
2
15000 South
4000 East
Output
NO
Input
5
20000 South
1000 North
1000000 West
9000 North
10000 North
Output
YES
Input
3
20000 South
10 East
20000 North
Output
NO
Input
2
1000 North
1000 South
Output
NO
Input
4
50 South
50 North
15000 South
15000 North
Output
YES
Note
Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole.
<image> | instruction | 0 | 6,264 | 1 | 12,528 |
Tags: geometry, implementation
Correct Solution:
```
n = int(input())
ans = 'YES'
p = 0
for _ in range(n):
t, d = input().split()
if d == 'South':
p += int(t)
if p > 20000:
ans = 'NO'
break
elif d == 'North':
p -= int(t)
if p < 0:
ans = 'NO'
break
else:
if abs(p) % 20000 == 0:
ans = 'NO'
break
if p != 0:
ans = 'NO'
print(ans)
``` | output | 1 | 6,264 | 1 | 12,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y.
A path from city s to city t is a sequence of cities p1, p2, ... , pk, where p1 = s, pk = t, and there is a road from city pi to city pi + 1 for each i from 1 to k - 1. The path can pass multiple times through each city except t. It can't pass through t more than once.
A path p from s to t is ideal if it is the lexicographically minimal such path. In other words, p is ideal path from s to t if for any other path q from s to t pi < qi, where i is the minimum integer such that pi ≠ qi.
There is a tourist agency in the country that offers q unusual excursions: the j-th excursion starts at city sj and ends in city tj.
For each pair sj, tj help the agency to study the ideal path from sj to tj. Note that it is possible that there is no ideal path from sj to tj. This is possible due to two reasons:
* there is no path from sj to tj;
* there are paths from sj to tj, but for every such path p there is another path q from sj to tj, such that pi > qi, where i is the minimum integer for which pi ≠ qi.
The agency would like to know for the ideal path from sj to tj the kj-th city in that path (on the way from sj to tj).
For each triple sj, tj, kj (1 ≤ j ≤ q) find if there is an ideal path from sj to tj and print the kj-th city in that path, if there is any.
Input
The first line contains three integers n, m and q (2 ≤ n ≤ 3000,0 ≤ m ≤ 3000, 1 ≤ q ≤ 4·105) — the number of cities, the number of roads and the number of excursions.
Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), denoting that the i-th road goes from city xi to city yi. All roads are one-directional. There can't be more than one road in each direction between two cities.
Each of the next q lines contains three integers sj, tj and kj (1 ≤ sj, tj ≤ n, sj ≠ tj, 1 ≤ kj ≤ 3000).
Output
In the j-th line print the city that is the kj-th in the ideal path from sj to tj. If there is no ideal path from sj to tj, or the integer kj is greater than the length of this path, print the string '-1' (without quotes) in the j-th line.
Example
Input
7 7 5
1 2
2 3
1 3
3 4
4 5
5 3
4 6
1 4 2
2 6 1
1 7 3
1 3 2
1 3 5
Output
2
-1
-1
2
-1
Submitted Solution:
```
def tryExcursion(grid, start, end, city):
path = [start]
currentCity = start
move = moveCities(grid, path, start)
while move != -1:
if not move in path:
path += [move]
if move == end:
if not move in path:
path += [move]
break
move = moveCities(grid, path, move)
if move == -1 and path[-1] != end:
return move
elif city - 1 < len(path):
return path[city-1]
else:
return -1
class Hello(BaseException): pass
def moveCities(grid, path, currentCity):
#print(path)
#print(grid[currentCity -1 ])
for a in grid[currentCity-1]:
for b in path:
if a == b:
return -1
return a
return -1
''' for a in grid[currentCity - 1]:
#print(a)
try:
for b in path:
if a == b:
return -1
#print("THIS IS B ", b)
raise Hello()
except Hello:
#print("SKIPPING ", a)
continue
#path += [a]
return a
return -1
'''
inputtext = input().split(" ")
cities = int(inputtext[0])
roads = int(inputtext[1])
excursions = int(inputtext[2])
excursionslist = []
grid = [[] for i in range(cities)]
for a in range(roads):
road = [int(a) for a in input().split(" ")]
if road[1] not in grid[road[0]-1]:
grid[road[0] - 1] += [road[1]]
if road[0] not in grid[road[1]-1]:
grid[road[1] - 1] += [road[0]]
for gr in grid:
gr.sort()
for _ in range(excursions):
excursionslist += [[int(i) for i in input().split(" ")]]
for _ in range(excursions):
#if excursionslist[_][0] > excursionslist[_][1]:
# print(-1)
#else:
print(tryExcursion(grid, excursionslist[_][0], excursionslist[_][1], excursionslist[_][2]))
``` | instruction | 0 | 6,297 | 1 | 12,594 |
No | output | 1 | 6,297 | 1 | 12,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y.
A path from city s to city t is a sequence of cities p1, p2, ... , pk, where p1 = s, pk = t, and there is a road from city pi to city pi + 1 for each i from 1 to k - 1. The path can pass multiple times through each city except t. It can't pass through t more than once.
A path p from s to t is ideal if it is the lexicographically minimal such path. In other words, p is ideal path from s to t if for any other path q from s to t pi < qi, where i is the minimum integer such that pi ≠ qi.
There is a tourist agency in the country that offers q unusual excursions: the j-th excursion starts at city sj and ends in city tj.
For each pair sj, tj help the agency to study the ideal path from sj to tj. Note that it is possible that there is no ideal path from sj to tj. This is possible due to two reasons:
* there is no path from sj to tj;
* there are paths from sj to tj, but for every such path p there is another path q from sj to tj, such that pi > qi, where i is the minimum integer for which pi ≠ qi.
The agency would like to know for the ideal path from sj to tj the kj-th city in that path (on the way from sj to tj).
For each triple sj, tj, kj (1 ≤ j ≤ q) find if there is an ideal path from sj to tj and print the kj-th city in that path, if there is any.
Input
The first line contains three integers n, m and q (2 ≤ n ≤ 3000,0 ≤ m ≤ 3000, 1 ≤ q ≤ 4·105) — the number of cities, the number of roads and the number of excursions.
Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), denoting that the i-th road goes from city xi to city yi. All roads are one-directional. There can't be more than one road in each direction between two cities.
Each of the next q lines contains three integers sj, tj and kj (1 ≤ sj, tj ≤ n, sj ≠ tj, 1 ≤ kj ≤ 3000).
Output
In the j-th line print the city that is the kj-th in the ideal path from sj to tj. If there is no ideal path from sj to tj, or the integer kj is greater than the length of this path, print the string '-1' (without quotes) in the j-th line.
Example
Input
7 7 5
1 2
2 3
1 3
3 4
4 5
5 3
4 6
1 4 2
2 6 1
1 7 3
1 3 2
1 3 5
Output
2
-1
-1
2
-1
Submitted Solution:
```
# -*- coding: utf-8 -*-
import collections
N, M, Q = map(int, input().split())
ST = []
for i in range(M):
ST.append([int(x) for x in input().split()])
ST.sort()
P = collections.defaultdict(list)
for s,t in ST:
P[s].append(t)
INF = False
memo = {}
def dfs(start, end, path, visited, circle):
global INF
if INF:
return []
key = (start, end)
if start == end:
return path
if key in memo:
rest = memo[key]
if not rest:
return []
# maybe exists circle
# path += rest[1:]
# return path
for to in P[start]:
if to not in visited:
ans = dfs(to, end, path+[to], visited | {to}, circle)
if ans:
memo[key] = ans[len(path)-1:]
return ans
else:
if not circle:
# circle, break out from some point on the circle,
# if it can reach destination, no smallest lexicographically path.
# no need to record path
ci = path.index(to)
for j in range(ci+1, len(path)+1):
key = (path[j-1], end)
if key in memo:
if memo[key]:
return []
if dfs(path[j-1], end, [], visited, True):
INF = True
memo[(start, end)] = []
return []
memo[key] = []
return []
for i in range(Q):
s, t, k = map(int, input().split())
INF = False
p = dfs(s, t, [s], {s}, False)
# print(s, t, k, p)
if INF:
print(-1)
continue
if not p:
print(-1)
continue
if k > len(p):
print(-1)
else:
print(p[k - 1])
# 2 3 4 5 4 5 4 5 .... 4 6
``` | instruction | 0 | 6,298 | 1 | 12,596 |
No | output | 1 | 6,298 | 1 | 12,597 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y.
A path from city s to city t is a sequence of cities p1, p2, ... , pk, where p1 = s, pk = t, and there is a road from city pi to city pi + 1 for each i from 1 to k - 1. The path can pass multiple times through each city except t. It can't pass through t more than once.
A path p from s to t is ideal if it is the lexicographically minimal such path. In other words, p is ideal path from s to t if for any other path q from s to t pi < qi, where i is the minimum integer such that pi ≠ qi.
There is a tourist agency in the country that offers q unusual excursions: the j-th excursion starts at city sj and ends in city tj.
For each pair sj, tj help the agency to study the ideal path from sj to tj. Note that it is possible that there is no ideal path from sj to tj. This is possible due to two reasons:
* there is no path from sj to tj;
* there are paths from sj to tj, but for every such path p there is another path q from sj to tj, such that pi > qi, where i is the minimum integer for which pi ≠ qi.
The agency would like to know for the ideal path from sj to tj the kj-th city in that path (on the way from sj to tj).
For each triple sj, tj, kj (1 ≤ j ≤ q) find if there is an ideal path from sj to tj and print the kj-th city in that path, if there is any.
Input
The first line contains three integers n, m and q (2 ≤ n ≤ 3000,0 ≤ m ≤ 3000, 1 ≤ q ≤ 4·105) — the number of cities, the number of roads and the number of excursions.
Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), denoting that the i-th road goes from city xi to city yi. All roads are one-directional. There can't be more than one road in each direction between two cities.
Each of the next q lines contains three integers sj, tj and kj (1 ≤ sj, tj ≤ n, sj ≠ tj, 1 ≤ kj ≤ 3000).
Output
In the j-th line print the city that is the kj-th in the ideal path from sj to tj. If there is no ideal path from sj to tj, or the integer kj is greater than the length of this path, print the string '-1' (without quotes) in the j-th line.
Example
Input
7 7 5
1 2
2 3
1 3
3 4
4 5
5 3
4 6
1 4 2
2 6 1
1 7 3
1 3 2
1 3 5
Output
2
-1
-1
2
-1
Submitted Solution:
```
# -*- coding: utf-8 -*-
import collections
N, M, Q = map(int, input().split())
ST = []
for i in range(M):
ST.append([int(x) for x in input().split()])
ST.sort()
P = collections.defaultdict(list)
for s,t in ST:
P[s].append(t)
INF = False
memo = {}
def dfs(start, end, path, visited, circle):
global INF
if INF:
return []
key = (start, end)
if start == end:
memo[key] = path
return path
if key in memo:
rest = memo[key]
if not rest:
return []
path += rest[1:]
return path
for to in P[start]:
if to not in visited:
ans = dfs(to, end, path+[to], visited | {to}, circle)
if ans:
memo[key] = ans
return ans
else:
if not circle:
# circle, break out from some point on the circle,
# if it can reach destination, no smallest lexicographically path.
# no need to record path
ci = path.index(to)
for j in range(ci+1, len(path)+1):
if dfs(path[j-1], end, [], visited, True):
INF = True
memo[key] = []
return []
memo[key] = []
return []
for i in range(Q):
s, t, k = map(int, input().split())
INF = False
p = dfs(s, t, [s], {s}, False)
# print(s, t, k, p)
if INF:
print(-1)
continue
if not p:
print(-1)
continue
if k > len(p):
print(-1)
else:
print(p[k - 1])
# 2 3 4 5 4 5 4 5 .... 4 6
``` | instruction | 0 | 6,299 | 1 | 12,598 |
No | output | 1 | 6,299 | 1 | 12,599 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y.
A path from city s to city t is a sequence of cities p1, p2, ... , pk, where p1 = s, pk = t, and there is a road from city pi to city pi + 1 for each i from 1 to k - 1. The path can pass multiple times through each city except t. It can't pass through t more than once.
A path p from s to t is ideal if it is the lexicographically minimal such path. In other words, p is ideal path from s to t if for any other path q from s to t pi < qi, where i is the minimum integer such that pi ≠ qi.
There is a tourist agency in the country that offers q unusual excursions: the j-th excursion starts at city sj and ends in city tj.
For each pair sj, tj help the agency to study the ideal path from sj to tj. Note that it is possible that there is no ideal path from sj to tj. This is possible due to two reasons:
* there is no path from sj to tj;
* there are paths from sj to tj, but for every such path p there is another path q from sj to tj, such that pi > qi, where i is the minimum integer for which pi ≠ qi.
The agency would like to know for the ideal path from sj to tj the kj-th city in that path (on the way from sj to tj).
For each triple sj, tj, kj (1 ≤ j ≤ q) find if there is an ideal path from sj to tj and print the kj-th city in that path, if there is any.
Input
The first line contains three integers n, m and q (2 ≤ n ≤ 3000,0 ≤ m ≤ 3000, 1 ≤ q ≤ 4·105) — the number of cities, the number of roads and the number of excursions.
Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), denoting that the i-th road goes from city xi to city yi. All roads are one-directional. There can't be more than one road in each direction between two cities.
Each of the next q lines contains three integers sj, tj and kj (1 ≤ sj, tj ≤ n, sj ≠ tj, 1 ≤ kj ≤ 3000).
Output
In the j-th line print the city that is the kj-th in the ideal path from sj to tj. If there is no ideal path from sj to tj, or the integer kj is greater than the length of this path, print the string '-1' (without quotes) in the j-th line.
Example
Input
7 7 5
1 2
2 3
1 3
3 4
4 5
5 3
4 6
1 4 2
2 6 1
1 7 3
1 3 2
1 3 5
Output
2
-1
-1
2
-1
Submitted Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
"""
created by shhuan at 2017/10/5 11:00
"""
N, M, Q = map(int, input().split())
P = collections.defaultdict(list)
for i in range(M):
s, t = map(int, input().split())
P[s].append(t)
E = []
for i in range(Q):
s, t, k = map(int, input().split())
E.append((s, t, k))
INF = False
def dfs(start, end, path, visited, circle):
global INF
if INF:
return []
if start == end:
return [path]
ans = []
for to in sorted(P[start]):
if to not in visited:
ans.extend(dfs(to, end, path+[to], visited | {to}, circle))
else:
if not circle:
i = path.index(to)
for j in range(i+1, len(path)):
if dfs(path[j-1], end, path+path[i:j], visited, True):
INF = True
return []
return ans
for s, t, k in E:
INF = False
paths = dfs(s, t, [s], set(), False)
if INF:
print(-1)
continue
if not paths:
print(-1)
continue
paths = sorted(paths)
# print(s, t, k, paths)
if paths[0] > paths[-1]:
print(-1)
else:
path = paths[0]
if k >= len(path):
print(-1)
else:
print(path[k-1])
# 2 3 4 5 4 5 4 5 .... 4 6
``` | instruction | 0 | 6,300 | 1 | 12,600 |
No | output | 1 | 6,300 | 1 | 12,601 |
Provide a correct Python 3 solution for this coding contest problem.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10 | instruction | 0 | 6,445 | 1 | 12,890 |
"Correct Solution:
```
N, M, Q = map(int, input().split())
train = [[0]*(N+1) for _ in range(N+1)]
for i in range(M):
a, b = map(int, input().split())
train[a][b] += 1
for i in range(1, N+1):
for j in range(1, N+1):
train[i][j] += train[i][j-1]
for i in range(Q):
ans = 0
l, r = map(int, input().split())
for j in range(l, r+1):
ans += train[j][r]-train[j][l-1]
print(ans)
``` | output | 1 | 6,445 | 1 | 12,891 |
Provide a correct Python 3 solution for this coding contest problem.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10 | instruction | 0 | 6,446 | 1 | 12,892 |
"Correct Solution:
```
n,m,q=map(int,input().split())
t=[[0]*(1+n) for _ in range(1+n)]
for i in range(m):
l,r=map(int,input().split())
t[l][r]+=1
for i in range(n):
for j in range(n):
t[i+1][j+1]+=t[i+1][j]+t[i][j+1]-t[i][j]
for i in range(q):
p,q=map(int,input().split())
p-=1
print(t[q][q]-t[q][p]-t[p][q]+t[p][p])
``` | output | 1 | 6,446 | 1 | 12,893 |
Provide a correct Python 3 solution for this coding contest problem.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10 | instruction | 0 | 6,447 | 1 | 12,894 |
"Correct Solution:
```
from itertools import accumulate
N, M, Q, *I = map(int, open(0).read().split())
LR, PQ = I[:2 * M], I[2 * M:]
M = [[0] * (N + 1) for _ in range(N + 1)]
for l, r in zip(*[iter(LR)] * 2):
M[l][r] += 1
A = [list(accumulate(reversed(a)))[::-1] for a in zip(*[accumulate(m) for m in M])]
for p, q in zip(*[iter(PQ)] * 2):
print(A[q][p])
``` | output | 1 | 6,447 | 1 | 12,895 |
Provide a correct Python 3 solution for this coding contest problem.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10 | instruction | 0 | 6,448 | 1 | 12,896 |
"Correct Solution:
```
n,m,q=map(int,input().split())
tpos=[[0]*(n+1) for _ in range(n+1)]
for _ in range(m):
l,r=map(int,input().split())
tpos[l][r]+=1
for i in range(1,n+1):
for j in range(1,n+1):
tpos[i][j]=tpos[i][j]+tpos[i-1][j]+tpos[i][j-1]-tpos[i-1][j-1]
for _ in range(q):
l,r=map(int,input().split())
print(tpos[r][r]-tpos[l-1][r]-tpos[r][l-1]+tpos[l-1][l-1])
``` | output | 1 | 6,448 | 1 | 12,897 |
Provide a correct Python 3 solution for this coding contest problem.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10 | instruction | 0 | 6,449 | 1 | 12,898 |
"Correct Solution:
```
import bisect
N,M,Q=map(int,input().split())
LR=[[0]*(N+1) for _ in range(N)]
for i in range(M):
l,r=map(int,input().split())
LR[l-1][r]+=1
for i in range(N):
for j in range(1,N+1):
LR[i][j]+=LR[i][j-1]
for _ in range(Q):
ans=0
p,q=map(int,input().split())
for i in range(p-1,q):
ans+=LR[i][q]-LR[i][p-1]
print(ans)
``` | output | 1 | 6,449 | 1 | 12,899 |
Provide a correct Python 3 solution for this coding contest problem.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10 | instruction | 0 | 6,450 | 1 | 12,900 |
"Correct Solution:
```
N, M, Q = map(int, input().split())
G = [[0]*(N+1) for _ in range(N+1)]
for _ in range(M):
L, R = map(int, input().split())
G[L][R] += 1
for i in range(N+1):
for j in range(1, N+1):
G[i][j] += G[i][j-1]
for _ in range(Q):
p, q = map(int, input().split())
ans = 0
for i in range(p, q+1):
ans += G[i][q]
print(ans)
``` | output | 1 | 6,450 | 1 | 12,901 |
Provide a correct Python 3 solution for this coding contest problem.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10 | instruction | 0 | 6,451 | 1 | 12,902 |
"Correct Solution:
```
N,M,Q = map(int,input().split())
LR = [[0 for _ in range(N)] for _ in range(N)]
for j in range(M):
l,r = map(int,input().split())
LR[l-1][r-1] += 1
for i in range(N):
for j in range(1,N):
LR[i][j] += LR[i][j-1]
for _ in range(Q):
p,q = map(int,input().split())
ans = 0
for i in range(q-p+1):
ans += LR[p+i-1][q-1]
print(ans)
``` | output | 1 | 6,451 | 1 | 12,903 |
Provide a correct Python 3 solution for this coding contest problem.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10 | instruction | 0 | 6,452 | 1 | 12,904 |
"Correct Solution:
```
n,m,Q = map(int,input().split())
a = []
for i in range(n+1):
a.append([0]*(n+1))
s = a[:]
for i in range(m):
l,r = map(int,input().split())
a[l][r] += 1
for l in range(1,n+1):
for r in range(1,n+1):
s[l][r] = a[l][r] + s[l-1][r] + s[l][r-1] - s[l-1][r-1]
for i in range(Q):
p,q = map(int,input().split())
print(s[q][q] - s[p-1][q] - s[q][p-1] + s[p-1][p-1])
``` | output | 1 | 6,452 | 1 | 12,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10
Submitted Solution:
```
N, M, Q = map(int, input().split())
lst = []
cnt = [0]*N
ans = [0]*Q
for i in range(M):
a, b = map(int, input().split())
lst.append([b, a, 't'])
for i in range(Q):
a, b = map(int, input().split())
lst.append([b, a+500, i])
lst.sort()
for i in lst:
if i[2] == 't':
cnt[i[1]-1] += 1
else:
ans[i[2]] = sum(cnt[i[1]-501:i[0]])
for j in ans:
print(j)
``` | instruction | 0 | 6,453 | 1 | 12,906 |
Yes | output | 1 | 6,453 | 1 | 12,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10
Submitted Solution:
```
N,M,Q = map(int,input().split())
s = [[0 for j in range(501)] for i in range(501)]
for _ in range(M):
L,R = map(int,input().split())
s[L][R] += 1
# 二次元累積和
for i in range(1,501):
for j in range(1,501):
s[i][j] += s[i-1][j] + s[i][j-1] - s[i-1][j-1]
# クエリに対してO(1)で求める
for _ in range(Q):
p,q = map(int,input().split())
print(s[q][q]-s[p-1][q]-s[q][p-1]+s[p-1][p-1])
``` | instruction | 0 | 6,454 | 1 | 12,908 |
Yes | output | 1 | 6,454 | 1 | 12,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10
Submitted Solution:
```
n,m,q=map(int,input().split())
t=[[0]*(1+n) for _ in range(1+n)]
for i in range(m):
l,r=map(int,input().split())
t[l][r]+=1
for i in range(n):
for j in range(n+1):
t[i+1][j]+=t[i][j]
for i in range(n+1):
for j in range(n):
t[i][j+1]+=t[i][j]
for i in range(q):
p,q=map(int,input().split())
print(t[q][q]-t[q][p-1]-t[p-1][q]+t[p-1][p-1])
``` | instruction | 0 | 6,455 | 1 | 12,910 |
Yes | output | 1 | 6,455 | 1 | 12,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10
Submitted Solution:
```
N, M, Q = map(int, input().split())
MAP = [[0] * N for i in range(N)]
for i in range(M):
L, R = map(int, input().split())
MAP[L-1][R-1] += 1
for r in range(N):
for l in range(N-1, 0, -1):
MAP[l-1][r] += MAP[l][r]
for r in range(N-1):
for l in range(N):
MAP[l][r+1] += MAP[l][r]
for i in range(Q):
p, q = map(int, input().split())
print(MAP[p-1][q-1])
``` | instruction | 0 | 6,456 | 1 | 12,912 |
Yes | output | 1 | 6,456 | 1 | 12,913 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10
Submitted Solution:
```
N,M,Q = [int(i) for i in input().split()]
LR = [[int(i), int(j)] for i, j in [input().split() for i in range(M)]]
LR = sorted(LR)
PQ = [[int(i), int(j)] for i, j in [input().split() for i in range(Q)]]
for p,q in PQ:
tmp = [p,-1]
LR.append(tmp)
LR = sorted(LR)
ind = LR.index(tmp)+1
tmpLR = LR[ind:]
LR.remove(tmp)
tmp = [N+1,q]
tmpLR.append(tmp)
tmpLR = sorted(tmpLR, key = lambda x:x[1])
ind = tmpLR.index(tmp)
tmpLR = tmpLR[:ind]
print(len(tmpLR))
``` | instruction | 0 | 6,457 | 1 | 12,914 |
No | output | 1 | 6,457 | 1 | 12,915 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10
Submitted Solution:
```
import numpy as np
n, m, q = map(int, input().split())
m_list = []
for i in range(m):
m_list.append(list(map(int, input().split())))
m_list = sorted(m_list)
q_list = []
for i in range(q):
q_list.append(list(map(int, input().split())))
train_map = np.array([[0 for i in range(n)] for ii in range(n)])
for m_ in m_list:
start, end = m_[0], m_[1]
train_map[:start, end-1:] += 1
for q_ in q_list:
q_s, q_e = q_[0]-1, q_[1]-1
print(train_map[q_s, q_e])
``` | instruction | 0 | 6,458 | 1 | 12,916 |
No | output | 1 | 6,458 | 1 | 12,917 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10
Submitted Solution:
```
n, m, q = map(int,input().split())
bord = [[0 for _j in range(n+1)] for _i in range(n+1)]
for _i in range(m):
left, right = map(int, input().split())
bord[left][right] += 1
result = []
for _i in range(q):
p, q = map(int, input().split())
c = 0
for i in range(p, q+1):
for j in range(p, q+1):
c += bord[i][j]
result.append(c)
print(*result)
``` | instruction | 0 | 6,459 | 1 | 12,918 |
No | output | 1 | 6,459 | 1 | 12,919 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:
* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.
Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.
Constraints
* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)
Input
Input is given from Standard Input in the following format:
N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q
Output
Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.
Examples
Input
2 3 1
1 1
1 2
2 2
1 2
Output
3
Input
10 3 2
1 5
2 8
7 10
1 7
3 10
Output
1
1
Input
10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10
Output
7
9
10
6
8
9
6
7
8
10
Submitted Solution:
```
n,m,q=map(int,input().split())
a=[]
b=[]
for i in range(n):
a.append([0]*(n))
b.append([0]*(n))
#import numpy as np
#b=np.array(b)
#print(a)
for i in range(m):
l,r=map(int,input().split())
#print(a[(r-1):n,0:l])
a[r-1][l-1]+=1
for l in range(n):
for r in range(l,n):
temp=a[r][l]
for i in range(r,n):
for j in range(0,l+1):
b[i][j]+=temp
#b[r:n,0:l+1]+=temp
#print(a)
#print(b)
for i in range(q):
P,Q=map(int,input().split())
print(b[(Q-1)][(P-1)])
``` | instruction | 0 | 6,460 | 1 | 12,920 |
No | output | 1 | 6,460 | 1 | 12,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The new pedestrian zone in Moscow city center consists of n squares connected with each other by n - 1 footpaths. We define a simple path as a sequence of squares such that no square appears in this sequence twice and any two adjacent squares in this sequence are directly connected with a footpath. The size of a simple path is the number of squares in it. The footpaths are designed in a such a way that there is exactly one simple path between any pair of different squares.
During preparations for Moscow City Day the city council decided to renew ground tiles on all n squares. There are k tile types of different colors, numbered from 1 to k. For each square exactly one tile type must be selected and then used to cover this square surface. To make walking through the city center more fascinating, it was decided to select tiles types for each square in such a way that any possible simple path of size exactly k contains squares with all k possible tile colors.
You need to find out whether it is possible to place the tiles this way or not.
Input
The first line contains two integers n, k (2 ≤ k ≤ n ≤ 200 000) — the number of squares in the new pedestrian zone, the number of different tile colors.
Each of the following n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n) — numbers of the squares connected by the corresponding road.
It's guaranteed, that it's possible to go from any square to any other square, moreover there is exactly one such simple path.
Output
Print "Yes" if it is possible to assign tile colors this way and "No" otherwise.
In case your answer is "Yes", print n integers from 1 to k each, the color of the tile for every square.
Examples
Input
7 4
1 3
2 3
3 4
4 5
5 6
5 7
Output
Yes
1 1 2 3 4 1 1
Input
7 3
1 3
2 3
3 4
4 5
5 6
5 7
Output
No
Note
The following pictures illustrate the pedestrian zone in first and second examples. The second picture also shows one possible distribution of colors among the squares for k = 4.
<image>
Submitted Solution:
```
def dfs(cur, color):
if visited[cur]:
return
visited[cur] = True
res[cur] = colors[color]
if len(graph[cur]) >= K:
print('No')
exit()
for nxt in graph[cur]:
dfs(nxt, (color + 1) % K)
input = __import__('sys').stdin.readline
N, K = map(int,input().split())
graph = [[] for _ in range(N + 1)]
visited = [False for _ in range(N + 1)]
colors = list(range(1, K + 1))
res = [-1 for _ in range(N + 1)]
for _ in range(N - 1):
a, b = map(int,input().split())
graph[a].append(b)
graph[b].append(a)
dfs(1, 0)
print('Yes')
print(" ".join(map(str,res[1:])))
``` | instruction | 0 | 6,661 | 1 | 13,322 |
No | output | 1 | 6,661 | 1 | 13,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The new pedestrian zone in Moscow city center consists of n squares connected with each other by n - 1 footpaths. We define a simple path as a sequence of squares such that no square appears in this sequence twice and any two adjacent squares in this sequence are directly connected with a footpath. The size of a simple path is the number of squares in it. The footpaths are designed in a such a way that there is exactly one simple path between any pair of different squares.
During preparations for Moscow City Day the city council decided to renew ground tiles on all n squares. There are k tile types of different colors, numbered from 1 to k. For each square exactly one tile type must be selected and then used to cover this square surface. To make walking through the city center more fascinating, it was decided to select tiles types for each square in such a way that any possible simple path of size exactly k contains squares with all k possible tile colors.
You need to find out whether it is possible to place the tiles this way or not.
Input
The first line contains two integers n, k (2 ≤ k ≤ n ≤ 200 000) — the number of squares in the new pedestrian zone, the number of different tile colors.
Each of the following n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n) — numbers of the squares connected by the corresponding road.
It's guaranteed, that it's possible to go from any square to any other square, moreover there is exactly one such simple path.
Output
Print "Yes" if it is possible to assign tile colors this way and "No" otherwise.
In case your answer is "Yes", print n integers from 1 to k each, the color of the tile for every square.
Examples
Input
7 4
1 3
2 3
3 4
4 5
5 6
5 7
Output
Yes
1 1 2 3 4 1 1
Input
7 3
1 3
2 3
3 4
4 5
5 6
5 7
Output
No
Note
The following pictures illustrate the pedestrian zone in first and second examples. The second picture also shows one possible distribution of colors among the squares for k = 4.
<image>
Submitted Solution:
```
def dfs(cur, color):
if visited[cur]:
return
visited[cur] = True
res[cur] = colors[color]
if len(graph[cur]) >= K:
print('No')
exit()
for nxt in graph[cur]:
color = (color + 1) % K
dfs(nxt, color)
input = __import__('sys').stdin.readline
N, K = map(int,input().split())
graph = [[] for _ in range(N + 1)]
visited = [False for _ in range(N + 1)]
colors = list(range(1, K + 1))
res = [-1 for _ in range(N + 1)]
for _ in range(N - 1):
a, b = map(int,input().split())
graph[a].append(b)
graph[b].append(a)
dfs(1, 0)
print('Yes')
print(" ".join(map(str,res[1:])))
``` | instruction | 0 | 6,662 | 1 | 13,324 |
No | output | 1 | 6,662 | 1 | 13,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a road consisting of several rows. Each row is divided into several rectangular tiles, and all tiles in the same row are equal. The first row contains exactly one rectangular tile. Look at the picture below which shows how the tiles are arranged.
The road is constructed as follows:
* the first row consists of 1 tile;
* then a_1 rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_1 rows follow; each of these rows contains 1 tile less than the previous row;
* then a_2 rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_2 rows follow; each of these rows contains 1 tile less than the previous row;
* ...
* then a_n rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_n rows follow; each of these rows contains 1 tile less than the previous row.
<image> An example of the road with n = 2, a_1 = 4, b_1 = 2, a_2 = 2, b_2 = 3. Rows are arranged from left to right.
You start from the only tile in the first row and want to reach the last row (any tile of it). From your current tile, you can move to any tile in the next row which touches your current tile.
Calculate the number of different paths from the first row to the last row. Since it can be large, print it modulo 998244353.
Input
The first line contains one integer n (1 ≤ n ≤ 1000).
Then n lines follow. The i-th of them contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ 10^5; |a_i - b_i| ≤ 5).
Additional constraint on the input: the sequence of a_i and b_i never results in a row with non-positive number of tiles.
Output
Print one integer — the number of paths from the first row to the last row, taken modulo 998244353.
Examples
Input
2
4 2
2 3
Output
850
Input
3
4 1
2 3
3 1
Output
10150
Input
8
328 323
867 868
715 718
721 722
439 435
868 870
834 834
797 796
Output
759099319
Submitted Solution:
```
print('dtl3')
``` | instruction | 0 | 6,826 | 1 | 13,652 |
No | output | 1 | 6,826 | 1 | 13,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a road consisting of several rows. Each row is divided into several rectangular tiles, and all tiles in the same row are equal. The first row contains exactly one rectangular tile. Look at the picture below which shows how the tiles are arranged.
The road is constructed as follows:
* the first row consists of 1 tile;
* then a_1 rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_1 rows follow; each of these rows contains 1 tile less than the previous row;
* then a_2 rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_2 rows follow; each of these rows contains 1 tile less than the previous row;
* ...
* then a_n rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_n rows follow; each of these rows contains 1 tile less than the previous row.
<image> An example of the road with n = 2, a_1 = 4, b_1 = 2, a_2 = 2, b_2 = 3. Rows are arranged from left to right.
You start from the only tile in the first row and want to reach the last row (any tile of it). From your current tile, you can move to any tile in the next row which touches your current tile.
Calculate the number of different paths from the first row to the last row. Since it can be large, print it modulo 998244353.
Input
The first line contains one integer n (1 ≤ n ≤ 1000).
Then n lines follow. The i-th of them contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ 10^5; |a_i - b_i| ≤ 5).
Additional constraint on the input: the sequence of a_i and b_i never results in a row with non-positive number of tiles.
Output
Print one integer — the number of paths from the first row to the last row, taken modulo 998244353.
Examples
Input
2
4 2
2 3
Output
850
Input
3
4 1
2 3
3 1
Output
10150
Input
8
328 323
867 868
715 718
721 722
439 435
868 870
834 834
797 796
Output
759099319
Submitted Solution:
```
print('dtl1')
``` | instruction | 0 | 6,827 | 1 | 13,654 |
No | output | 1 | 6,827 | 1 | 13,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a road consisting of several rows. Each row is divided into several rectangular tiles, and all tiles in the same row are equal. The first row contains exactly one rectangular tile. Look at the picture below which shows how the tiles are arranged.
The road is constructed as follows:
* the first row consists of 1 tile;
* then a_1 rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_1 rows follow; each of these rows contains 1 tile less than the previous row;
* then a_2 rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_2 rows follow; each of these rows contains 1 tile less than the previous row;
* ...
* then a_n rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_n rows follow; each of these rows contains 1 tile less than the previous row.
<image> An example of the road with n = 2, a_1 = 4, b_1 = 2, a_2 = 2, b_2 = 3. Rows are arranged from left to right.
You start from the only tile in the first row and want to reach the last row (any tile of it). From your current tile, you can move to any tile in the next row which touches your current tile.
Calculate the number of different paths from the first row to the last row. Since it can be large, print it modulo 998244353.
Input
The first line contains one integer n (1 ≤ n ≤ 1000).
Then n lines follow. The i-th of them contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ 10^5; |a_i - b_i| ≤ 5).
Additional constraint on the input: the sequence of a_i and b_i never results in a row with non-positive number of tiles.
Output
Print one integer — the number of paths from the first row to the last row, taken modulo 998244353.
Examples
Input
2
4 2
2 3
Output
850
Input
3
4 1
2 3
3 1
Output
10150
Input
8
328 323
867 868
715 718
721 722
439 435
868 870
834 834
797 796
Output
759099319
Submitted Solution:
```
print('quypnquypn1231211111112121')
``` | instruction | 0 | 6,828 | 1 | 13,656 |
No | output | 1 | 6,828 | 1 | 13,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider a road consisting of several rows. Each row is divided into several rectangular tiles, and all tiles in the same row are equal. The first row contains exactly one rectangular tile. Look at the picture below which shows how the tiles are arranged.
The road is constructed as follows:
* the first row consists of 1 tile;
* then a_1 rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_1 rows follow; each of these rows contains 1 tile less than the previous row;
* then a_2 rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_2 rows follow; each of these rows contains 1 tile less than the previous row;
* ...
* then a_n rows follow; each of these rows contains 1 tile greater than the previous row;
* then b_n rows follow; each of these rows contains 1 tile less than the previous row.
<image> An example of the road with n = 2, a_1 = 4, b_1 = 2, a_2 = 2, b_2 = 3. Rows are arranged from left to right.
You start from the only tile in the first row and want to reach the last row (any tile of it). From your current tile, you can move to any tile in the next row which touches your current tile.
Calculate the number of different paths from the first row to the last row. Since it can be large, print it modulo 998244353.
Input
The first line contains one integer n (1 ≤ n ≤ 1000).
Then n lines follow. The i-th of them contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ 10^5; |a_i - b_i| ≤ 5).
Additional constraint on the input: the sequence of a_i and b_i never results in a row with non-positive number of tiles.
Output
Print one integer — the number of paths from the first row to the last row, taken modulo 998244353.
Examples
Input
2
4 2
2 3
Output
850
Input
3
4 1
2 3
3 1
Output
10150
Input
8
328 323
867 868
715 718
721 722
439 435
868 870
834 834
797 796
Output
759099319
Submitted Solution:
```
print('dtl4')
``` | instruction | 0 | 6,829 | 1 | 13,658 |
No | output | 1 | 6,829 | 1 | 13,659 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8 | instruction | 0 | 7,386 | 1 | 14,772 |
"Correct Solution:
```
N=int(input())
city=[0]*N
for i in range(N):
x,y=map(int,input().split())
city[i]=(i,x,y)
city.sort(key=lambda x:x[1])
data=[(city[i][0],city[i+1][0],city[i+1][1]-city[i][1]) for i in range(N-1)]
city.sort(key=lambda x:x[2])
data+=[(city[i][0],city[i+1][0],city[i+1][2]-city[i][2]) for i in range(N-1)]
data.sort(key=lambda x:x[2])
f = list(range(N))
costs = [1] * N
def find(x):
if f[x] != x:
f[x] = find(f[x])
return f[x]
res = 0
for i, j, k in data:
fi, fj = find(i), find(j)
if fi == fj:
continue
else:
if costs[fi] <= costs[fj]:
f[fi] = fj
costs[fj] += costs[fi]
res += k
else:
f[fj] = fi
costs[fi] += costs[fj]
res += k
print(res)
``` | output | 1 | 7,386 | 1 | 14,773 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8 | instruction | 0 | 7,387 | 1 | 14,774 |
"Correct Solution:
```
# coding: utf-8
import heapq
n=int(input())
p=[]
d=[[] for i in range(n)]
for i in range(n):
p.append(tuple(map(int,input().split()))+tuple([i]))
x_sorted=sorted(p,key=lambda x:x[0])
y_sorted=sorted(p,key=lambda x:x[1])
for i in range(n-1):
d[x_sorted[i][2]].append((x_sorted[i+1][0]-x_sorted[i][0],x_sorted[i+1][2]))
d[x_sorted[i+1][2]].append((x_sorted[i+1][0]-x_sorted[i][0],x_sorted[i][2]))
d[y_sorted[i][2]].append((y_sorted[i+1][1]-y_sorted[i][1],y_sorted[i+1][2]))
d[y_sorted[i+1][2]].append((y_sorted[i+1][1]-y_sorted[i][1],y_sorted[i][2]))
h=[]
for q in d[0]:
heapq.heappush(h,q)
used=[False for i in range(n)]
used[0]=True
cost=0
while len(h):
q=heapq.heappop(h)
if used[q[1]]:
continue
used[q[1]]=True
cost+=q[0]
for r in d[q[1]]:
heapq.heappush(h,r)
print(cost)
``` | output | 1 | 7,387 | 1 | 14,775 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8 | instruction | 0 | 7,388 | 1 | 14,776 |
"Correct Solution:
```
#!/usr/bin python3
# -*- coding: utf-8 -*-
#最小全域木 クラスカル法
# 重み付き無向グラフで、それらの全ての頂点を結び連結するような木の最小のコストを求める
# 辺の重みの小さい順にみて、連結成分が閉路にならない辺を追加していく
# つなぐ頂点が同じ連結成分にないことをUnion Find Tree でみる
INF = float('inf')
class UnionFind():
def __init__(self, n): #初期化
self.n = n
# 親
self.parents = [i for i in range(n)]
# 木の深さ
self.ranks = [0] * n
def find(self, x): #親を出力
if self.parents[x] == x:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.ranks[x] < self.ranks[y]:
self.parents[x] = y
else:
self.parents[y] = x
if self.ranks[x]==self.ranks[y]:
self.ranks[x] += 1
def same(self, x, y): #xとyが同じグループかどうか
return self.find(x) == self.find(y)
def kruskal(n, edges):
uf = UnionFind(n)
ret = 0
for w, u, v in edges:
if not uf.same(u, v):
ret += w
uf.unite(u, v)
return ret
def main():
N = int(input())
#リストの作成
L = [None]*N
for i in range(N):
x, y = map(int,input().split())
L[i]=(x, y, i)
Edges = []
for i in range(2):
L.sort(key=lambda x:x[i])
for j in range(N-1):
Edges.append( (L[j+1][i]-L[j][i], L[j][2], L[j+1][2]) )
Edges.sort()
print(kruskal(N, Edges))
if __name__ == '__main__':
main()
``` | output | 1 | 7,388 | 1 | 14,777 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8 | instruction | 0 | 7,389 | 1 | 14,778 |
"Correct Solution:
```
from heapq import heappush, heappop
# 入力
N = int(input())
x, y = (
zip(*(map(int, input().split()) for _ in range(N))) if N else
((), ())
)
# x座標およびy座標について街をソートし、ソート後に隣り合う街を辺で結んだ重み付きグラフを作成する
# 作成したグラフに対してプリム法により解を求める
ts = list(zip(range(1, N + 1), x, y))
ts_x = sorted(ts, key=lambda t: t[1])
ts_y = sorted(ts, key=lambda t: t[2])
G = [{} for _ in range(N + 1)]
for ((i, a, b), (j, c, d)) in zip(ts_x[1:], ts_x):
G[i][j] = min(abs(c - a), abs(d - b))
G[j][i] = G[i][j]
for ((i, a, b), (j, c, d)) in zip(ts_y[1:], ts_y):
G[i][j] = min(abs(c - a), abs(d - b))
G[j][i] = G[i][j]
def prim(G):
used = [False for _ in range(len(G))]
res = 0
q = []
used[1] = True
for j, w in G[1].items():
heappush(q, (w, j))
while q:
w, j = heappop(q)
if not used[j]:
used[j] = True
res += w
for j2, w2 in G[j].items():
heappush(q, (w2, j2))
return res
ans = prim(G)
# 出力
print(ans)
``` | output | 1 | 7,389 | 1 | 14,779 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8 | instruction | 0 | 7,390 | 1 | 14,780 |
"Correct Solution:
```
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
a = sorted(a)
gra = []
for i in range(n):
a[i].append(i)
for i in range(n-1):
gra.append([a[i][2],a[i+1][2],a[i+1][0]-a[i][0]])
a = sorted(a,key= lambda x:x[1])
for i in range(n-1):
gra.append([a[i][2],a[i+1][2],a[i+1][1]-a[i][1]])
union = [0] * n
uc = 0
ans = 0
gra = sorted(gra, key = lambda x: x[2])
class UnionFind():
#負の値はルートで集合の個数
#正の値は次の要素を返す
def __init__(self,size):
self.table = [-1 for _ in range(size)]
#集合の代表を求める
def find(self,x):
while self.table[x] >= 0:
#根に来た時,self.table[根のindex]は負の値なのでx = 根のindexで値が返される。
x = self.table[x]
return x
#併合
def union(self,x,y):
s1 = self.find(x)#根のindex,table[s1]がグラフの高さ
s2 = self.find(y)
if s1 != s2:#根が異なる場合
if self.table[s1] != self.table[s2]:#グラフの高さが異なる場合
if self.table[s1] < self.table[s2]:
self.table[s2] = s1
else:
self.table[s1] = s2
else:
#グラフの長さが同じ場合,どちらを根にしても変わらない
#その際,グラフが1長くなることを考慮する
self.table[s1] += -1
self.table[s2] = s1
return
uni = UnionFind(n)
for i in range(len(gra)):
hen = gra[i]
if (uni.find(hen[0]) != uni.find(hen[1])):
ans += hen[2]
uni.union(hen[0],hen[1])
uc += 1
if uc == n-1:
break
print(ans)
``` | output | 1 | 7,390 | 1 | 14,781 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8 | instruction | 0 | 7,391 | 1 | 14,782 |
"Correct Solution:
```
from heapq import heapify, heappop, heappush
n = int(input())
x_loc, y_loc = [], []
for i in range(n):
x, y = map(int, input().split())
x_loc.append((x, i))
y_loc.append((y, i))
x_loc.sort()
y_loc.sort()
links = [set() for _ in range(n)]
for (x1, i1), (x2, i2) in zip(x_loc, x_loc[1:]):
dist = x2 - x1
links[i1].add((dist, i2))
links[i2].add((dist, i1))
for (y1, i1), (y2, i2) in zip(y_loc, y_loc[1:]):
dist = y2 - y1
links[i1].add((dist, i2))
links[i2].add((dist, i1))
# プリム法
visited = {0}
queue = list(links[0])
heapify(queue)
total = 0
while True:
cost, i = heappop(queue)
if i in visited:
continue
visited.add(i)
total += cost
if len(visited) == n:
break
for cost2, j in links[i]:
if j in visited:
continue
heappush(queue, (cost2, j))
print(total)
``` | output | 1 | 7,391 | 1 | 14,783 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8 | instruction | 0 | 7,392 | 1 | 14,784 |
"Correct Solution:
```
from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import *
from bisect import *
def read():
return int(input())
def reads():
return [int(x) for x in input().split()]
setrecursionlimit(1 << 30)
class union_find:
def __init__(self, n): self.par = [-1] * n; self.rank = [0] * n
def __repr__(self): return "union_find({0})".format([self.root(i) for i in range(n)])
def unite(self, x, y):
x = self.root(x); y = self.root(y)
if x == y: return
if self.rank[x] < self.rank[y]: self.par[x] = y
else:
self.par[y] = x
if self.rank[x] == self.rank[y]: self.rank[x] += 1
def root(self, x):
if self.par[x] == -1: return x
else: self.par[x] = self.root(self.par[x]); return self.par[x]
def same(self, x, y): return self.root(x) == self.root(y)
N = read()
ps = []
for i in range(N):
x, y = reads()
ps.append((i, x, y))
edges = []
for q in range(1, 3):
ps.sort(key=lambda p: p[q])
for i in range(N-1):
edges.append((ps[i+1][q] - ps[i][q], ps[i][0], ps[i+1][0]))
edges.sort()
uf = union_find(N)
ans = 0
for c, i, j in edges:
if not uf.same(i, j):
ans += c
uf.unite(i, j)
print(ans)
``` | output | 1 | 7,392 | 1 | 14,785 |
Provide a correct Python 3 solution for this coding contest problem.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8 | instruction | 0 | 7,393 | 1 | 14,786 |
"Correct Solution:
```
class UnionFindNode:
def __init__(self, group_id, parent=None, value=None):
self.group_id_ = group_id
self.parent_ = parent
self.value = value
self.rank_ = 1
self.member_num_ = 1
def is_root(self):
return not self.parent_
def root(self):
parent = self
while not parent.is_root():
parent = parent.parent_
self.parent_ = parent
return parent
def find(self):
root = self.root()
return root.group_id_
def rank(self):
root = self.root()
return root.rank_
def unite(self, unite_node):
root = self.root()
unite_root = unite_node.root()
if root.group_id_ != unite_root.group_id_:
if root.rank() > unite_root.rank():
unite_root.parent_ = root
root.rank_ = max(root.rank_, unite_root.rank_ + 1)
root.member_num_ = root.member_num_ + unite_root.member_num_
else:
root.parent_ = unite_root
unite_root.rank_ = max(root.rank_ + 1, unite_root.rank_)
unite_root.member_num_ = root.member_num_ + unite_root.member_num_
N, = map(int, input().split())
X,Y = [],[]
for i in range(1, N+1):
x, y = map(int, input().split())
X.append((x,i))
Y.append((y,i))
X = sorted(X, key=lambda x:x[0])
Y = sorted(Y, key=lambda x:x[0])
G = [set() for _ in range(N+1)]
Es = set()
for i in range(N-1):
Es.add((tuple(sorted([X[i][1], X[i+1][1]])), abs(X[i][0]-X[i+1][0])))
Es.add((tuple(sorted([Y[i][1], Y[i+1][1]])), abs(Y[i][0]-Y[i+1][0])))
G[X[i][1]].add(X[i+1][1])
G[Y[i][1]].add(Y[i+1][1])
G[X[i+1][1]].add(X[i][1])
G[Y[i+1][1]].add(Y[i][1])
node_list = [UnionFindNode(i) for i in range(N+1)]
Es = sorted(Es, key=lambda x:x[1])
r = 0
for (x, y), c in Es:
if node_list[x].find() == node_list[y].find():
continue
r += c
node_list[x].unite(node_list[y])
print(r)
``` | output | 1 | 7,393 | 1 | 14,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
class UnionFind(object):
def __init__(self, n):
self.n = n
self.par = list(range(n))
self.rank = [1] * n
def is_same(self, a, b):
return self.root(a) == self.root(b)
def root(self, x):
if self.par[x] == x:
return x
self.par[x] = self.root(self.par[x])
return self.par[x]
def unite(self, x, y):
x = self.root(x)
y = self.root(y)
if x == y:
return
if self.rank[x] > self.rank[y]:
self.par[y] = x
elif self.rank[x] < self.rank[y]:
self.par[x] = y
else:
self.par[y] = x
self.rank[x] += 1
N = int(input())
X = []
Y = []
for i in range(N):
x, y = map(int, input().split())
X.append((x, i))
Y.append((y, i))
X = sorted(X)
Y = sorted(Y)
graph = []
for i in range(N - 1):
graph.append((X[i + 1][0] - X[i][0], X[i][1], X[i + 1][1]))
graph.append((Y[i + 1][0] - Y[i][0], Y[i][1], Y[i + 1][1]))
graph.sort()
uf = UnionFind(N)
total_cost = 0
for cost, a, b in graph:
if not uf.is_same(a, b):
uf.unite(a, b)
total_cost += cost
print(total_cost)
``` | instruction | 0 | 7,394 | 1 | 14,788 |
Yes | output | 1 | 7,394 | 1 | 14,789 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
class UnionFind():
# 要素数を指定して作成 はじめは全ての要素が別グループに属し、親はいない
def __init__(self, n):
self.n = n
self.parents = [-1] * n
# xの根を返す
def find(self, x):
if self.parents[x] < 0: return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
# xとyが属するグループを併合
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y: return
if self.parents[x] > self.parents[y]: x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
# xが属するグループの要素数
def size(self, x): return -self.parents[self.find(x)]
# xとyが同じグループか否か
def same(self, x, y): return self.find(x) == self.find(y)
# xと同じメンバーの要素
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
# 根の一覧
def roots(self): return [i for i, x in enumerate(self.parents) if x < 0]
# グループ数
def group_count(self): return len(self.roots())
# 可視化 [print(uf)]
def __str__(self): return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
def kruskal(G):
G = sorted(G, key = lambda x: x[2])
U = UnionFind(len(G))
res = 0
for e in G:
s, t, w = e
if not U.same(s, t):
res += w
U.union(s, t)
return res
N = int(input())
in_list = []
for i in range(N):
in1, in2 = list(map(int,input().split()))
in_list.append([i, in1, in2])
x = sorted(in_list, key = lambda x: x[1])
y = sorted(in_list, key = lambda x: x[2])
G = []
for i in range(1, N):
G.append([x[i - 1][0], x[i][0], x[i][1] - x[i - 1][1]])
G.append([y[i - 1][0], y[i][0], y[i][2] - y[i - 1][2]])
ans = kruskal(G)
print(ans)
``` | instruction | 0 | 7,395 | 1 | 14,790 |
Yes | output | 1 | 7,395 | 1 | 14,791 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
import heapq
import sys
sys.setrecursionlimit(10 ** 7)
class UnionFind():
def __init__(self, size):
self.table = [-1 for _ in range(size)]
self.count = 0
# def find(self, x):
# while self.table[x] >= 0:
# x = self.table[x]
# return x
def find(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self.find(self.table[x])
return self.table[x]
def union(self, x, y):
s1 = self.find(x)
s2 = self.find(y)
if s1 != s2:
if self.table[s1] > self.table[s2]:
self.table[s2] = s1
elif self.table[s1] < self.table[s2]:
self.table[s1] = s2
else:
self.table[s1] = s2
self.table[s2] -= 1
self.count += 1
return True
return False
n = int(input())
x = []
y = []
for i in range(n):
a, b = map(int, input().split())
x.append([i, a])
y.append([i, b])
vx = sorted(x, key=lambda x: x[1])
vy = sorted(y, key=lambda x: x[1])
edges = []
uf = UnionFind(n)
for i in range(n - 1):
if vx[i][1] == vx[i + 1][1]:
uf.union(vx[i][0], vx[i + 1][0])
else:
heapq.heappush(edges, (vx[i + 1][1] - vx[i][1], vx[i][0], vx[i + 1][0]))
if vy[i][1] == vy[i + 1][1]:
uf.union(vy[i][0], vy[i + 1][0])
else:
heapq.heappush(edges, (vy[i + 1][1] - vy[i][1], vy[i][0], vy[i + 1][0]))
#edges = sorted(edges, key=lambda x: x[2], reverse=True)
#print(edges)
ans = 0
while edges != []:
e = heapq.heappop(edges)
if uf.union(e[1], e[2]):
ans += e[0]
if uf.count == n - 1:
break
print(ans)
``` | instruction | 0 | 7,396 | 1 | 14,792 |
Yes | output | 1 | 7,396 | 1 | 14,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
import sys
#import time
import copy
#from collections import deque, Counter, defaultdict
#from fractions import gcd
#import bisect
#import heapq
#import time
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
inf = 10**18
MOD = 1000000007
ri = lambda : int(input())
rs = lambda : input().strip()
rl = lambda : list(map(int, input().split()))
class UnionFind():
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rnk = [0]*(n+1)
# ノードxのrootノードを見つける
def find(self, x):
if(self.root[x] < 0):
return x
else:
self.root[x] = self.find(self.root[x])
return self.root[x]
# 木の併合、入力は併合したい各ノード
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if(x == y):
return
elif(self.rnk[x] > self.rnk[y]):
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if(self.rnk[x] == self.rnk[y]):
self.rnk[y] += 1
# xとyが同じグループに属するか判断
def same(self, x, y):
return self.find(x) == self.find(y)
# ノードxが属する木のサイズを返す
def size(self, x):
return -self.root[self.find(x)]
n = ri()
d1=[tuple(rl())+tuple((i,)) for i in range(n)]
d2=d1[:]
d1.sort(key=lambda x:x[0])
d2.sort(key=lambda x:x[1])
edge=[]
for i in range(n-1):
edge.append((d1[i+1][2], d1[i][2],d1[i+1][0]-d1[i][0]))
edge.append((d2[i+1][2], d2[i][2],d2[i+1][1]-d2[i][1]))
edge.sort(key=lambda x: x[2])
res=0
uf = UnionFind(n)
for e in edge:
if uf.same(e[0], e[1]):
continue
uf.unite(e[0], e[1])
res+=e[2]
print(res)
``` | instruction | 0 | 7,397 | 1 | 14,794 |
Yes | output | 1 | 7,397 | 1 | 14,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
length = int(input())
target = []
for i in range(length):
a,b = (int(n) for n in input().split(" "))
target.append([a,b,i])
target.sort()
bef_x,bef_y = -1,-1
for i in range(length-1,-1,-1):
if bef_x == target[i][0] and bef_y == target[i][1]:
target.pop(i)
length -= 1
else:
bef_x = target[i][0]
bef_y = target[i][1]
x_sorted = target[:]
y_sorted = (sorted(target,key=lambda x:x[1]))[:]
count = 0
already = set()
now_x = 0
now_y = 0
now_rev_x = length - 1
now_rev_y = length - 1
answer = 0
# print(x_sorted)
# print(y_sorted)
while count < length - 1:
x_diff = abs(x_sorted[now_x][0] - x_sorted[now_x + 1][0])
rev_x_diff = abs(x_sorted[now_rev_x][0] - x_sorted[now_rev_x - 1][0])
y_diff = abs(y_sorted[now_y][1] - y_sorted[now_y + 1][1])
rev_y_diff = abs(y_sorted[now_rev_y][1] - y_sorted[now_rev_y - 1][1])
min_choice = min(x_diff,rev_x_diff,y_diff,rev_y_diff)
if min_choice == x_diff:
real_index = {x_sorted[now_x][2],x_sorted[now_x + 1][2]}
if (real_index - already):
answer += min_choice
already |= real_index
now_x += 1
else:
now_x += 1
elif min_choice == y_diff:
real_index = {y_sorted[now_y][2],y_sorted[now_y + 1][2]}
if (real_index - already):
answer += min_choice
already |= real_index
now_y += 1
else:
now_y += 1
elif min_choice == rev_x_diff:
real_index = {x_sorted[now_rev_x][2],x_sorted[now_rev_x - 1][2]}
if (real_index - already):
answer += min_choice
already |= real_index
now_rev_x -= 1
else:
now_rev_x -= 1
else:
real_index = {y_sorted[now_rev_y][2],y_sorted[now_rev_y - 1][2]}
if (real_index - already):
answer += min_choice
already |= real_index
now_rev_y -= 1
else:
now_rev_y -= 1
if now_x == now_rev_x:
x_sorted[now_x][0] = float("inf")
elif now_y == now_rev_y:
y_sorted[now_y][1] = float("inf")
# print(x_diff,rev_x_diff,y_diff,rev_y_diff,now_x,now_rev_x,now_y,now_rev_y,answer,already)
count += 1
print(answer)
``` | instruction | 0 | 7,398 | 1 | 14,796 |
No | output | 1 | 7,398 | 1 | 14,797 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
from heapq import heappop, heappush
import sys
input = sys.stdin.readline
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n + 1)]
self.rank = [0] * (n + 1)
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def same_check(self, x, y):
return self.find(x) == self.find(y)
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if self.rank[x] < self.rank[y]:
self.par[x] = y
else:
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
class Kruskal:
def __init__(self, Q, n):
self.uf = UnionFind(n)
self.cost = 0
self.Q = Q
for i in range(2 * N - 2):
w, u, v = heappop(self.Q)
if self.uf.same_check(u, v) != True:
self.uf.union(u, v)
self.cost += w
N = int(input())
L1 = []
L2 = []
for i in range(N):
x, y = list(map(int, input().split()))
L1.append([x, y, i + 1])
L2.append([y, x, i + 1])
Lx = sorted(L1)
Ly = sorted(L2)
Q = []
for i in range(N - 1):
u = Lx[i][2]
v = Lx[i + 1][2]
w = min(Lx[i+ 1][0] - Lx[i][0], abs(Lx[i + 1][1] - Lx[i][1]))
heappush(Q, [w, u, v])
u = Ly[i][2]
v = Ly[i + 1][2]
w = min(Ly[i+ 1][0] - Ly[i][0], abs(Ly[i + 1][1] - Ly[i][1]))
heappush(Q, [w, u, v])
Km = Kruskal(Q, N)
print(Km.cost)
``` | instruction | 0 | 7,399 | 1 | 14,798 |
No | output | 1 | 7,399 | 1 | 14,799 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
import numpy as np
N=int(input())
pos_mat=np.zeros((N,2))
for i in range(N):
buf=input().split()
pos_mat[i,0]=int(buf[0])
pos_mat[i,1]=int(buf[1])
minCost_arr=np.array([float("inf") for _ in range(N)])
used_arr=np.zeros(N, dtype=bool)
minCost_arr[0]=0
totalCost=0
while np.sum(used_arr)<N:
idx=np.arange(N)[~used_arr]
u=idx[np.argmin(minCost_arr[idx])]
totalCost+=minCost_arr[u]
used_arr[u]=True
for v in range(N):
edgeCost=min(abs(pos_mat[u, 0]-pos_mat[v,0]), abs(pos_mat[u, 1]-pos_mat[v,1]))
minCost_arr[v]=min(minCost_arr[v], edgeCost)
print(int(totalCost))
``` | instruction | 0 | 7,400 | 1 | 14,800 |
No | output | 1 | 7,400 | 1 | 14,801 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.
You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.
Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ x_i,y_i ≤ 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.
Examples
Input
3
1 5
3 9
7 8
Output
3
Input
6
8 3
4 9
12 19
18 1
13 5
7 6
Output
8
Submitted Solution:
```
import sys
#import time
import copy
#from collections import deque, Counter, defaultdict
#from fractions import gcd
#import bisect
#import heapq
#import time
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
inf = 10**18
MOD = 1000000007
ri = lambda : int(input())
rs = lambda : input().strip()
rl = lambda : list(map(int, input().split()))
class UnionFind():
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rnk = [0]*(n+1)
# ノードxのrootノードを見つける
def find(self, x):
if(self.root[x] < 0):
return x
else:
self.root[x] = self.find(self.root[x])
return self.root[x]
# 木の併合、入力は併合したい各ノード
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if(x == y):
return
elif(self.rnk[x] > self.rnk[y]):
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if(self.rnk[x] == self.rnk[y]):
self.rnk[y] += 1
# xとyが同じグループに属するか判断
def same(self, x, y):
return self.find(x) == self.find(y)
# ノードxが属する木のサイズを返す
def size(self, x):
return -self.root[self.find(x)]
def kruskal(v, edge):
edge.sort(key=lambda x: x[2])
res=0
uf = UnionFind(v)
for e in edge:
if uf.same(e[0], e[1]):
continue
uf.unite(e[0], e[1])
res+=e[2]
return res
n = ri()
d1=[rl()+[i] for i in range(n)]
d2=copy.deepcopy(d1)
d1.sort(key=lambda x: x[0])
d2.sort(key=lambda x: x[1])
edge=[]
for i in range(n-1):
edge.append(( d1[i+1][2], d1[i][2],d1[i+1][0]-d1[i][0]))
edge.append(( d2[i+1][2], d2[i][2],d2[i+1][1]-d2[i][1]))
edge.sort(key=lambda x: x[2])
res=0
uf = UnionFind(n)
for e in edge:
if uf.same(e[0], e[1]):
continue
uf.unite(e[0], e[1])
res+=e[2]
print(res)
``` | instruction | 0 | 7,401 | 1 | 14,802 |
No | output | 1 | 7,401 | 1 | 14,803 |
Provide a correct Python 3 solution for this coding contest problem.
The Aizu Wakamatsu city office decided to lay a hot water pipeline covering the whole area of the city to heat houses. The pipeline starts from some hot springs and connects every district in the city. The pipeline can fork at a hot spring or a district, but no cycle is allowed. The city office wants to minimize the length of pipeline in order to build it at the least possible expense.
Write a program to compute the minimal length of the pipeline. The program reads an input that consists of the following three parts:
Hint
The first line correspondings to the first part: there are three hot springs and five districts. The following three lines are the second part: the distances between a hot spring and a district. For instance, the distance between the first hot spring and the third district is 25. The last four lines are the third part: the distances between two districts. For instance, the distance between the second and the third districts is 9. The second hot spring and the fourth district are not connectable The second and the fifth districts are not connectable, either.
Input
* The first part consists of two positive integers in one line, which represent the number s of hot springs and the number d of districts in the city, respectively.
* The second part consists of s lines: each line contains d non-negative integers. The i-th integer in the j-th line represents the distance between the j-th hot spring and the i-th district if it is non-zero. If zero it means they are not connectable due to an obstacle between them.
* The third part consists of d-1 lines. The i-th line has d - i non-negative integers. The i-th integer in the j-th line represents the distance between the j-th and the (i + j)-th districts if it is non-zero. The meaning of zero is the same as mentioned above.
For the sake of simplicity, you can assume the following:
* The number of hot springs and that of districts do not exceed 50.
* Each distance is no more than 100.
* Each line in the input file contains at most 256 characters.
* Each number is delimited by either whitespace or tab.
The input has several test cases. The input terminate with a line which has two 0. The number of test cases is less than 20.
Output
Output the minimum length of pipeline for each test case.
Example
Input
3 5
12 8 25 19 23
9 13 16 0 17
20 14 16 10 22
17 27 18 16
9 7 0
19 5
21
0 0
Output
38 | instruction | 0 | 7,442 | 1 | 14,884 |
"Correct Solution:
```
while(1):
s,d=[int(x) for x in input().split()]
A=[999 for x in range(d)]
if s==0: break
for j in range(s):
l=[int(x) for x in input().split()]
for i in range(d):
if l[i]!=0:
A[i]=min(A[i], l[i])
B=[[999 for x in range(d)] for y in range(d)]
for j in range(d-1):
l=[int(x) for x in input().split()]
for i in range(d-1-j):
if l[i]!=0:
B[j][i+j+1]=l[i]
B[i+j+1][j]=l[i]
notevaled=[1 for x in range(d)]
ans=0
for i in range(d):
mini=A.index(min(A))
ans+=A[mini]
notevaled[mini]=0
A[mini]=999
for x in range(d):
if notevaled[x]:
A[x]=min( A[x], B[mini][x] )
print(ans)
``` | output | 1 | 7,442 | 1 | 14,885 |
Provide a correct Python 3 solution for this coding contest problem.
The Aizu Wakamatsu city office decided to lay a hot water pipeline covering the whole area of the city to heat houses. The pipeline starts from some hot springs and connects every district in the city. The pipeline can fork at a hot spring or a district, but no cycle is allowed. The city office wants to minimize the length of pipeline in order to build it at the least possible expense.
Write a program to compute the minimal length of the pipeline. The program reads an input that consists of the following three parts:
Hint
The first line correspondings to the first part: there are three hot springs and five districts. The following three lines are the second part: the distances between a hot spring and a district. For instance, the distance between the first hot spring and the third district is 25. The last four lines are the third part: the distances between two districts. For instance, the distance between the second and the third districts is 9. The second hot spring and the fourth district are not connectable The second and the fifth districts are not connectable, either.
Input
* The first part consists of two positive integers in one line, which represent the number s of hot springs and the number d of districts in the city, respectively.
* The second part consists of s lines: each line contains d non-negative integers. The i-th integer in the j-th line represents the distance between the j-th hot spring and the i-th district if it is non-zero. If zero it means they are not connectable due to an obstacle between them.
* The third part consists of d-1 lines. The i-th line has d - i non-negative integers. The i-th integer in the j-th line represents the distance between the j-th and the (i + j)-th districts if it is non-zero. The meaning of zero is the same as mentioned above.
For the sake of simplicity, you can assume the following:
* The number of hot springs and that of districts do not exceed 50.
* Each distance is no more than 100.
* Each line in the input file contains at most 256 characters.
* Each number is delimited by either whitespace or tab.
The input has several test cases. The input terminate with a line which has two 0. The number of test cases is less than 20.
Output
Output the minimum length of pipeline for each test case.
Example
Input
3 5
12 8 25 19 23
9 13 16 0 17
20 14 16 10 22
17 27 18 16
9 7 0
19 5
21
0 0
Output
38 | instruction | 0 | 7,443 | 1 | 14,886 |
"Correct Solution:
```
# AOJ 1014: Computation of Minimum Length of Pipeline
# Python3 2018.7.5 bal4u
import sys
from sys import stdin
input = stdin.readline
import heapq
while True:
s, d = map(int, input().split())
if s == 0: break
visited = [0]*100
Q = []
to = [[] for i in range(100)]
for i in range(s):
visited[i] = 1
c = list(map(int, input().split()))
for j in range(d):
if c[j] > 0: heapq.heappush(Q, (c[j], i, s+j))
for i in range(d-1):
c = list(map(int, input().split()))
for j in range(i+1, d):
if c[j-i-1] > 0:
to[s+i].append((s+j, c[j-i-1]))
to[s+j].append((s+i, c[j-i-1]))
ans = k = 0
while k < d:
while True:
c, a, b = heapq.heappop(Q)
if visited[a] == 0 or visited[b] == 0: break
ans, k = ans+c, k+1
if visited[a]: a = b
visited[a] = 1;
for e, c in to[a]:
if visited[e] == 0: heapq.heappush(Q, (c, a, e))
print(ans)
``` | output | 1 | 7,443 | 1 | 14,887 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Aizu Wakamatsu city office decided to lay a hot water pipeline covering the whole area of the city to heat houses. The pipeline starts from some hot springs and connects every district in the city. The pipeline can fork at a hot spring or a district, but no cycle is allowed. The city office wants to minimize the length of pipeline in order to build it at the least possible expense.
Write a program to compute the minimal length of the pipeline. The program reads an input that consists of the following three parts:
Hint
The first line correspondings to the first part: there are three hot springs and five districts. The following three lines are the second part: the distances between a hot spring and a district. For instance, the distance between the first hot spring and the third district is 25. The last four lines are the third part: the distances between two districts. For instance, the distance between the second and the third districts is 9. The second hot spring and the fourth district are not connectable The second and the fifth districts are not connectable, either.
Input
* The first part consists of two positive integers in one line, which represent the number s of hot springs and the number d of districts in the city, respectively.
* The second part consists of s lines: each line contains d non-negative integers. The i-th integer in the j-th line represents the distance between the j-th hot spring and the i-th district if it is non-zero. If zero it means they are not connectable due to an obstacle between them.
* The third part consists of d-1 lines. The i-th line has d - i non-negative integers. The i-th integer in the j-th line represents the distance between the j-th and the (i + j)-th districts if it is non-zero. The meaning of zero is the same as mentioned above.
For the sake of simplicity, you can assume the following:
* The number of hot springs and that of districts do not exceed 50.
* Each distance is no more than 100.
* Each line in the input file contains at most 256 characters.
* Each number is delimited by either whitespace or tab.
The input has several test cases. The input terminate with a line which has two 0. The number of test cases is less than 20.
Output
Output the minimum length of pipeline for each test case.
Example
Input
3 5
12 8 25 19 23
9 13 16 0 17
20 14 16 10 22
17 27 18 16
9 7 0
19 5
21
0 0
Output
38
Submitted Solution:
```
while(1):
s,d=[int(x) for x in input().split()]
A=[999 for x in range(d)]
if s==0: break
for j in range(s):
l=[int(x) for x in input().split()]
for i in range(d):
if l[i]!=0:
A[i]=min(A[i], l[i])
B=[[999 for x in range(d)] for y in range(d)]
for j in range(d-1):
l=[int(x) for x in input().split()]
for i in range(d-1-j):
if l[i]!=0:
B[i][i+j+1]=l[i]
B[i+j+1][i]=l[i]
notevaled=[1 for x in range(d)]
ans=0
for i in range(d):
mini=A.index(min(A))
ans+=A[mini]
notevaled[mini]=0
A[mini]=999
for x in range(d):
if notevaled[x]:
A[x]=min( A[x], B[mini][x] )
print(ans)
``` | instruction | 0 | 7,444 | 1 | 14,888 |
No | output | 1 | 7,444 | 1 | 14,889 |
Provide a correct Python 3 solution for this coding contest problem.
Despite urging requests of the townspeople, the municipal office cannot afford to improve many of the apparently deficient city amenities under this recession. The city swimming pool is one of the typical examples. It has only two swimming lanes. The Municipal Fitness Agency, under this circumstances, settled usage rules so that the limited facilities can be utilized fully.
Two lanes are to be used for one-way swimming of different directions. Swimmers are requested to start swimming in one of the lanes, from its one end to the other, and then change the lane to swim his/her way back. When he or she reaches the original starting end, he/she should return to his/her initial lane and starts swimming again.
Each swimmer has his/her own natural constant pace. Swimmers, however, are not permitted to pass other swimmers except at the ends of the pool; as the lanes are not wide enough, that might cause accidents. If a swimmer is blocked by a slower swimmer, he/she has to follow the slower swimmer at the slower pace until the end of the lane is reached. Note that the blocking swimmer’s natural pace may be faster than the blocked swimmer; the blocking swimmer might also be blocked by another swimmer ahead, whose natural pace is slower than the blocked swimmer. Blocking would have taken place whether or not a faster swimmer was between them.
Swimmers can change their order if they reach the end of the lane simultaneously. They change their order so that ones with faster natural pace swim in front. When a group of two or more swimmers formed by a congestion reaches the end of the lane, they are considered to reach there simultaneously, and thus change their order there.
The number of swimmers, their natural paces in times to swim from one end to the other, and the numbers of laps they plan to swim are given. Note that here one "lap" means swimming from one end to the other and then swimming back to the original end. Your task is to calculate the time required for all the swimmers to finish their plans. All the swimmers start from the same end of the pool at the same time, the faster swimmers in front.
In solving this problem, you can ignore the sizes of swimmers' bodies, and also ignore the time required to change the lanes and the order in a group of swimmers at an end of the lanes.
Input
The input is a sequence of datasets. Each dataset is formatted as follows.
n
t1 c1
...
tn cn
n is an integer (1 ≤ n ≤ 50) that represents the number of swimmers. ti and ci are integers (1 ≤ ti ≤ 300, 1 ≤ ci ≤ 250) that represent the natural pace in times to swim from one end to the other and the number of planned laps for the i-th swimmer, respectively. ti and ci are separated by a space.
The end of the input is indicated by a line containing one zero.
Output
For each dataset, output the time required for all the swimmers to finish their plans in a line. No extra characters should occur in the output.
Example
Input
2
10 30
15 20
2
10 240
15 160
3
2 6
7 2
8 2
4
2 4
7 2
8 2
18 1
0
Output
600
4800
36
40 | instruction | 0 | 7,456 | 1 | 14,912 |
"Correct Solution:
```
from collections import deque
while 1:
N = int(input())
if N == 0:
break
T = [0]*N; C = [0]*N
que0 = deque()
que1 = deque()
P = [list(map(int, input().split())) for i in range(N)]
P.sort()
for i in range(N):
t, c = P[i]
que0.append((i, t))
T[i] = t
C[i] = c
INF = 10**18
ans = 0
rest = N
while rest:
t = min(que0[0][1] if que0 else INF, que1[0][1] if que1 else INF)
st0 = []; st1 = []
while que0 and que0[0][1] <= t:
st0.append(que0.popleft()[0])
st0.sort()
for i in st0:
que1.append((i, t+T[i]))
while que1 and que1[0][1] <= t:
st1.append(que1.popleft()[0])
st1.sort()
for i in st1:
if C[i] == 1:
rest -= 1
else:
que0.append((i, t+T[i]))
C[i] -= 1
ans = max(ans, t)
print(ans)
``` | output | 1 | 7,456 | 1 | 14,913 |
Provide a correct Python 3 solution for this coding contest problem.
Despite urging requests of the townspeople, the municipal office cannot afford to improve many of the apparently deficient city amenities under this recession. The city swimming pool is one of the typical examples. It has only two swimming lanes. The Municipal Fitness Agency, under this circumstances, settled usage rules so that the limited facilities can be utilized fully.
Two lanes are to be used for one-way swimming of different directions. Swimmers are requested to start swimming in one of the lanes, from its one end to the other, and then change the lane to swim his/her way back. When he or she reaches the original starting end, he/she should return to his/her initial lane and starts swimming again.
Each swimmer has his/her own natural constant pace. Swimmers, however, are not permitted to pass other swimmers except at the ends of the pool; as the lanes are not wide enough, that might cause accidents. If a swimmer is blocked by a slower swimmer, he/she has to follow the slower swimmer at the slower pace until the end of the lane is reached. Note that the blocking swimmer’s natural pace may be faster than the blocked swimmer; the blocking swimmer might also be blocked by another swimmer ahead, whose natural pace is slower than the blocked swimmer. Blocking would have taken place whether or not a faster swimmer was between them.
Swimmers can change their order if they reach the end of the lane simultaneously. They change their order so that ones with faster natural pace swim in front. When a group of two or more swimmers formed by a congestion reaches the end of the lane, they are considered to reach there simultaneously, and thus change their order there.
The number of swimmers, their natural paces in times to swim from one end to the other, and the numbers of laps they plan to swim are given. Note that here one "lap" means swimming from one end to the other and then swimming back to the original end. Your task is to calculate the time required for all the swimmers to finish their plans. All the swimmers start from the same end of the pool at the same time, the faster swimmers in front.
In solving this problem, you can ignore the sizes of swimmers' bodies, and also ignore the time required to change the lanes and the order in a group of swimmers at an end of the lanes.
Input
The input is a sequence of datasets. Each dataset is formatted as follows.
n
t1 c1
...
tn cn
n is an integer (1 ≤ n ≤ 50) that represents the number of swimmers. ti and ci are integers (1 ≤ ti ≤ 300, 1 ≤ ci ≤ 250) that represent the natural pace in times to swim from one end to the other and the number of planned laps for the i-th swimmer, respectively. ti and ci are separated by a space.
The end of the input is indicated by a line containing one zero.
Output
For each dataset, output the time required for all the swimmers to finish their plans in a line. No extra characters should occur in the output.
Example
Input
2
10 30
15 20
2
10 240
15 160
3
2 6
7 2
8 2
4
2 4
7 2
8 2
18 1
0
Output
600
4800
36
40 | instruction | 0 | 7,457 | 1 | 14,914 |
"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**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
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():
rr = []
def f(n):
a = [LI() for _ in range(n)]
q = []
d = [0] * 2
for t,c in a:
heapq.heappush(q, (0,0,t,c*2))
while q:
ct, l, t, c = heapq.heappop(q)
nx = l ^ 1
nt = ct + t
if d[nx] > nt:
nt = d[nx]
else:
d[nx] = nt
if c > 1:
heapq.heappush(q, (nt,nx,t,c-1))
return max(d)
while 1:
n = I()
if n == 0:
break
rr.append(f(n))
return '\n'.join(map(str, rr))
print(main())
``` | output | 1 | 7,457 | 1 | 14,915 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.