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.
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.
Input
The first line contains three integers L, b и f (10 ≤ L ≤ 100000, 1 ≤ b, f ≤ 100). The second line contains an integer n (1 ≤ n ≤ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.
Output
For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.
Examples
Input
30 1 2
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
23
Input
30 1 1
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
6
Input
10 1 1
1
1 12
Output
-1 | instruction | 0 | 36,483 | 1 | 72,966 |
Tags: data structures, implementation
Correct Solution:
```
l,b,f=list(map(int,input().split()))
n=int(input())
a=[]
z=0
for j in range(n):
d,c=list(map(int,input().split()))
if d==1:
x=-1
y=0
for i in range(z):
if a[i][0]+a[i][1]+b+c<=l and (i==z-1 or a[i][0]+a[i][1]+b+c<=a[i+1][0]-f):
x=a[i][0]+a[i][1]+b
y=i+1
break
if z==0:
if c<=l:
print(0)
a=[[0,c,j+1]]+a
z+=1
else:
print(-1)
else:
if c+f<=a[0][0]:
print(0)
a=[[0,c,j+1]]+a
z+=1
elif x==-1:
print(-1)
else:
print(x)
a=a[:y]+[[x,c,j+1]]+a[y:]
z+=1
else:
for i in range(z):
if a[i][2]==c:
a=a[:i]+a[i+1:]
z-=1
break
``` | output | 1 | 36,483 | 1 | 72,967 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.
Input
The first line contains three integers L, b и f (10 ≤ L ≤ 100000, 1 ≤ b, f ≤ 100). The second line contains an integer n (1 ≤ n ≤ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.
Output
For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.
Examples
Input
30 1 2
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
23
Input
30 1 1
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
6
Input
10 1 1
1
1 12
Output
-1
Submitted Solution:
```
from sys import stdin
L,b,f = [int(x) for x in stdin.readline().split()]
n = int(stdin.readline())
segs = [[0,L]]
cars = {}
for x in range(n):
r,ln = [int(x) for x in stdin.readline().split()]
if r == 1:
#print(segs)
place = -1
bruh = len(segs)
for ind in range(bruh):
s = segs[ind]
start,end = s
tB = b
tF = f
if start == 0:
tB = 0
if end == L:
tF = 0
if end-start >= tB+tF+ln:
place = start+tB
cars[x] = [start+tB, start+tB+ln]
s[0] += tB+ln
segs.insert(ind, [start,start+tB])
print(place)
else:
ln -= 1
start,end = cars[ln]
for x in range(len(segs)-1):
if segs[x][1] == start and segs[x+1][0] == end:
segs[x][1] = segs[x+1][1]
del segs[x+1]
``` | instruction | 0 | 36,484 | 1 | 72,968 |
No | output | 1 | 36,484 | 1 | 72,969 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.
Input
The first line contains three integers L, b и f (10 ≤ L ≤ 100000, 1 ≤ b, f ≤ 100). The second line contains an integer n (1 ≤ n ≤ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.
Output
For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.
Examples
Input
30 1 2
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
23
Input
30 1 1
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
6
Input
10 1 1
1
1 12
Output
-1
Submitted Solution:
```
from sys import stdin
L,b,f = [int(x) for x in stdin.readline().split()]
n = int(stdin.readline())
segs = [[0,L]]
cars = {}
for x in range(n):
r,ln = [int(x) for x in stdin.readline().split()]
if r == 1:
#print(segs)
place = -1
bruh = len(segs)
for ind in range(bruh):
s = segs[ind]
start,end = s
tB = b
tF = f
if start == 0:
tB = 0
if end == L:
tF = 0
if end-start >= tB+tF+ln:
place = start+tB
cars[x] = [start+tB, start+tB+ln]
s[0] += tB+ln
if tB > 0:
segs.insert(ind, [start,start+tB])
print(place)
else:
ln -= 1
start,end = cars[ln]
for x in range(len(segs)-1):
if segs[x][1] == start and segs[x+1][0] == end:
segs[x][1] = segs[x+1][1]
del segs[x+1]
``` | instruction | 0 | 36,485 | 1 | 72,970 |
No | output | 1 | 36,485 | 1 | 72,971 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.
Input
The first line contains three integers L, b и f (10 ≤ L ≤ 100000, 1 ≤ b, f ≤ 100). The second line contains an integer n (1 ≤ n ≤ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.
Output
For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.
Examples
Input
30 1 2
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
23
Input
30 1 1
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
6
Input
10 1 1
1
1 12
Output
-1
Submitted Solution:
```
from sys import stdin
L,b,f = [int(x) for x in stdin.readline().split()]
n = int(stdin.readline())
segs = [[0,L]]
cars = {}
for x in range(n):
r,ln = [int(x) for x in stdin.readline().split()]
if r == 1:
#print(segs)
place = -1
bruh = len(segs)
for ind in range(bruh):
s = segs[ind]
start,end = s
tB = b
tF = f
if start == 0:
tB = 0
if end == L+1:
tF = 0
if end-start >= tB+tF+ln:
place = start+tB
cars[x] = [start+tB, start+tB+ln]
s[0] += tB+ln
if tB > 0:
segs.insert(ind, [start,start+tB])
print(place)
else:
ln -= 1
start,end = cars[ln]
for x in range(len(segs)-1):
if segs[x][1] == start and segs[x+1][0] == end:
segs[x][1] = segs[x+1][1]
del segs[x+1]
``` | instruction | 0 | 36,486 | 1 | 72,972 |
No | output | 1 | 36,486 | 1 | 72,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.
Input
The first line contains three integers L, b и f (10 ≤ L ≤ 100000, 1 ≤ b, f ≤ 100). The second line contains an integer n (1 ≤ n ≤ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.
Output
For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.
Examples
Input
30 1 2
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
23
Input
30 1 1
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
6
Input
10 1 1
1
1 12
Output
-1
Submitted Solution:
```
from sys import stdin
L,b,f = [int(x) for x in stdin.readline().split()]
n = int(stdin.readline())
segs = [[0,L+1]]
cars = {}
for x in range(n):
r,ln = [int(x) for x in stdin.readline().split()]
if r == 1:
place = -1
bruh = len(segs)
for ind in range(bruh):
s = segs[ind]
start,end = s
tB = b
tF = f
if start == 0:
tB = 0
if end == L+1:
tF = 0
if end-start >= tB+tF+ln:
place = start+tB
cars[x] = [start+tB, start+tB+ln]
s[0] += tB+ln
segs.insert(ind, [start,start+tB])
print(place)
else:
ln -= 1
start,end = cars[ln]
for x in range(len(segs)-1):
if segs[x][1] == start and segs[x+1][0] == end:
segs[x][1] = segs[x+1][1]
del segs[x+1]
``` | instruction | 0 | 36,487 | 1 | 72,974 |
No | output | 1 | 36,487 | 1 | 72,975 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive.
All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road.
Your task is — for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (109 + 7).
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 2·105) — the number of cities in the country. Next line contains n - 1 positive integers p2, p3, p4, ..., pn (1 ≤ pi ≤ i - 1) — the description of the roads in the country. Number pi means that the country has a road connecting city pi and city i.
Output
Print n integers a1, a2, ..., an, where ai is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (109 + 7), if the capital of the country is at city number i.
Examples
Input
3
1 1
Output
4 3 3
Input
5
1 2 3 4
Output
5 8 9 8 5 | instruction | 0 | 36,502 | 1 | 73,004 |
Tags: dp, trees
Correct Solution:
```
class Graph:
def __init__(self, n_vertices, edges, directed=True, weighted=False):
self.n_vertices = n_vertices
self.edges = edges
self.directed = directed
self.weighted = weighted
@property
def adj(self):
try:
return self._adj
except AttributeError:
adj = [[] for _ in range(self.n_vertices)]
def d_w(e):
adj[e[0]].append((e[1],e[2]))
def ud_w(e):
adj[e[0]].append((e[1],e[2]))
adj[e[1]].append((e[0],e[2]))
def d_uw(e):
adj[e[0]].append(e[1])
def ud_uw(e):
adj[e[0]].append(e[1])
adj[e[1]].append(e[0])
helper = (ud_uw, d_uw, ud_w, d_w)[self.directed+self.weighted*2]
for e in self.edges:
helper(e)
self._adj = adj
return adj
class RootedTree(Graph):
def __init__(self, n_vertices, edges, root_vertex):
self.root = root_vertex
super().__init__(n_vertices, edges, False, False)
@property
def parent(self):
try:
return self._parent
except AttributeError:
adj = self.adj
parent = [None]*self.n_vertices
parent[self.root] = -1
stack = [self.root]
for i in range(self.n_vertices):
v = stack.pop()
for u in adj[v]:
if parent[u] is None:
parent[u] = v
stack.append(u)
self._parent = parent
return parent
@property
def children(self):
try:
return self._children
except AttributeError:
children = [None]*self.n_vertices
for v,(l,p) in enumerate(zip(self.adj,self.parent)):
children[v] = [u for u in l if u != p]
self._children = children
return children
@property
def dfs_order(self):
try:
return self._dfs_order
except AttributeError:
order = [None]*self.n_vertices
children = self.children
stack = [self.root]
for i in range(self.n_vertices):
v = stack.pop()
order[i] = v
for u in children[v]:
stack.append(u)
self._dfs_order = order
return order
from functools import reduce
from itertools import accumulate,chain
def rerooting(rooted_tree, merge, identity, finalize):
N = rooted_tree.n_vertices
parent = rooted_tree.parent
children = rooted_tree.children
order = rooted_tree.dfs_order
# from leaf to parent
dp_down = [None]*N
for v in reversed(order[1:]):
dp_down[v] = finalize(reduce(merge,
(dp_down[c] for c in children[v]),
identity))
# from parent to leaf
dp_up = [None]*N
dp_up[0] = identity
for v in order:
if len(children[v]) == 0:
continue
temp = (dp_up[v],)+tuple(dp_down[u] for u in children[v])+(identity,)
left = tuple(accumulate(temp,merge))
right = tuple(accumulate(reversed(temp[2:]),merge))
for u,l,r in zip(children[v],left,reversed(right)):
dp_up[u] = finalize(merge(l,r))
res = [None]*N
for v,l in enumerate(children):
res[v] = reduce(merge,
(dp_down[u] for u in children[v]),
identity)
res[v] = finalize(merge(res[v], dp_up[v]))
return res
def solve(T):
MOD = 10**9 + 7
def merge(x,y):
return (x*y)%MOD
def finalize(x):
return x+1
return [v-1 for v in rerooting(T,merge,1,finalize)]
if __name__ == '__main__':
N = int(input())
edges = [(i+1,p-1) for i,p in enumerate(map(int,input().split()))]
T = RootedTree(N, edges, 0)
print(*solve(T))
``` | output | 1 | 36,502 | 1 | 73,005 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive.
All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road.
Your task is — for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (109 + 7).
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 2·105) — the number of cities in the country. Next line contains n - 1 positive integers p2, p3, p4, ..., pn (1 ≤ pi ≤ i - 1) — the description of the roads in the country. Number pi means that the country has a road connecting city pi and city i.
Output
Print n integers a1, a2, ..., an, where ai is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (109 + 7), if the capital of the country is at city number i.
Examples
Input
3
1 1
Output
4 3 3
Input
5
1 2 3 4
Output
5 8 9 8 5 | instruction | 0 | 36,503 | 1 | 73,006 |
Tags: dp, trees
Correct Solution:
```
class Graph:
def __init__(self, n_vertices, edges, directed=True, weighted=False):
self.n_vertices = n_vertices
self.edges = edges
self.directed = directed
self.weighted = weighted
@property
def adj(self):
try:
return self._adj
except AttributeError:
adj = [[] for _ in range(self.n_vertices)]
def d_w(e):
adj[e[0]].append((e[1],e[2]))
def ud_w(e):
adj[e[0]].append((e[1],e[2]))
adj[e[1]].append((e[0],e[2]))
def d_uw(e):
adj[e[0]].append(e[1])
def ud_uw(e):
adj[e[0]].append(e[1])
adj[e[1]].append(e[0])
helper = (ud_uw, d_uw, ud_w, d_w)[self.directed+self.weighted*2]
for e in self.edges:
helper(e)
self._adj = adj
return adj
class RootedTree(Graph):
def __init__(self, n_vertices, edges, root_vertex):
self.root = root_vertex
super().__init__(n_vertices, edges, False, False)
@property
def parent(self):
try:
return self._parent
except AttributeError:
adj = self.adj
parent = [None]*self.n_vertices
parent[self.root] = -1
stack = [self.root]
for i in range(self.n_vertices):
v = stack.pop()
for u in adj[v]:
if parent[u] is None:
parent[u] = v
stack.append(u)
self._parent = parent
return parent
@property
def children(self):
try:
return self._children
except AttributeError:
children = [None]*self.n_vertices
for v,(l,p) in enumerate(zip(self.adj,self.parent)):
children[v] = [u for u in l if u != p]
self._children = children
return children
@property
def dfs_order(self):
try:
return self._dfs_order
except AttributeError:
order = [None]*self.n_vertices
children = self.children
stack = [self.root]
for i in range(self.n_vertices):
v = stack.pop()
order[i] = v
for u in children[v]:
stack.append(u)
self._dfs_order = order
return order
from functools import reduce
from itertools import accumulate,chain
def rerooting(rooted_tree, merge, identity, finalize):
N = rooted_tree.n_vertices
parent = rooted_tree.parent
children = rooted_tree.children
order = rooted_tree.dfs_order
# from leaf to parent
dp_down = [None]*N
for v in reversed(order[1:]):
dp_down[v] = finalize(reduce(merge,
(dp_down[c] for c in children[v]),
identity))
# from parent to leaf
dp_up = [None]*N
dp_up[0] = identity
for v in order:
if len(children[v]) == 0:
continue
temp = (dp_up[v],)+tuple(dp_down[u] for u in children[v])+(identity,)
left = accumulate(temp[:-2],merge)
right = tuple(accumulate(reversed(temp[2:]),merge))
for u,l,r in zip(children[v],left,reversed(right)):
dp_up[u] = finalize(merge(l,r))
res = [None]*N
for v,l in enumerate(children):
res[v] = reduce(merge,
(dp_down[u] for u in children[v]),
identity)
res[v] = finalize(merge(res[v], dp_up[v]))
return res
def solve(T):
MOD = 10**9 + 7
def merge(x,y):
return (x*y)%MOD
def finalize(x):
return x+1
return [v-1 for v in rerooting(T,merge,1,finalize)]
if __name__ == '__main__':
N = int(input())
edges = [(i+1,p-1) for i,p in enumerate(map(int,input().split()))]
T = RootedTree(N, edges, 0)
print(*solve(T))
``` | output | 1 | 36,503 | 1 | 73,007 |
Provide a correct Python 3 solution for this coding contest problem.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0 | instruction | 0 | 36,635 | 1 | 73,270 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
def main():
n = int(input())
l = [list(map(int,input().split())) for i in range(n)]
xcal = [[0]*n for i in range(1<<n)]
ycal = [[0]*n for i in range(1<<n)]
for i in range(1<<n):
for j in range(n):
xcal[i][j] = abs(l[j][0])
ycal[i][j] = abs(l[j][1])
for k in range(n):
if (i>>k) & 1:
xcal[i][j] = min(xcal[i][j],abs(l[j][0]-l[k][0]))
ycal[i][j] = min(ycal[i][j],abs(l[j][1]-l[k][1]))
xcal[i][j] *= l[j][2]
ycal[i][j] *= l[j][2]
ans = [float("INF")]*(n+1)
for i in range(1<<n):
count = 0
for j in range(n):
if i >> j & 1:
count += 1
j = i
while j >= 0:
j &= i
cost = 0
for k in range(n):
if not (i>>k & 1):
cost += min(xcal[j][k],ycal[i-j][k])
if cost > ans[count]:
break
ans[count] = min(ans[count],cost)
j -= 1
for i in ans:
print(i)
if __name__ == "__main__":
main()
``` | output | 1 | 36,635 | 1 | 73,271 |
Provide a correct Python 3 solution for this coding contest problem.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0 | instruction | 0 | 36,636 | 1 | 73,272 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
INF = float('inf')
N = int(input().strip())
data = [list(map(int, input().split())) for _ in range(N)]
cost_b = []
cost_D = []
for b in range(1<<N):
towns = []
cost = INF
for i in range(N):
if (b>>i)&1:
towns.append(data[i])
for i in range(len(towns)):
X = towns[i][0]
cost = min(cost,sum(abs(towns[j][0]-X)*towns[j][2] for j in range(len(towns))))
for i in range(len(towns)):
Y = towns[i][1]
cost = min(cost,sum(abs(towns[j][1]-Y)*towns[j][2] for j in range(len(towns))))
if len(towns) == 0:
cost = 0
cost_b.append(cost)
cost_D.append(sum(min(abs(towns[j][0]),abs(towns[j][1]))*towns[j][2] for j in range(len(towns))))
dp = [[INF]*(N+1) for i in range(1<<N)]
for i in range(1<<N):
dp[i][0] = cost_D[i]
count = 0
for k in range(1,N+1):
for i in reversed(range(1<<N)):
x = i
while x>=0:
x &= i
new = dp[i-x][k-1]+cost_b[x]
if dp[i][k] > new:
dp[i][k] = new
if new == 0:
break
x -= 1
for i in range(N+1):
print(dp[-1][i])
``` | output | 1 | 36,636 | 1 | 73,273 |
Provide a correct Python 3 solution for this coding contest problem.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0 | instruction | 0 | 36,637 | 1 | 73,274 |
"Correct Solution:
```
inf = 10**15
def main():
import sys
input = sys.stdin.readline
N = int(input())
X = []
Y = []
P = []
for _ in range(N):
x, y, p = map(int, input().split())
X.append(x)
Y.append(y)
P.append(p)
dx = [[inf] * N for _ in range(1<<N)]
dy = [[inf] * N for _ in range(1<<N)]
for i in range(1 << N):
Xline = [0]
Yline = [0]
for j in range(N):
if i>>j&1:
Xline.append(X[j])
Yline.append(Y[j])
for j in range(N):
for x, y in zip(Xline, Yline):
dx[i][j] = min(dx[i][j], abs(x - X[j]))
dy[i][j] = min(dy[i][j], abs(y - Y[j]))
ans = [inf] * (N+1)
beki = [1<<j for j in range(N)]
for i in range(3**(N-1)):
M = i
k = 0
ix = iy = 0
J = []
for j in range(N-1):
M, m = divmod(M, 3)
if m == 0:
J.append(j)
elif m == 1:
k += 1
ix += beki[j]
else:
k += 1
iy += beki[j]
for x in range(3):
kk = k
ix_ = ix
iy_ = iy
if x == 0:
J.append(N-1)
elif x == 1:
kk += 1
ix_ += beki[N-1]
else:
kk += 1
iy_ += beki[N-1]
cost = 0
for j in J:
p = P[j]
cost += min(dx[ix_][j], dy[iy_][j]) * p
ans[kk] = min(ans[kk], cost)
for c in ans:
print(c)
if __name__ == '__main__':
main()
``` | output | 1 | 36,637 | 1 | 73,275 |
Provide a correct Python 3 solution for this coding contest problem.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0 | instruction | 0 | 36,638 | 1 | 73,276 |
"Correct Solution:
```
# Fast IO (only use in integer input)
# TLE
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def main():
N = int(input())
Resident = []
for i in range(N):
x,y,p = map(int,input().split())
Resident.append((x,y,p))
def abs(N):
if N >= 0:
return N
else:
return -N
minCost = [float("inf")] * (N+1)
preCalRange = 1 << N
horizontalLineDistance = []
verticalLineDistance = []
for i in range(preCalRange):
railRoad = bin(i)[2:]
railRoad = '0' * (N - len(railRoad)) + railRoad
horizontalLineDistance.append([])
verticalLineDistance.append([])
for j in range(N):
horizontalLineDistance[i].append(min(abs(Resident[j][0]),abs(Resident[j][1])))
verticalLineDistance[i].append(min(abs(Resident[j][0]),abs(Resident[j][1])))
for k in range(N):
if railRoad[k] == '1' and abs(Resident[j][0] - Resident[k][0]) < horizontalLineDistance[i][j]:
horizontalLineDistance[i][j] = abs(Resident[j][0] - Resident[k][0])
if railRoad[k] == '1' and abs(Resident[j][1] - Resident[k][1]) < verticalLineDistance[i][j]:
verticalLineDistance[i][j] = abs(Resident[j][1] - Resident[k][1])
power2 = [1]
for i in range(N):
power2.append(power2[-1] * 2)
loopCount = power2[N]
for i in range(loopCount):
numNewRailroad = bin(i)[2:].count('1')
j = i
while j >= 0:
j &= i
goodList1 = horizontalLineDistance[j]
goodList2 = verticalLineDistance[i - j]
cost = 0
for k in range(N):
cost += Resident[k][2] * min(goodList1[k], goodList2[k])
if minCost[numNewRailroad] > cost:
minCost[numNewRailroad] = cost
j -= 1
for elem in minCost:
print(elem)
main()
``` | output | 1 | 36,638 | 1 | 73,277 |
Provide a correct Python 3 solution for this coding contest problem.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0 | instruction | 0 | 36,639 | 1 | 73,278 |
"Correct Solution:
```
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
INF = 1 << 50
def generate_dist_arr(X, Y, P):
N = len(X)
dist_arr_x = [[] for _ in range(1<<N)]
dist_arr_y = [[] for _ in range(1<<N)]
for j in range(1 << N): # x-y-lines
x_lines_list = [0]
y_lines_list = [0]
for k in range(N):
if j >> k & 1:
x_lines_list.append(X[k])
y_lines_list.append(Y[k])
dist_xx, dist_yy = [INF] * N, [INF] * N
x_lines_list = sorted(x_lines_list)
y_lines_list = sorted(y_lines_list)
for idx, x in enumerate(X):
v = bisect.bisect_left(x_lines_list, x)
pre_x = x_lines_list[min(v-1, 0)]
post_x = x_lines_list[min(v, len(x_lines_list)-1)]
dist_xx[idx] = min(abs(pre_x - x), abs(post_x - x)) * P[idx]
dist_arr_x[j] = dist_xx
for idx, y in enumerate(Y):
v = bisect.bisect_left(y_lines_list, y)
pre_y = y_lines_list[max(v-1, 0)]
post_y = y_lines_list[min(v, len(y_lines_list) - 1)]
dist_yy[idx] = min(abs(pre_y - y), abs(post_y - y)) * P[idx]
dist_arr_y[j] = dist_yy
return dist_arr_x, dist_arr_y
def calc(val_list):
val_list = sorted(val_list)
n = len(val_list)
dp = [[INF] * (n+1) for _ in range(n+1)]
dp[0][0] = 0
for l in range(n+1):
for r in range(l+1, n+1):
next_dist = INF
for k in range(l+1, r+1):
sum = 0
for v in range(l+1, r+1):
sum += abs(val_list[v-1][0] - val_list[k-1][0]) * val_list[v-1][1]
next_dist = min(next_dist, sum)
for j in range(n):
dp[r][j + 1] = min(dp[r][j + 1], dp[l][j] + next_dist)
# 0-line
sum = 0
for v in range(l + 1, r + 1):
sum += abs(val_list[v-1][0]) * val_list[v-1][1]
next_dist = sum
for j in range(n+1):
dp[r][j] = min(dp[r][j], dp[l][j]+next_dist)
return dp
def run():
N = int(sysread())
X, Y = [], []
for i in range(1, N+1):
x,y,p = map(int, sysread().split())
X.append((x, p))
Y.append((y, p))
ans = [INF] * (N + 1)
for i in range(1 << N):# x-y-directions
x_town_list = []
y_town_list = []
for k in range(N):
if i >> k & 1:
x_town_list.append(X[k])
else:
y_town_list.append(Y[k])
#print('x', x_town_list)
#print('y', y_town_list)
dp_x = calc(x_town_list)[-1]
dp_y = calc(y_town_list)[-1]
#print(calc(x_town_list))
#print(calc(y_town_list), '\n')
#print(bin(i))
#print(dist_towns_x)
#print(dist_towns_y)
for i in range(len(dp_x)):
for j in range(len(dp_y)):
val = dp_x[i] + dp_y[j]
ans[i + j] = min(ans[i + j], val)
for a in ans:
print(a)
if __name__ == "__main__":
run()
``` | output | 1 | 36,639 | 1 | 73,279 |
Provide a correct Python 3 solution for this coding contest problem.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0 | instruction | 0 | 36,640 | 1 | 73,280 |
"Correct Solution:
```
import sys
n, *towns = map(int, sys.stdin.buffer.read().split())
xxx = towns[0::3]
yyy = towns[1::3]
ppp = towns[2::3]
INF = 10 ** 18
ans = [INF] * (n + 1)
precalc_dist_x = []
precalc_dist_y = []
for bit in range(1 << n):
dists_x = []
dists_y = []
for i in range(n):
x = xxx[i]
y = yyy[i]
dist_x = abs(x)
dist_y = abs(y)
t = bit
j = 0
while t:
if t & 1:
dist_x = min(dist_x, abs(xxx[j] - x))
dist_y = min(dist_y, abs(yyy[j] - y))
t >>= 1
j += 1
dists_x.append(dist_x * ppp[i])
dists_y.append(dist_y * ppp[i])
precalc_dist_x.append(dists_x)
precalc_dist_y.append(dists_y)
for bit in range(1 << n):
k = (bit & 0x5555) + (bit >> 1 & 0x5555)
k = (k & 0x3333) + (k >> 2 & 0x3333)
k = (k & 0x0f0f) + (k >> 4 & 0x0f0f)
k = (k & 0x00ff) + (k >> 8 & 0x00ff)
vertical = bit
while vertical:
cost = 0
pcx = precalc_dist_x[vertical]
pcy = precalc_dist_y[vertical ^ bit]
for i in range(n):
cost += min(pcx[i], pcy[i])
ans[k] = min(ans[k], cost)
vertical = (vertical - 1) & bit
cost = 0
pcx = precalc_dist_x[0]
pcy = precalc_dist_y[bit]
for i in range(n):
cost += min(pcx[i], pcy[i])
ans[k] = min(ans[k], cost)
print('\n'.join(map(str, ans)))
``` | output | 1 | 36,640 | 1 | 73,281 |
Provide a correct Python 3 solution for this coding contest problem.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0 | instruction | 0 | 36,641 | 1 | 73,282 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
INF = 10**13
def main():
N = int(input())
T = [[int(i) for i in input().split()] for j in range(N)]
X_dist = [[0]*N for _ in range(1 << N)]
Y_dist = [[0]*N for _ in range(1 << N)]
for bit in range(1 << N):
cur_x = [0]
cur_y = [0]
for i in range(N):
if bit & (1 << i):
cur_x.append(T[i][0])
cur_y.append(T[i][1])
for i, (x, y, p) in enumerate(T):
X_dist[bit][i] = p*min(abs(cx - x) for cx in cur_x)
Y_dist[bit][i] = p*min(abs(cy - y) for cy in cur_y)
answer = [INF] * (N+1)
count = 0
for i in range(1 << N):
cnt = bin(i).count("1")
j = i
while j >= 0:
j &= i
cost = 0
for k in range(N):
count += 1
if not((i >> k) & 1):
cost += min(X_dist[j][k], Y_dist[i - j][k])
answer[cnt] = min(answer[cnt], cost)
j -= 1
for ans in answer:
print(ans)
if __name__ == '__main__':
main()
``` | output | 1 | 36,641 | 1 | 73,283 |
Provide a correct Python 3 solution for this coding contest problem.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0 | instruction | 0 | 36,642 | 1 | 73,284 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
N=int(input())
P=[list(map(int,input().split())) for i in range(N)]
ANS=[1<<60]*(N+1)
ANS[-1]=0
DP1=[20000]*N
S=0
for i in range(N):
x,y,p=P[i]
DP1[i]=min(abs(x),abs(y))
S+=DP1[i]*p
ANS[0]=S
def dfs(DP,now,used):
if used==N-1:
return
for next_town in range(now,N):
x,y,p=P[next_town]
DP2=list(DP)
S=0
for i in range(N):
DP2[i]=min(DP2[i],abs(P[i][0]-x))
S+=DP2[i]*P[i][2]
#print(DP,now,used,next_town,DP2)
ANS[used+1]=min(ANS[used+1],S)
if S!=0:
dfs(DP2,next_town+1,used+1)
DP2=list(DP)
S=0
for i in range(N):
DP2[i]=min(DP2[i],abs(P[i][1]-y))
S+=DP2[i]*P[i][2]
#print(DP,now,used,next_town,DP2)
ANS[used+1]=min(ANS[used+1],S)
if S!=0:
dfs(DP2,next_town+1,used+1)
dfs(DP1,0,0)
for i in range(1,N):
ANS[i]=min(ANS[i],ANS[i-1])
print(*ANS)
``` | output | 1 | 36,642 | 1 | 73,285 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0
Submitted Solution:
```
n = int(input())
XYP = [tuple(map(int, input().split())) for i in range(n)]
X = [x for x, y, p in XYP]
Y = [y for x, y, p in XYP]
P = [p for x, y, p in XYP]
pow2 = [2**i for i in range(n + 1)]
DX = [[0] * n for s in range(pow2[n])]
DY = [[0] * n for s in range(pow2[n])]
for s in range(1 << n):
for i in range(n):
DX[s][i] = abs(X[i]) * P[i]
DY[s][i] = abs(Y[i]) * P[i]
for j in range(n):
if s & (1 << j):
DX[s][i] = min(DX[s][i], abs(X[i] - X[j]) * P[i])
DY[s][i] = min(DY[s][i], abs(Y[i] - Y[j]) * P[i])
BC = [bin(s).count("1") for s in range(pow2[n])]
A = [10**20] * (n + 1)
for sx in range(pow2[n]):
rx = (pow2[n] - 1) ^ sx
sy = rx
for _ in range(pow2[n - BC[sx]]):
sy = (sy - 1) & rx
d = 0
for i in range(n):
d += min(DX[sx][i], DY[sy][i])
c = BC[sx] + BC[sy]
A[c] = min(A[c], d)
print(*A, sep="\n")
``` | instruction | 0 | 36,643 | 1 | 73,286 |
Yes | output | 1 | 36,643 | 1 | 73,287 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0
Submitted Solution:
```
import sys
input = sys.stdin.readline
N=int(input())
P=[list(map(int,input().split())) for i in range(N)]
ANS=[1<<60]*(N+1)
ANS[-1]=0
DP1=[20000]*N
S=0
for i in range(N):
x,y,p=P[i]
DP1[i]=min(abs(x),abs(y))
S+=DP1[i]*p
ANS[0]=S
def dfs(DP,now,used):
for next_town in range(now,N):
x,y,p=P[next_town]
DP2=list(DP)
S=0
for i in range(N):
DP2[i]=min(DP2[i],abs(P[i][0]-x))
S+=DP2[i]*P[i][2]
ANS[used+1]=min(ANS[used+1],S)
dfs(DP2,next_town+1,used+1)
DP2=list(DP)
S=0
for i in range(N):
DP2[i]=min(DP2[i],abs(P[i][1]-y))
S+=DP2[i]*P[i][2]
ANS[used+1]=min(ANS[used+1],S)
dfs(DP2,next_town+1,used+1)
dfs(DP1,0,0)
for i in range(1,N):
ANS[i]=min(ANS[i],ANS[i-1])
print(*ANS)
``` | instruction | 0 | 36,644 | 1 | 73,288 |
Yes | output | 1 | 36,644 | 1 | 73,289 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0
Submitted Solution:
```
N = int(input())
X = []
Y = []
P = []
for _ in range(N):
x, y, p = map(int, input().split())
X.append(x)
Y.append(y)
P.append(p)
DX = [[0] * (1 << N) for _ in range(N)]
DY = [[0] * (1 << N) for _ in range(N)]
for i, x in enumerate(X):
for k in range(1 << N):
d = abs(x)
for j, xx in enumerate(X):
if k & (1 << j):
d = min(d, abs(xx - x))
DX[i][k] = d * P[i]
for i, y in enumerate(Y):
for k in range(1 << N):
d = abs(y)
for j, yy in enumerate(Y):
if k & (1 << j):
d = min(d, abs(yy - y))
DY[i][k] = d * P[i]
ANS = [1 << 100] * (N + 1)
PC = [0] * (1 << N)
for i in range(1, 1 << N):
j = i ^ (i & (-i))
PC[i] = PC[j] + 1
RA = []
for i in range(1 << N):
t = []
for j in range(N):
if i & (1 << j):
t.append(j)
RA.append(tuple(t))
mm = (1 << N) - 1
for i in range(1 << N):
m = i ^ mm
j = m
while 1:
ans = 0
for k in RA[i^j^mm]:
ans += min(DX[k][i], DY[k][j])
pc = PC[i] + PC[j]
ANS[pc] = min(ANS[pc], ans)
if not j:
break
j = m & (j - 1)
print(*ANS, sep = "\n")
``` | instruction | 0 | 36,645 | 1 | 73,290 |
Yes | output | 1 | 36,645 | 1 | 73,291 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0
Submitted Solution:
```
import sys
N = int(input())
XYP = [list(map(int, input().split())) for _ in range(N)]
bits = 1 << N
xmemo = [sys.maxsize]*(N*bits)
ymemo = [sys.maxsize]*(N*bits)
for b in range(bits):
for i in range(N):
xmemo[b*N+i] = min(XYP[i][2]*abs(XYP[i][0]), xmemo[b*N+i])
ymemo[b*N+i] = min(XYP[i][2]*abs(XYP[i][1]), ymemo[b*N+i])
if not (b & (1<<i)):
continue
for j in range(N):
xmemo[b*N+j] = min(XYP[j][2]*abs(XYP[i][0]-XYP[j][0]), xmemo[b*N+j])
ymemo[b*N+j] = min(XYP[j][2]*abs(XYP[i][1]-XYP[j][1]), ymemo[b*N+j])
ans = [sys.maxsize]*(N+1)
for b in range(bits):
b_ = b
cnt = bin(b_).count('1')
while b_ >= 0:
b_ &= b
yi = b - b_
tmp = 0
for i in range(N):
tmp += min(xmemo[b_*N+i], ymemo[yi*N+i])
ans[cnt] = min(ans[cnt], tmp)
b_ -= 1
for i in range(N+1):
print(ans[i])
``` | instruction | 0 | 36,646 | 1 | 73,292 |
Yes | output | 1 | 36,646 | 1 | 73,293 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0
Submitted Solution:
```
from collections import defaultdict
from collections import deque
def solve(n, XYP):
def convert(x, n=2, k=0):
A = deque()
while x:
x, r = divmod(x, n)
A.appendleft(r)
return ''.join(map(str, A)).zfill(k)
def preprocess(n, XYP):
d_x = {}
d_y = {}
for i in range(2**n):
X, Y = [0], [0]
for j, (x, y, p) in enumerate(XYP):
if (i>>j) & 1:
X.append(x)
Y.append(y)
Z, W = [], []
for x, y, p in XYP:
Z.append(min(abs(x-x_) for x_ in X) * p)
W.append(min(abs(y-y_) for y_ in Y) * p)
d_x[str(X)] = Z
d_y[str(Y)] = W
return d_x, d_y
d_x, d_y = preprocess(n, XYP)
A = defaultdict(lambda:1<<64)
for i in range(3**n):
S = list(bin(i))
c = 0
X, Y = [0], [0]
# for s, (x, y, p) in zip(S, XYP):
# if s == 1:
# X.append(x)
# c += 1
# elif s == 2:
# Y.append(y)
# c += 1
# s = sum(min(d_x[str(X)][j], d_y[str(Y)][j]) for j in range(n))
# if A[c] > s:
# A[c] = s
# for i in range(n+1):
# print(A[i])
n, *XYP = map(int, open(0).read().split())
XYP = list(zip(XYP[::3], XYP[1::3], XYP[2::3]))
solve(n, XYP)
``` | instruction | 0 | 36,647 | 1 | 73,294 |
No | output | 1 | 36,647 | 1 | 73,295 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0
Submitted Solution:
```
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
INF = 1 << 50
def generate_dist_arr(X, Y, P):
N = len(X)
dist_arr_x = [[] for _ in range(1<<N)]
dist_arr_y = [[] for _ in range(1<<N)]
for j in range(1 << N): # x-y-lines
x_lines_list = [0]
y_lines_list = [0]
for k in range(N):
if j >> k & 1:
x_lines_list.append(X[k])
y_lines_list.append(Y[k])
dist_xx, dist_yy = [INF] * N, [INF] * N
x_lines_list = sorted(x_lines_list)
y_lines_list = sorted(y_lines_list)
for idx, x in enumerate(X):
v = bisect.bisect_left(x_lines_list, x)
pre_x = x_lines_list[min(v, len(x_lines_list)-1)]
post_x = x_lines_list[min(v+1, len(x_lines_list)-1)]
dist_xx[idx] = min(abs(pre_x - x), abs(post_x - x)) * P[idx]
dist_arr_x[j] = dist_xx
for idx, y in enumerate(Y):
v = bisect.bisect_left(y_lines_list, y)
pre_y = y_lines_list[min(v, len(y_lines_list) - 1)]
post_y = y_lines_list[min(v + 1, len(y_lines_list) - 1)]
dist_yy[idx] = min(abs(pre_y - y), abs(post_y - y)) * P[idx]
dist_arr_y[j] = dist_yy
return dist_arr_x, dist_arr_y
def run():
N = int(sysread())
X, Y, P = [], [], []
ans = [INF] * N
for i in range(1, N+1):
x,y,p = map(int, sysread().split())
X.append(x)
Y.append(y)
P.append(p)
ans = [INF] * (N + 1)
dist_arr_x , dist_arr_y = generate_dist_arr(X,Y,P)
for i in range(1 << N):# x-y-directions
dist_towns_x = [INF] * (N + 1)
dist_towns_y = [INF] * (N + 1)
x_town_list = []
y_town_list = []
for k in range(N):
if i >> k & 1:
x_town_list.append(k)
else:
y_town_list.append(k)
for j in range(1 << N): # x-lines
x_lines_list = [0]
for k in range(N):
if j >> k & 1:
x_lines_list.append(X[k])
dists_base = dist_arr_x[j]
dist_ = []
for k in x_town_list:
dist_.append(dists_base[k])
tmp = len(x_lines_list)-1
dist_towns_x[tmp] = min(sum(dist_), dist_towns_x[tmp])
for j in range(1 << N): # y-lines
y_lines_list = [0]
for k in range(N):
if j >> k & 1:
y_lines_list.append(Y[k])
dists_base = dist_arr_y[j]
dist_ = []
for k in y_town_list:
dist_.append(dists_base[k])
tmp = len(y_lines_list) - 1
dist_towns_y[tmp] = min(sum(dist_), dist_towns_y[tmp])
#print(bin(i))
#print(dist_towns_x)
#print(dist_towns_y)
for i in range(N + 1):
for j in range(N + 1 - i):
val = dist_towns_x[i] + dist_towns_y[j]
ans[i + j] = min(ans[i + j], val)
for a in ans:
print(a)
if __name__ == "__main__":
run()
``` | instruction | 0 | 36,648 | 1 | 73,296 |
No | output | 1 | 36,648 | 1 | 73,297 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0
Submitted Solution:
```
import sys
input = sys.stdin.readline
import numpy as np
from numba import njit
def read():
N = int(input().strip())
XYP = np.empty((N, 3), dtype=np.int32)
for i in range(N):
XYP[i] = np.fromstring(input().strip(), sep=" ")
return N, XYP
@njit
def solve(N, XYP, INF=10**18):
ans = np.full(N+1, INF, dtype=np.int64)
vcost = np.zeros((N, 2**N), dtype=np.int32)
hcost = np.zeros((N, 2**N), dtype=np.int32)
# check 2**N pairs
for intptn in range(2**N):
for i in range(N):
xi, yi, pi = XYP[i]
v = abs(xi)
h = abs(yi)
for j in range(N):
xj, yj, pj = XYP[j]
if (intptn >> j) & 1 == 1:
v = min(v, abs(xj-xi))
h = min(h, abs(yj-yi))
vcost[i, intptn] += v
hcost[i, intptn] += h
# check 3**N pairs
for intptn in range(3**N):
# split into two 2**N pairs
p, intvptn, inthptn = intptn, 0, 0
u = 0
for i in range(N):
if p % 3 == 1:
intvptn += 1 << (N-i-1)
u += 1
elif p % 3 == 2:
inthptn += 1 << (N-i-1)
u += 1
p //= 3
s = 0
for i in range(N):
s += min(vcost[i, intvptn], hcost[i, inthptn]) * XYP[i, 2]
ans[u] = min(ans[u], s)
return ans
if __name__ == '__main__':
inputs = read()
ans = solve(*inputs)
for a in ans:
print(a)
``` | instruction | 0 | 36,649 | 1 | 73,298 |
No | output | 1 | 36,649 | 1 | 73,299 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.
There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.
The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.
Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.
For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?
Constraints
* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N
Output
Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.
Examples
Input
3
1 2 300
3 3 600
1 4 800
Output
2900
900
0
0
Input
5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
Output
13800
1600
0
0
0
0
Input
6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
Output
26700
13900
3200
1200
0
0
0
Input
8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
Output
2576709
1569381
868031
605676
366338
141903
0
0
0
Submitted Solution:
```
import numpy as np
import sys
n = int(input())
inp = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=' ')
xxx = inp[0::3]
yyy = inp[1::3]
ppp = inp[2::3]
ans = [10 ** 18]*(n+1)
default_dist = np.minimum(np.abs(xxx), np.abs(yyy))
# どの点に線を引くか全探索
for bit in range(1 << n):
k = (bit & 0x5555) + (bit >> 1 & 0x5555)
k = (k & 0x3333) + (k >> 2 & 0x3333)
k = (k & 0x0f0f) + (k >> 4 & 0x0f0f)
k = (k & 0x00ff) + (k >> 8 & 0x00ff)
i = 0
cur = 0
t = bit
# selected: 選択する点のidを格納
selected = np.zeros(k, dtype=np.int)
# is_selected: bit
is_selected = np.zeros(n, dtype=np.int)
while t:
if t & 1:
selected[cur] = i
is_selected[i] = 1
cur += 1
t >>= 1
i += 1
# 引くと決めた座標にタテヨコどちらを引くか全探索
for bit2 in range(1 << k):
cost = 0
for i in range(n):
if is_selected[i]:
continue
town_dist = default_dist[i]
t = bit2
for j in range(k):
if t & 1:
town_dist = min(town_dist, abs(yyy[selected[j]] - yyy[i]))
else:
town_dist = min(town_dist, abs(xxx[selected[j]] - xxx[i]))
t >>= 1
cost += town_dist * ppp[i]
ans[k] = min(ans[k], cost)
print('\n'.join(map(str, ans)))
``` | instruction | 0 | 36,650 | 1 | 73,300 |
No | output | 1 | 36,650 | 1 | 73,301 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Greg the Dwarf has been really busy recently with excavations by the Neverland Mountain. However for the well-known reasons (as you probably remember he is a very unusual dwarf and he cannot stand sunlight) Greg can only excavate at night. And in the morning he should be in his crypt before the first sun ray strikes. That's why he wants to find the shortest route from the excavation point to his crypt. Greg has recollected how the Codeforces participants successfully solved the problem of transporting his coffin to a crypt. So, in some miraculous way Greg appeared in your bedroom and asks you to help him in a highly persuasive manner. As usual, you didn't feel like turning him down.
After some thought, you formalized the task as follows: as the Neverland mountain has a regular shape and ends with a rather sharp peak, it can be represented as a cone whose base radius equals r and whose height equals h. The graveyard where Greg is busy excavating and his crypt can be represented by two points on the cone's surface. All you've got to do is find the distance between points on the cone's surface.
The task is complicated by the fact that the mountain's base on the ground level and even everything below the mountain has been dug through by gnome (one may wonder whether they've been looking for the same stuff as Greg...). So, one can consider the shortest way to pass not only along the side surface, but also along the cone's base (and in a specific case both points can lie on the cone's base — see the first sample test)
Greg will be satisfied with the problem solution represented as the length of the shortest path between two points — he can find his way pretty well on his own. He gave you two hours to solve the problem and the time is ticking!
Input
The first input line contains space-separated integers r and h (1 ≤ r, h ≤ 1000) — the base radius and the cone height correspondingly. The second and third lines contain coordinates of two points on the cone surface, groups of three space-separated real numbers. The coordinates of the points are given in the systems of coordinates where the origin of coordinates is located in the centre of the cone's base and its rotation axis matches the OZ axis. In this coordinate system the vertex of the cone is located at the point (0, 0, h), the base of the cone is a circle whose center is at the point (0, 0, 0), lying on the XOY plane, and all points on the cone surface have a non-negative coordinate z. It is guaranteed that the distances from the points to the cone surface do not exceed 10 - 12. All real numbers in the input have no more than 16 digits after decimal point.
Output
Print the length of the shortest path between the points given in the input, with absolute or relative error not exceeding 10 - 6.
Examples
Input
2 2
1.0 0.0 0.0
-1.0 0.0 0.0
Output
2.000000000
Input
2 2
1.0 0.0 0.0
1.0 0.0 1.0
Output
2.414213562
Input
2 2
1.0 0.0 1.0
-1.0 0.0 1.0
Output
2.534324263
Input
2 2
1.0 0.0 0.0
0.0 1.0 1.0
Output
3.254470198 | instruction | 0 | 37,028 | 1 | 74,056 |
Tags: geometry
Correct Solution:
```
import math
mas = list(map(int, input().split()))
r = mas[0]
h = mas[1]
l = (r ** 2 + h ** 2) ** 0.5#2 * math.pi * r
mas = list(map(float, input().split()))
x1 = mas[0]
y1 = mas[1]
z1 = mas[2]
mas = list(map(float, input().split()))
x2 = mas[0]
y2 = mas[1]
z2 = mas[2]
s = 0
if ((z1 == 0) and (z2 == 0)):
s = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
elif ((z1 != 0) and (z2 != 0)):
if ((x1 ** 2 + y1 ** 2 == 0) or (x2 ** 2 + y2 ** 2 == 0)):
alf = 0
else:
alf = math.acos((x1 * x2 + y1 * y2) / math.sqrt((x1 ** 2 + y1 ** 2) * (x2 ** 2 + y2 ** 2)))
l1 = l * (1 - z1 / h)
l2 = l * (1 - z2 / h)
xx1 = l1; yy1 = 0;
xx1_ = l1 * math.cos(2 * math.pi * r / l); yy1_ = l1 * math.sin(2 * math.pi * r / l);
phi = alf * r / l
xx2 = l2 * math.cos(phi); yy2 = l2 * math.sin(phi)
# расстояние только по боковой поверхности
sbok = min(((xx1 - xx2) ** 2 + (yy1 - yy2) ** 2) ** 0.5, ((xx1_ - xx2) ** 2 + (yy1_ - yy2) ** 2) ** 0.5)
#print(sbok)
# расстояние через основание
step1 = 2 * math.pi
step2 = 2 * math.pi
start1 = 0
start2 = 0
smin = 1000000000000000
sbok1min = 0
sbok2min = 0
sosnmin = 0
alf1min = 0
alf2min = 0
phi1min = 0
phi2min = 0
i1min = 0
i2min = 0
for j in range(20):
k = 80
i1 = 0
for i1 in range(k + 1):
alf1 = start1 + i1 / k * step1
phi1 = alf1 * r / l
xxx1 = l * math.cos(phi1)
yyy1 = l * math.sin(phi1)
xxx1_ = r * math.cos(alf1)
yyy1_ = r * math.sin(alf1)
i2 = 0
for i2 in range(k + 1):
alf2 = start2 + i2 / k * step2
phi2 = alf2 * r / l
xxx2 = l * math.cos(phi2)
yyy2 = l * math.sin(phi2)
xxx2_ = r * math.cos(alf2)
yyy2_ = r * math.sin(alf2)
sbok1 = (min((xx1 - xxx1) ** 2 + (yy1 - yyy1) ** 2, (xx1_ - xxx1) ** 2 + (yy1_ - yyy1) ** 2)) ** 0.5
sbok2 = ((xx2 - xxx2) ** 2 + (yy2 - yyy2) ** 2) ** 0.5
sosn = ((xxx1_ - xxx2_) ** 2 + (yyy1_ - yyy2_) ** 2) ** 0.5
ss = sbok1 + sbok2 + sosn
if (ss < smin):
smin = ss
alf1min = alf1
start1min = alf1min - step1 / k
i1min = i1
alf2min = alf2
start2min = alf2min - step2 / k
i2min = i2
sbok1min = sbok1
sbok2min = sbok2
sosnmin = sosn
phi1min = phi1
phi2min = phi2
step1 = step1 / k * 2
start1 = start1min
if (start1 < 0):
start1 = 0
step2 = step2 / k * 2
start2 = start2min
if (start2 < 0):
start2 = 0
#print(smin, alf1min, alf2min, phi1min, phi2min, phi)
#print(sbok1min, sbok2min, sosnmin)
s = min(sbok, smin)
else:
if (z1 == 0):
xtemp = x2
ytemp = y2
ztemp = z2
x2 = x1
y2 = y1
z2 = z1
x1 = xtemp
y1 = ytemp
z1 = ztemp
if ((x1 ** 2 + y1 ** 2 == 0) or (x2 ** 2 + y2 ** 2 == 0)):
alf = 0
else:
alf = math.acos((x1 * x2 + y1 * y2) / math.sqrt((x1 ** 2 + y1 ** 2) * (x2 ** 2 + y2 ** 2)))
l1 = l * (1 - z1 / h)
xx1 = l1; yy1 = 0;
xx1_ = l1 * math.cos(2 * math.pi * r / l); yy1_ = l1 * math.sin(2 * math.pi * r / l);
step1 = 2 * math.pi
start1 = 0
smin = 1000000000000000
sbok1min = 0
alf1min = 0
phi1min = 0
i1min = 0
for j in range(30):
k = 1000
i1 = 0
for i1 in range(k + 1):
alf1 = start1 + i1 / k * step1
phi1 = alf1 * r / l
xxx1 = l * math.cos(phi1)
yyy1 = l * math.sin(phi1)
xxx1_ = r * math.cos(alf1)
yyy1_ = r * math.sin(alf1)
sbok1 = (min((xx1 - xxx1) ** 2 + (yy1 - yyy1) ** 2, (xx1_ - xxx1) ** 2 + (yy1_ - yyy1) ** 2)) ** 0.5
rosn = (x2 ** 2 + y2 ** 2) ** 0.5
xosn = rosn * math.cos(alf)
yosn = rosn * math.sin(alf)
sosn = ((xxx1_ - xosn) ** 2 + (yyy1_ - yosn) ** 2) ** 0.5
ss = sbok1 + sosn
if (ss < smin):
smin = ss
alf1min = alf1
start1min = alf1min - step1 / k
i1min = i1
sbok1min = sbok1
sosnmin = sosn
phi1min = phi1
step1 = step1 / k * 2
start1 = start1min
if (start1 < 0):
start1 = 0
s = smin
print(s)
``` | output | 1 | 37,028 | 1 | 74,057 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0 | instruction | 0 | 37,119 | 1 | 74,238 |
Tags: graphs
Correct Solution:
```
def find_next_path(matrix, n, path, ind):
for i in range(n):
if matrix[ind][i] != 0 and i not in path or \
matrix[i][ind] != 0 and i not in path:
return i
return -1
n = int(input())
matrix = [[0] * n for i in range(n)]
for i in range(n):
a, b, price = [int(item) for item in input().split()]
matrix[a - 1][b - 1] = price
path = [0]
ind = find_next_path(matrix, n, path, 0)
while ind != -1:
path.append(ind)
ind = find_next_path(matrix, n, path, path[len(path) - 1])
cw = matrix[path[n - 1]][0]
acw = matrix[0][path[n - 1]]
i, j = 0, n - 1
while i < n - 1:
cw += matrix[path[i]][path[i + 1]]
acw += matrix[path[j]][path[j - 1]]
i += 1
j -= 1
print(cw if cw < acw else acw)
``` | output | 1 | 37,119 | 1 | 74,239 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0 | instruction | 0 | 37,120 | 1 | 74,240 |
Tags: graphs
Correct Solution:
```
A = set()
B = set()
cost1 = 0
cost2 = 0
def swap(a,b):
a,b = b,a
return a,b
n = int(input())
for i in range(n):
a,b,c = map(int,input().split())
if (a in A) or (b in B):
a,b = swap(a,b)
cost1 += c
else:
cost2 += c
A.add(a)
B.add(b)
print(min(cost1,cost2))
``` | output | 1 | 37,120 | 1 | 74,241 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0 | instruction | 0 | 37,121 | 1 | 74,242 |
Tags: graphs
Correct Solution:
```
n=int(input())
d=[[] for i in range(n+1)]
for i in range(n):
a,b,c=map(int,input().split())
d[a].append([b,1,c])
d[b].append([a,-1,c])
s=[1]
v=[0]*(n+1)
r=0
x=0
while(s):
m=s.pop()
v[m]=1
if v[d[m][0][0]]==1 and v[d[m][1][0]]==1:
pass
elif v[d[m][0][0]]==0:
s.append(d[m][0][0])
if d[m][0][1]==-1:
r+=d[m][0][2]
else:
x+=d[m][0][2]
elif v[d[m][1][0]] == 0:
s.append(d[m][1][0])
if d[m][1][1] == -1:
r += d[m][1][2]
else:
x+=d[m][1][2]
if d[m][0][0]==1:
if d[m][0][1] == -1:
r += d[m][0][2]
else:
x += d[m][0][2]
else:
if d[m][1][1] == -1:
r += d[m][1][2]
else:
x += d[m][1][2]
print(min(r,x))
``` | output | 1 | 37,121 | 1 | 74,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0 | instruction | 0 | 37,122 | 1 | 74,244 |
Tags: graphs
Correct Solution:
```
n = int(input())
ar=[]
br=[]
x=y=0
for i in range(n):
a,b,c=map(int,input().split())
if (a in ar or b in br):
a,b=b,a
y+=c
x+=c
ar.append(a)
br.append(b)
print(min(y,x-y))
``` | output | 1 | 37,122 | 1 | 74,245 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0 | instruction | 0 | 37,123 | 1 | 74,246 |
Tags: graphs
Correct Solution:
```
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
#def input(): return sys.stdin.readline().strip()
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
ilelec = lambda: map(int1,input().split())
alelec = lambda: list(map(int1, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
N = int(input())
A = []
cost = {}
for i in range(N):
a,b,c = ilele()
cost[(b,a)] = c
A.append((a,b))
B = [*A[0]]
del A[0]
i = 1
while True:
f = 0
for j in range(len(A)):
if A[j][0] == B[i]:
B.append(A[j][1])
i+=1;f = 1
del A[j]
break
elif A[j][1] == B[i]:
B.append(A[j][0])
i+=1;f = 1
del A[j]
break
if not f:
break
#print(B)
ans1 = 0;ans2 = 0
for i in range(1,len(B)):
ans1 += cost.get((B[i],B[i-1]),0)
ans2 += cost.get((B[i-1],B[i]),0)
print(min(ans1,ans2))
``` | output | 1 | 37,123 | 1 | 74,247 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0 | instruction | 0 | 37,124 | 1 | 74,248 |
Tags: graphs
Correct Solution:
```
n = int(input())
p = [tuple(map(int, input().split())) for i in range(n)]
t = [[] for i in range(n + 1)]
for a, b, c in p:
t[a].append(b)
t[b].append(a)
t[1], x = t[1][0], 1
for i in range(1, n):
y = t[x]
t[y], x = t[y][t[y][0] == x], y
t[x] = 1
s = d = 0
for a, b, c in p:
if t[a] == b: d += c
s += c
print(min(d, s - d))
``` | output | 1 | 37,124 | 1 | 74,249 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0 | instruction | 0 | 37,125 | 1 | 74,250 |
Tags: graphs
Correct Solution:
```
dic,tcost,ncost = {}, 0,0
for line in range(int(input())):
a,b,c = list(map(int, input().split(" ")))
if a not in dic:
dic[a] = {b: 0}
else: dic[a][b] = 0
if b not in dic:
dic[b] = {a: c}
else: dic[b][a] = c
tcost +=c
curr = b
prev = a
next = None
while curr != a:
for x in dic[curr].keys()-[prev]: next = x
ncost += dic[curr][next]
prev, curr = curr,next
if ncost < tcost/2:
print(ncost)
else: print(tcost - ncost)
``` | output | 1 | 37,125 | 1 | 74,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0 | instruction | 0 | 37,126 | 1 | 74,252 |
Tags: graphs
Correct Solution:
```
n = int(input())
p,c,ss = [[] for _ in range(n+1)],[[0]*(n+1) for _ in range(n+1)], 0
for x,y,z in [map(int,input().split()) for _ in range(n)]:
p[x].append(y),p[y].append(x)
c[x][y],ss= z,ss+z
tmp ,vis,cir = 1,[0 for _ in range(n+1)],[]
while 1:
ok = 0
cir.append(tmp)
vis[tmp] = 1
if not vis[p[tmp][0]] :tmp,ok = p[tmp][0],1
elif not vis[p[tmp][1]]: tmp,ok = p[tmp][1],1
if not ok : break
ns = sum(c[cir[i]][cir[i+1]] for i in range(-1,n-1))
print(min(ns,ss-ns))
``` | output | 1 | 37,126 | 1 | 74,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0
Submitted Solution:
```
amount = int(input())
array = [[] for i in range(amount)]
used = [0] * amount
cs = []
for i in range(amount):
a,b,c = [int(s) for s in input().split()]
a -= 1
b -= 1
if not b in array[a]:
array[a].append(b)
if not a in array[b]:
array[b].append(a)
cs.append((a,b,c))
path = [0]
used[0] = 1
curr = path[-1]
#print(array)
while len(path) != amount:
for i in range(len(array[curr])):
if not used[array[curr][i]]:
path.append(array[curr][i])
used[array[curr][i]] = 1
curr = path[-1]
break
counter_1 = 0
counter_2 = 0
for i in range(len(path) - 1):
for j in range(len(cs)):
if path[i] == cs[j][1] and path[i + 1] == cs[j][0]:
counter_1 += cs[j][2]
for j in range(len(cs)):
if path[-1] == cs[j][1] and path[0] == cs[j][0]:
counter_1 += cs[j][2]
sum_ = sum(elem[2] for elem in cs)
print(min(counter_1,sum_ - counter_1))
``` | instruction | 0 | 37,127 | 1 | 74,254 |
Yes | output | 1 | 37,127 | 1 | 74,255 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0
Submitted Solution:
```
n = int(input())
G = [ [0]*(n+1) for _ in range(n+1)]
circle = []
done = set()
for _ in range(n):
a,b,c = map(int,input().split())
G[a][b] = c
def dfs(x):
done.add(x)
circle.append(x)
#print(x)
for i in range(1,n+1):
if not i in done and (G[x][i] != 0 or G[i][x] != 0):
dfs(i)
dfs(1)
left=0
right=0
#print(circle,n)
circle.append(1)
for i in range(n):
right+=G[circle[i]][circle[i+1]]
circle = circle[::-1]
for i in range(n):
left+=G[circle[i]][circle[i+1]]
print(min(left,right))
``` | instruction | 0 | 37,128 | 1 | 74,256 |
Yes | output | 1 | 37,128 | 1 | 74,257 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0
Submitted Solution:
```
def count(origin,parent,check,roads,tree):
# print("parent is",parent)
if check == origin:
return 0
else:
if tree[check - 1][0] != parent:
return roads[check-1][tree[check-1][0]-1] + count(origin,check,tree[check-1][0],roads,tree)
else:
return roads[check-1][tree[check-1][1]-1] + count(origin,check,tree[check-1][1],roads,tree)
def Ring_road():
cities = int(input())
roads = [[0 for i in range(cities)] for i in range(cities)]
tree = [[] for i in range(cities)]
for i in range(cities):
start,end,cost = map(int,input().split())
roads[end-1][start-1] = cost
tree[start-1].append(end)
tree[end-1].append(start)
# print(roads)
# print(tree)
return min(roads[0][tree[0][0]-1] + count(1,1,tree[0][0],roads,tree),roads[0][tree[0][1]-1] + count(1,1,tree[0][1],roads,tree))
remaing_test_cases = 1
# remaing_test_cases = int(input())
while remaing_test_cases > 0:
print(Ring_road())
remaing_test_cases = remaing_test_cases - 1
``` | instruction | 0 | 37,129 | 1 | 74,258 |
Yes | output | 1 | 37,129 | 1 | 74,259 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0
Submitted Solution:
```
source=set()
dest=set()
c1=0
c2=0
for i in range(int(input())):
s,d,w=map(int,input().split())
if s in source or d in dest:
c1=c1+w
s,d=d,s
else:
c2=c2+w
source.add(s)
dest.add(d)
print(min(c1,c2))
``` | instruction | 0 | 37,130 | 1 | 74,260 |
Yes | output | 1 | 37,130 | 1 | 74,261 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0
Submitted Solution:
```
n = int(input())
e = [ [] for i in range(n)]
e2 = [ [] for i in range(n)]
C = 0
for i in range(n):
a,b,c = map(int,input().split())
a-=1
b-=1
e[a].append((b,c))
e[b].append((a,c))
e2[a].append(b)
C += c
col = [ -1 for i in range(n)]
col[0] = 0
od = 0
def dfs(n):
global od
for v in e[n]:
if col[v[0]] == -1:
if e2[n]:
if v[0] in e2[n] :
# print(n + 1 ,v[0] + 1)
od += v[1]
col[v[0]] = col[n] + v[1]
dfs(v[0])
elif col[v[0]] == 0 and min(col) > -1:
if e2[n]:
if v[0] in e2[n] :
# print(n + 1 ,v[0] + 1)
col[v[0]] = col[n] + v[1]
od += v[1]
dfs(0)
print(min( abs(C - od) , od))
``` | instruction | 0 | 37,131 | 1 | 74,262 |
No | output | 1 | 37,131 | 1 | 74,263 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0
Submitted Solution:
```
n = int(input())
e = [ [] for i in range(n)]
e2 = [ [] for i in range(n)]
C = 0
for i in range(n):
a,b,c = map(int,input().split())
a-=1
b-=1
e[a].append((b,c))
e[b].append((a,c))
e2[a].append(b)
C += c
col = [ -1 for i in range(n)]
col[0] = 0
od = 0
def dfs(n):
global od
for v in e[n]:
if col[v[0]] == -1:
if e2[n]:
if v[0] in e2[n] :
od += v[1]
col[v[0]] = col[n] + v[1]
dfs(v[0])
dfs(0)
if len(e2[0]) == 1:
for v in e[0]:
if e2[0][0] != v[0]:
od += v[1]
print(min( abs(C - od) , od))
``` | instruction | 0 | 37,132 | 1 | 74,264 |
No | output | 1 | 37,132 | 1 | 74,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0
Submitted Solution:
```
##Author: bushra04
##Date: 11/05/2021
##Time: 17:17:22
n=int(input())
arr,brr=[],[]
tot,y=0,0
for i in range(0,n):
a,b,c=map(int,input().split())
tot+=c
if a in arr or b in brr:
a,b=b,a
y+=c
arr.append(a)
brr.append(b)
print(min(y,tot-c))
``` | instruction | 0 | 37,133 | 1 | 74,266 |
No | output | 1 | 37,133 | 1 | 74,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0
Submitted Solution:
```
n = int(input())
e = [ [] for i in range(n)]
e2 = [ [] for i in range(n)]
C = 0
for i in range(n):
a,b,c = map(int,input().split())
a-=1
b-=1
e[a].append((b,c))
e[b].append((a,c))
e2[a].append(b)
C += c
col = [ -1 for i in range(n)]
col[0] = 0
od = 0
fisrtnode = -1
def dfs(n):
global od
global fisrtnode
for v in e[n]:
if fisrtnode == -1 :
fisrtnode = v[0]
if col[v[0]] == -1:
if e2[n]:
if v[0] in e2[n] :
# print(n + 1 ,v[0] + 1)
od += v[1]
col[v[0]] = col[n] + v[1]
dfs(v[0])
elif col[v[0]] == 0 and min(col) > -1:
if e2[n]:
if v[0] in e2[n] :
if v[0] != fisrtnode:
# print(n + 1 ,v[0] + 1)
col[v[0]] = col[n] + v[1]
od += v[1]
dfs(0)
print(min( abs(C - od) , od))
``` | instruction | 0 | 37,134 | 1 | 74,268 |
No | output | 1 | 37,134 | 1 | 74,269 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2.
Your program should handle the queries of the following two types:
1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals.
2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval?
Answer all the queries. Note, that initially you have an empty set of intervals.
Input
The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value.
It's guaranteed that all queries are correct.
Output
For each query of the second type print "YES" or "NO" on a separate line depending on the answer.
Examples
Input
5
1 1 5
1 5 11
2 1 2
1 2 9
2 1 2
Output
NO
YES | instruction | 0 | 37,154 | 1 | 74,308 |
Tags: dfs and similar, graphs
Correct Solution:
```
def main():
intervals = []
visited = []
for _ in range(int(input())):
read_input(intervals, visited)
def read_input(intervals: list, visited: list) -> None:
command, x, y = [int(x) for x in input().split(" ")]
if (command == 1):
intervals.append((x, y))
visited.append(False)
else:
# reset the visited array
for idx in range(len(visited)):
visited[idx] = False
if(find_path(intervals, visited, x-1, y-1)):
print("YES")
else:
print("NO")
def find_path(intervals: list, visited: list, start: int, end: int) -> bool:
if (start == end):
return True
else:
for x in range(len(intervals)):
if (can_move(intervals[start], intervals[x]) and not visited[x]):
visited[x] = True
if(find_path(intervals, visited, x, end)):
return True
return False
def can_move(a: tuple, b: tuple) -> bool:
if (b[0] < a[0] < b[1]):
return True
elif (b[0] < a[1] < b[1]):
return True
else:
return False
if __name__ == "__main__":
main()
``` | output | 1 | 37,154 | 1 | 74,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2.
Your program should handle the queries of the following two types:
1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals.
2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval?
Answer all the queries. Note, that initially you have an empty set of intervals.
Input
The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value.
It's guaranteed that all queries are correct.
Output
For each query of the second type print "YES" or "NO" on a separate line depending on the answer.
Examples
Input
5
1 1 5
1 5 11
2 1 2
1 2 9
2 1 2
Output
NO
YES
Submitted Solution:
```
def main():
class interval:
def __init__(self, a, b):
self.a = a
self.b = b
def travel(self, i2):
(a, b) = (self.a, self.b)
(c, d) = (i2.a, i2.b)
return (c < a and a < d) or (c < b and b < d)
def __str__(self):
return "({} {})".format(self.a, self.b)
from collections import defaultdict
adj = defaultdict(set)
vis = set()
def dfs(i, goal):
nonlocal vis
if i in vis:
return False
if i == goal:
return True
vis.add(i)
for j in intervals:
if i.a == j.a and i.b == j.b:
continue
if not i.travel(j):
continue
if j in vis:
continue
if j == goal:
return True
if dfs(j, goal):
return True
return False
intervals = []
n = int(input())
for i in range(n):
(x, a, b) = map(int, input().split(' '))
if x == 1:
intervals.append(interval(a, b))
else:
f = False
vis = set()
if dfs(intervals[a - 1], intervals[b - 1]):
print("YES")
else:
print("NO")
main()
``` | instruction | 0 | 37,157 | 1 | 74,314 |
Yes | output | 1 | 37,157 | 1 | 74,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
Input
First line contains single integer n (1 ≤ n ≤ 5000) — number of people.
Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
Output
The output should contain a single integer — maximal possible total comfort.
Examples
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
Note
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9. | instruction | 0 | 37,375 | 1 | 74,750 |
Tags: dp, implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
R, L = {}, {}
for i in range(n):
if a[i] not in L:
L[a[i]] = i
R[a[i]] = i
dp = [0] * (n + 1)
for i in range(n):
dp[i] = dp[i - 1]
if R[a[i]] != i:
continue
s = 0
l = L[a[i]]
for j in range(i, -1, -1):
if R[a[j]] <= i:
if R[a[j]] == j:
s ^= a[j]
l = min(l, L[a[j]])
if j == l:
dp[i] = max(dp[i], dp[j - 1] + s)
else:
break
print(dp[n - 1])
``` | output | 1 | 37,375 | 1 | 74,751 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
Input
First line contains single integer n (1 ≤ n ≤ 5000) — number of people.
Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
Output
The output should contain a single integer — maximal possible total comfort.
Examples
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
Note
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9. | instruction | 0 | 37,376 | 1 | 74,752 |
Tags: dp, implementation
Correct Solution:
```
#!/usr/bin/pypy3
import cProfile
from sys import stdin,stderr
from heapq import heappush,heappop
from random import randrange
def readInts(): return map(int,stdin.readline().strip().split())
def print_err(*args,**kwargs): print(*args,file=stderr,**kwargs)
def create_heap(ns):
mins = {}
maxs = {}
for i,v in enumerate(ns):
if v not in mins: mins[v] = i
maxs[v] = i
ranges = {}
rheap = []
for v,minix in mins.items():
maxix = maxs[v]
ranges[v] = (minix,maxix)
heappush(rheap,(maxix-minix+1,minix))
return (ranges,rheap)
def create_heap2(ns):
mins = {}
maxs = {}
for i,v in enumerate(ns):
if v not in mins: mins[v] = i
maxs[v] = i
ranges = {}
rheap = []
for v,minix in mins.items():
maxix = maxs[v]
ranges[v] = (minix,maxix)
heappush(rheap,(maxix-minix+1,minix,set([v])))
return (ranges,rheap)
def solve(n,ns):
ranges,pq = create_heap(ns)
resolved_ranges = {}
while pq:
w,lo_ix = heappop(pq)
#print(len(pq),w,lo_ix)
if lo_ix in resolved_ranges:
#print(len(pq))
continue
tot_subs = 0
tot_x = 0
ix = lo_ix
fail = False
xsv = set()
while ix < lo_ix+w:
v = ns[ix]
lo2,hi2 = ranges[v]
if lo2 < lo_ix or hi2 > lo_ix+w-1:
lo2 = min(lo2,lo_ix)
hi2 = max(hi2,lo_ix+w-1)
heappush(pq, (hi2-lo2+1,lo2) )
fail = True
break
if ix in resolved_ranges:
rhi_ix,c,x = resolved_ranges[ix]
tot_x ^= x
tot_subs += c
ix = rhi_ix + 1
continue
if v not in xsv:
xsv.add(v)
tot_x ^= v
ix += 1
if not fail:
resolved_ranges[lo_ix] = (lo_ix+w-1,max(tot_x,tot_subs),tot_x)
ix = 0
tot_c = 0
while ix < n:
rhi,c,_ = resolved_ranges[ix]
ix = rhi+1
tot_c += c
return tot_c
def solve2(n,ns):
ranges,pq = create_heap(ns)
resolved_ranges = {}
while pq:
w,lo_ix,xs = heappop(pq)
print(len(pq),w,lo_ix,xs)
if lo_ix in resolved_ranges:
print(len(pq))
continue
tot_subs = 0
tot_x = 0
for x in xs: tot_x ^= x
ix = lo_ix
fail = False
while ix < lo_ix+w:
v = ns[ix]
if v in xs:
ix += 1
continue
if ix in resolved_ranges:
rhi_ix,c,x = resolved_ranges[ix]
tot_x ^= x
tot_subs += c
ix = rhi_ix + 1
continue
lo2,hi2 = ranges[v]
lo2 = min(lo2,lo_ix)
hi2 = max(hi2,lo_ix+w-1)
xs.add(v)
heappush(pq, (hi2-lo2+1,lo2,xs) )
fail = True
break
if not fail:
resolved_ranges[lo_ix] = (lo_ix+w-1,max(tot_x,tot_subs),tot_x)
ix = 0
tot_c = 0
while ix < n:
rhi,c,_ = resolved_ranges[ix]
ix = rhi+1
tot_c += c
return tot_c
def test():
n = 5000
ns = []
for _ in range(n):
ns.append(randrange(1,n//2))
print(solve(n,ns))
def run():
n, = readInts()
ns = list(readInts())
print(solve(n,ns))
run()
``` | output | 1 | 37,376 | 1 | 74,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
Input
First line contains single integer n (1 ≤ n ≤ 5000) — number of people.
Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
Output
The output should contain a single integer — maximal possible total comfort.
Examples
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
Note
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9. | instruction | 0 | 37,377 | 1 | 74,754 |
Tags: dp, implementation
Correct Solution:
```
inf = 1<<30
n = int(input())
a = [0] + [int(i) for i in input().split()]
maxi = max(a)
f = [-1] * (maxi+1)
for i in range(1, n + 1):
if f[a[i]] == -1:
f[a[i]] = i
l = [-1] * (maxi+1)
for i in range(n, 0, -1):
if l[a[i]] == -1:
l[a[i]] = i
dp = [0] * (n+1)
for i in range(1, n + 1):
dp[i] = dp[i - 1]
if i == l[a[i]]:
min_l = f[a[i]]
max_r = i
vis = set()
v = 0
for j in range(i, -1, -1):
min_l = min(min_l, f[a[j]])
max_r = max(max_r, l[a[j]])
if a[j] not in vis:
v ^= a[j]
vis.add(a[j])
if max_r > i:
break
if j == min_l:
dp[i] = max(dp[i], dp[j-1] + v)
break
print(dp[n])
``` | output | 1 | 37,377 | 1 | 74,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
Input
First line contains single integer n (1 ≤ n ≤ 5000) — number of people.
Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
Output
The output should contain a single integer — maximal possible total comfort.
Examples
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
Note
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9. | instruction | 0 | 37,378 | 1 | 74,756 |
Tags: dp, implementation
Correct Solution:
```
def dp():
dparr = [0] * len(sections)
for i in range(len(sections) - 1, -1, -1):
_, curend, curcomfort = sections[i]
nextsection = i + 1
try:
while sections[nextsection][0] <= curend:
nextsection += 1
except IndexError:
# Loop til end
inc = curcomfort
else:
inc = curcomfort + dparr[nextsection]
exc = 0 if i == len(sections) - 1 else dparr[i + 1]
dparr[i] = max(inc, exc)
return dparr[0]
n = int(input())
zs = list(map(int, input().split()))
sections = []
seenstartz = set()
first = {z: i for i, z in reversed(list(enumerate(zs)))}
last = {z: i for i, z in enumerate(zs)}
for start, z in enumerate(zs):
if z in seenstartz:
continue
seenstartz.add(z)
end = last[z]
comfort = 0
i = start
while i <= end:
if first[zs[i]] < start:
break
if i == last[zs[i]]:
comfort ^= zs[i]
end = max(end, last[zs[i]])
i += 1
else:
sections.append((start, end, comfort))
ans = dp()
print(ans)
``` | output | 1 | 37,378 | 1 | 74,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
Input
First line contains single integer n (1 ≤ n ≤ 5000) — number of people.
Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
Output
The output should contain a single integer — maximal possible total comfort.
Examples
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
Note
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9. | instruction | 0 | 37,379 | 1 | 74,758 |
Tags: dp, implementation
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
n=int(input())
b=list(map(int,input().split()))
first=dict()
last=dict()
for i in range(n):
if b[i] not in first.keys():
first[b[i]]=i+1
if b[n-i-1] not in last.keys():
last[b[n-i-1]]=n-i
dp=[[-float("inf"),-float("inf")] for i in range(n+1)]
dp[0]=[0,0]
for i in range(1,n+1):
dp[i][0]=max(dp[i-1])
tot=0
l=dict()
j=i
val=0
while(j>=1):
if last[b[j-1]]==(j):
l[b[j-1]]=1
val^=b[j-1]
tot+=1
if first[b[j - 1]] == (j):
tot += -1
if b[j-1] not in l.keys():
break
else:
if tot==0:
dp[i][1]=max(dp[i][1],max(dp[j-1])+val)
j+=-1
print(max(dp[n]))
``` | output | 1 | 37,379 | 1 | 74,759 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
Input
First line contains single integer n (1 ≤ n ≤ 5000) — number of people.
Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
Output
The output should contain a single integer — maximal possible total comfort.
Examples
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
Note
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9. | instruction | 0 | 37,380 | 1 | 74,760 |
Tags: dp, implementation
Correct Solution:
```
from collections import Counter, defaultdict
R = lambda: map(int, input().split())
n = int(input())
arr = list(R())
cnts = Counter(arr)
dp = [0] * (n + 1)
for i in range(n):
acc = defaultdict(int)
cnt, xor = 0, 0
dp[i] = dp[i - 1]
for j in range(i, -1, -1):
acc[arr[j]] += 1
if acc[arr[j]] == cnts[arr[j]]:
cnt += 1
xor = xor ^ arr[j]
if len(acc) == cnt:
dp[i] = max(dp[i], dp[j - 1] + xor)
print(dp[n - 1])
``` | output | 1 | 37,380 | 1 | 74,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
Input
First line contains single integer n (1 ≤ n ≤ 5000) — number of people.
Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
Output
The output should contain a single integer — maximal possible total comfort.
Examples
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
Note
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9. | instruction | 0 | 37,381 | 1 | 74,762 |
Tags: dp, implementation
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
lmost=[99999999]*(5001)
rmost=[-1]*(5001)
dp=[0]*(5001)
for i in range(n):
lmost[a[i]]=min(lmost[a[i]],i)
for i in range(n-1,-1,-1):
rmost[a[i]]=max(rmost[a[i]],i)
for i in range(n):
val=0
m=lmost[a[i]]
dp[i]=dp[i-1]
for j in range(i,-1,-1):
if rmost[a[j]] >i:
break
if rmost[a[j]] ==j:
val=val^a[j]
m=min(m,lmost[a[j]])
if m==j:
dp[i]=max(dp[i],dp[j-1]+val)
print(max(dp))
``` | output | 1 | 37,381 | 1 | 74,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
Input
First line contains single integer n (1 ≤ n ≤ 5000) — number of people.
Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.
Output
The output should contain a single integer — maximal possible total comfort.
Examples
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
Note
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9. | instruction | 0 | 37,382 | 1 | 74,764 |
Tags: dp, implementation
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: max(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n=int(input())
l=list(map(int,input().split()))
l=[-1]+l
dp=[0 for j in range (n+1)]
d=defaultdict(int)
d1=defaultdict(int)
for i in range(1,n+1):
d[l[i]]=max(d[l[i]],i)
if d1[l[i]]==0:
d1[l[i]]=i
for i in range(1,n+1):
mi=n+6
ma=0
tot=set()
cur=0
for j in range(i,-1,-1):
if l[j] not in tot:
cur^=l[j]
tot.add(l[j])
ma=max(ma,d[l[j]])
mi=min(mi,d1[l[j]])
if ma<=i and mi>=j:
dp[i]=max(dp[i],dp[j-1]+cur)
dp[i]=max(dp[i],dp[j])
print(dp[n])
``` | output | 1 | 37,382 | 1 | 74,765 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.