message stringlengths 2 45.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 254 108k | cluster float64 3 3 | __index_level_0__ int64 508 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3 | instruction | 0 | 48,406 | 3 | 96,812 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
input=sys.stdin.readline
from collections import deque
#sys.setrecursionlimit(10**8)
t=1
import math
def bfs(a,i,dis,vis):
vis[i]=1
pp=deque()
pp.append(i)
while len(pp)!=0:
z=pp[0]
vis[z]=1
pp.popleft()
for j in a[z]:
if vis[j]==0:
dis[j]=dis[z]+1
pp.append(j)
while t>0:
t-=1
n,m=map(int,input().split())
a=[[] for i in range(n+1)]
for i in range(m):
x,y=map(int,input().split())
a[x].append(y)
a[y].append(x)
vis=[0 for i in range(n+1)]
dis=[0 for i in range(n+1)]
bfs(a,1,dis,vis)
#print(dis)
p=[max(dis),dis.index(max(dis))]
vis=[0 for i in range(n+1)]
dis=[0 for i in range(n+1)]
bfs(a,p[1],dis,vis)
p=[max(dis),dis.index(max(dis))]
print(p[0])
``` | output | 1 | 48,406 | 3 | 96,813 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3 | instruction | 0 | 48,407 | 3 | 96,814 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
arr = list(map(int, input().split()))
n=arr[0]
m=arr[1]
graph = [[] for _ in range(n)]
graph2= [[] for _ in range(n)]
for i in range(n - 1):
inf = list(map(int, input().split()))
v1 = inf[0] - 1
v2 = inf[1] - 1
graph2[v1].append(v2)
graph2[v2].append(v1)
graph[v1].append(v2)
graph[v2].append(v1)
curr = [0,0]
stk = []
nvis = [True] * n
ans = 0
dis=0
pt=0
while(True):
nxt = -1
temp=len(graph[curr[0]])
for i in range(temp-1,-1,-1):
if (nvis[graph[curr[0]][i]]):
nxt = graph[curr[0]][i]
break
else:
graph[curr[0]].pop()
if(nxt != -1):
stk.append([curr[0],curr[1]])
nvis[curr[0]] = False
curr = [nxt,curr[1]+1]
else:
if(curr[0]==0):
break
nvis[curr[0]] = False
if(dis<curr[1]):
dis=curr[1]
pt=curr[0]
curr = stk[-1]
stk.pop(-1)
init=pt
graph=graph2
curr = [pt,0]
stk = []
nvis = [True] * n
ans = 0
dis=0
pt=0
while(True):
nxt = -1
temp=len(graph[curr[0]])
for i in range(temp-1,-1,-1):
if(nvis[graph[curr[0]][i]]):
nxt = graph[curr[0]][i]
break
else:
graph[curr[0]].pop()
if(nxt != -1):
stk.append([curr[0],curr[1]])
nvis[curr[0]] = False
curr = [nxt,curr[1]+1]
else:
if(curr[0]==init):
break
nvis[curr[0]] = False
if(dis<curr[1]):
dis=curr[1]
pt=curr[0]
curr = stk[-1]
stk.pop(-1)
print(dis)
``` | output | 1 | 48,407 | 3 | 96,815 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3 | instruction | 0 | 48,408 | 3 | 96,816 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
node = 0
ans = 0
@iterative
def dfs(s, max_cnt):
global ans
global node
vis[s] = 1
if max_cnt > ans:
node = s
ans = max(ans, max_cnt)
for i in g[s]:
if vis[i] == 0:
vis[i] = 1
ok = yield dfs(i, max_cnt + 1)
yield True
n,k=map(int, input().split())
g = [[] for i in range(n + 1)]
ans = 0
for i in range(k):
u, v = map(int, input().split())
g[u].append(v)
g[v].append(u)
vis=[0]*(n + 1)
dfs(1, 1) # dfs 1 in this second parameter does not play any role but it requied in dfs2
ans = 1 ###store maximum nodes on longest path
vis=[0]*(n + 1)
dfs(node, 1) # dfs2
print((ans - 1))
``` | output | 1 | 48,408 | 3 | 96,817 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3 | instruction | 0 | 48,409 | 3 | 96,818 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
def find_farest_v(v, g):
queue_v = [(v, 0)]
order = []
visited_v = set()
while queue_v:
current_v, dist = queue_v.pop(0)
visited_v.add(current_v)
order.append((current_v, dist))
for neib in adj_graph[current_v]:
if neib not in visited_v:
queue_v.append((neib, dist + 1))
return order[-1]
n, m = list(map(int, input().strip().split(" ")))
adj_graph = [[] for i in range(n)]
for i in range(m):
line = input()
v1, v2 = list(map(int, line.split(" ")))
adj_graph[v1 - 1].append(v2 - 1)
adj_graph[v2 - 1].append(v1 - 1)
v1, d1 = find_farest_v(0, adj_graph)
v2, d2 = find_farest_v(v1, adj_graph)
print(d2)
``` | output | 1 | 48,409 | 3 | 96,819 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3
Submitted Solution:
```
#!/usr/bin/python3
__import__("sys").setrecursionlimit(10 ** 6)
import threading
threading.stack_size(64 * 1024 * 1024)
def dfs(u, h, par, tr, arr):
arr[u] = h
for v in tr[u]:
if v != par:
dfs(v, h + 1, u, tr, arr)
def longpathv(tr, v):
n = len(tr)
arr = [0] * n
dfs(v, 0, -1, tr, arr)
ans = max(range(n), key=lambda x: arr[x])
return ans, arr[ans]
def longpath(tr):
return longpathv(tr, longpathv(tr, 0)[0])[1]
def main(tr):
print(longpath(tr))
n, m = map(int, input().split())
tr = [[] for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
tr[a].append(b)
tr[b].append(a)
th = threading.Thread(target=main, args=tuple([tr]))
th.start()
``` | instruction | 0 | 48,410 | 3 | 96,820 |
Yes | output | 1 | 48,410 | 3 | 96,821 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3
Submitted Solution:
```
import copy
import sys
import threading
threading.stack_size(64 * 1024 * 1024)
sys.setrecursionlimit(10 ** 6)
n, m = map(int, input().split())
ans = 0
sz = [0] * (n + 1)
graph = []
for _ in range(n + 1):
graph.append([])
for _ in range(m):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
def dfs(v, pr):
global ans
for to in graph[v]:
if to != pr:
dfs(to, v)
if pr != -1:
ans = max(ans, sz[pr] + sz[v])
sz[pr] = max(sz[pr], sz[v] + 1)
def main():
dfs(1, -1)
print(ans + 1)
th = threading.Thread(target=main)
th.start()
``` | instruction | 0 | 48,411 | 3 | 96,822 |
Yes | output | 1 | 48,411 | 3 | 96,823 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3
Submitted Solution:
```
n,m=list(map(int,input().split()))
from collections import defaultdict,deque
g=defaultdict(list)
for i in range(m):
a,b=list(map(int,input().split()))
g[a-1].append(b-1)
g[b-1].append(a-1)
def dfs(x):
vis[x]=1
q=deque()
q.append((x,0))
while q:
cur,d=q.popleft()
if maxd[0]<d:
maxd[0]=d
maxnode[0]=cur
for i in g[cur]:
if vis[i]==0:
q.append((i,d+1))
vis[i]=1
vis=[0]*n
maxd=[0]
maxnode=[0]
dfs(0)
vis=[0]*n
maxd=[0]
dfs(maxnode[0])
print(maxd[0])
``` | instruction | 0 | 48,412 | 3 | 96,824 |
Yes | output | 1 | 48,412 | 3 | 96,825 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3
Submitted Solution:
```
def bfs(x, g):
n, q = len(g), [x]
dist = [0 if y == x else -1 for y in range(n)]
i = 0
while i < len(q):
v = q[i]
i += 1
for to in g[v]:
if dist[to] < 0:
dist[to] = dist[v] + 1
q.append(to)
return (q[-1], dist[q[-1]])
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
a, b = map(lambda x: int(x) - 1, input().split())
g[a].append(b)
g[b].append(a)
print(bfs(bfs(0, g)[0], g)[1])
``` | instruction | 0 | 48,413 | 3 | 96,826 |
Yes | output | 1 | 48,413 | 3 | 96,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3
Submitted Solution:
```
import sys
#with open(filename, 'r') as f:
with sys.stdin as f:
for i, line in enumerate(f):
if i == 0:
N, M = line.split(' ')
N, M = int(N), int(M)
graph = [[] for _ in range(N)] # [[]] * N not working, no deepcopy
else:
fromVertex, toVertex = line.split(' ')
fromVertex, toVertex = int(fromVertex)-1, int(toVertex)-1
graph[fromVertex].append(toVertex)
graph[toVertex].append(fromVertex)
# code is too slow, O(N^3)
#~ INFINITY = 9999999
#~ from queue import LifoQueue
#~ def bfs(start_node, graph):
#~ N = len(graph)
#~ distances = [INFINITY for _ in range(N)]
#~ distances[start_node] = 0
#~ nodes_queue = LifoQueue()
#~ nodes_queue.put(start_node)
#~ while not nodes_queue.empty():
#~ node = nodes_queue.get()
#~ for neigh in graph[node]:
#~ if distances[neigh] == INFINITY:
#~ # not yet visited
#~ distances[neigh] = distances[node] + 1
#~ nodes_queue.put(neigh)
#~ return distances
# use tree structure
from queue import LifoQueue
def farthest_node_distance(start_node, graph):
""" returns farthest node from start node and its distance """
N = len(graph)
visited = [False for _ in range(N)]
distances = [-1 for _ in range(N)]
visited[start_node] = True
distances[start_node] = 0
nodes_queue = LifoQueue()
nodes_queue.put(start_node)
while not nodes_queue.empty():
node = nodes_queue.get()
for neigh in graph[node]:
if not visited[neigh]:
visited[neigh] = True
distances[neigh] = distances[node] + 1
nodes_queue.put(neigh)
return node, distances[node]
u, dist_u = farthest_node_distance(0, graph)
v, dist_uv = farthest_node_distance(u, graph)
print(dist_uv)
``` | instruction | 0 | 48,414 | 3 | 96,828 |
No | output | 1 | 48,414 | 3 | 96,829 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3
Submitted Solution:
```
# itne me hi thakk gaye?
from collections import defaultdict
n, m = map(int, input().split())
graph = defaultdict(list)
for i in range(m):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
leaves = []
for i in graph:
if len(graph[i]) == 1:
leaves.append(i)
maxi = -1
visited = [False for z in range(n+1)]
q = [(leaves[0], 0)]
visited[leaves[0]] = True
while q!=[]:
node, dist = q[0]
maxi = max(maxi, dist)
q.pop(0)
for child in graph[node]:
if visited[child] is False:
visited[child] = True
q.append((child, dist+1))
print(maxi)
``` | instruction | 0 | 48,415 | 3 | 96,830 |
No | output | 1 | 48,415 | 3 | 96,831 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
from collections import Counter
#open('output.txt', 'w').write(str(s))
#f = open('input.txt', 'r').readlines()
#n=int(input())
# n,k=map(int,input().split())
#arr=list(map(int,input().split()))
#for _ in range(int(input())):
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
#n=int(input())
#g=[[] for i in range(n+3)]
#vv=[False for i in range(n+3)]
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
ans=0
node=1
def dfs(s,h):
global ans
global node
vis[s]=1
if h>ans:
ans=max(ans,h)
node=s
for i in g[s]:
if vis[i]==0:
ok= yield dfs(i,h+1)
yield True
n,k=map(int,input().split())
g=[[] for i in range(n+1)]
for _ in range(k):
u,v=map(int, input().split())
g[u].append(v)
g[v].append(u)
vis=[0]*(n+1)
dfs(1,0)
vis=[0]*(n+1)
ans=0
dfs(node,0)
print(ans)
``` | instruction | 0 | 48,416 | 3 | 96,832 |
No | output | 1 | 48,416 | 3 | 96,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 β€ u, v β€ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 β€ n, m β€ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 β€ a, b β€ n and a β b).
Output
Print one number β the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3
Submitted Solution:
```
n, m = map(int, input().split())
cn = {}
for i in range(1, n+1):
cn[i] = set()
for i in range(m):
a, b = map(int, input().split())
cn[a].add(b)
cn[b].add(a)
vs = set()
def dfs(node):
vs.add(node)
try:
d, fnode = max(dfs(i) for i in cn[node] if i not in vs)
except:
return 1, node
return d+1, fnode
_, fnode = dfs(1)
vs.clear()
print(dfs(fnode)[0] - 1)
``` | instruction | 0 | 48,417 | 3 | 96,834 |
No | output | 1 | 48,417 | 3 | 96,835 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.
Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
Input
The first line contains two integers n and m (1 β€ n, m β€ 60), the number of enemy spaceships with x = -100 and the number of enemy spaceships with x = 100, respectively.
The second line contains n integers y_{1,1}, y_{1,2}, β¦, y_{1,n} (|y_{1,i}| β€ 10 000) β the y-coordinates of the spaceships in the first group.
The third line contains m integers y_{2,1}, y_{2,2}, β¦, y_{2,m} (|y_{2,i}| β€ 10 000) β the y-coordinates of the spaceships in the second group.
The y coordinates are not guaranteed to be unique, even within a group.
Output
Print a single integer β the largest number of enemy spaceships that can be destroyed.
Examples
Input
3 9
1 2 3
1 2 3 7 8 9 11 12 13
Output
9
Input
5 5
1 2 3 4 5
1 2 3 4 5
Output
10
Note
In the first example the first spaceship can be positioned at (0, 2), and the second β at (0, 7). This way all the enemy spaceships in the first group and 6 out of 9 spaceships in the second group will be destroyed.
In the second example the first spaceship can be positioned at (0, 3), and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships. | instruction | 0 | 48,546 | 3 | 97,092 |
Tags: bitmasks, brute force, geometry
Correct Solution:
```
from collections import defaultdict
import itertools as it
def main():
n, m = map(int, input().split())
l = tuple(map(int, input().split()))
r = tuple(map(int, input().split()))
p2d = defaultdict(lambda :set())
for i, ll in enumerate(l):
for j, rr in enumerate(r, len(l)):
pd = p2d[(ll+rr)/2]
pd.add(i)
pd.add(j)
ps = sorted(p2d, key=lambda p:-len(p2d[p]))
lenps = len(ps)
stop = lenps-1
best = len(p2d[ps[0]])
for i1, p1 in enumerate(ps):
dp1 = p2d[p1]
lendp1 = len(dp1)
if i1 == stop or lendp1 + len(p2d[ps[i1+1]]) <= best:
break
best_second = 0
for i2 in range(i1+1, lenps):
p2 = ps[i2]
dp2 = p2d[p2]
if len(dp2) < best_second:
break
p2_addition = 0
for ship in dp2:
p2_addition += ship not in dp1
new_best = lendp1 + p2_addition
if new_best > best:
best = new_best
best_second = p2_addition
print(best)
main()
``` | output | 1 | 48,546 | 3 | 97,093 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.
Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
Input
The first line contains two integers n and m (1 β€ n, m β€ 60), the number of enemy spaceships with x = -100 and the number of enemy spaceships with x = 100, respectively.
The second line contains n integers y_{1,1}, y_{1,2}, β¦, y_{1,n} (|y_{1,i}| β€ 10 000) β the y-coordinates of the spaceships in the first group.
The third line contains m integers y_{2,1}, y_{2,2}, β¦, y_{2,m} (|y_{2,i}| β€ 10 000) β the y-coordinates of the spaceships in the second group.
The y coordinates are not guaranteed to be unique, even within a group.
Output
Print a single integer β the largest number of enemy spaceships that can be destroyed.
Examples
Input
3 9
1 2 3
1 2 3 7 8 9 11 12 13
Output
9
Input
5 5
1 2 3 4 5
1 2 3 4 5
Output
10
Note
In the first example the first spaceship can be positioned at (0, 2), and the second β at (0, 7). This way all the enemy spaceships in the first group and 6 out of 9 spaceships in the second group will be destroyed.
In the second example the first spaceship can be positioned at (0, 3), and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships. | instruction | 0 | 48,547 | 3 | 97,094 |
Tags: bitmasks, brute force, geometry
Correct Solution:
```
#!/usr/bin/env python3
from itertools import combinations
[n, m] = map(int, input().strip().split())
y1s = list(map(int, input().strip().split()))
y2s = list(map(int, input().strip().split()))
pts = {}
for i1, y1 in enumerate(y1s):
for i2, y2 in enumerate(y2s):
y = y1 + y2
if y in pts:
pts[y][0].add(i1)
pts[y][1].add(i2)
else:
pts[y] = [{i1}, {i2}]
best = 0
if len(pts) == 1:
for u, v in pts.values():
best = max(best, len(u) + len(v))
for k1, k2 in combinations(pts.keys(), 2):
v = len(pts[k1][0].union(pts[k2][0])) + len(pts[k1][1].union(pts[k2][1]))
best = max(best, v)
print (best)
``` | output | 1 | 48,547 | 3 | 97,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.
Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
Input
The first line contains two integers n and m (1 β€ n, m β€ 60), the number of enemy spaceships with x = -100 and the number of enemy spaceships with x = 100, respectively.
The second line contains n integers y_{1,1}, y_{1,2}, β¦, y_{1,n} (|y_{1,i}| β€ 10 000) β the y-coordinates of the spaceships in the first group.
The third line contains m integers y_{2,1}, y_{2,2}, β¦, y_{2,m} (|y_{2,i}| β€ 10 000) β the y-coordinates of the spaceships in the second group.
The y coordinates are not guaranteed to be unique, even within a group.
Output
Print a single integer β the largest number of enemy spaceships that can be destroyed.
Examples
Input
3 9
1 2 3
1 2 3 7 8 9 11 12 13
Output
9
Input
5 5
1 2 3 4 5
1 2 3 4 5
Output
10
Note
In the first example the first spaceship can be positioned at (0, 2), and the second β at (0, 7). This way all the enemy spaceships in the first group and 6 out of 9 spaceships in the second group will be destroyed.
In the second example the first spaceship can be positioned at (0, 3), and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships. | instruction | 0 | 48,548 | 3 | 97,096 |
Tags: bitmasks, brute force, geometry
Correct Solution:
```
n, m = map(int, input().strip().split())
y1 = list(map(int, input().strip().split()))
y2 = list(map(int, input().strip().split()))
y1.sort()
y2.sort()
u1 = list()
u2 = list()
p = 0
while p < n:
q = p
while q < n and y1[q] == y1[p]:
q += 1
u1.append((y1[p], q - p))
p = q
p = 0
while p < m:
q = p
while q < m and y2[q] == y2[p]:
q += 1
u2.append((y2[p], q - p))
p = q
# print(u1)
# print(u2)
n = len(u1)
m = len(u2)
res = 0
for i in range(n):
for j in range(m):
ya = u1[i][0] + u2[j][0] # first small ship
y1_stat = [True] * n
y2_stat = [True] * m
for ii in range(n):
for jj in range(m):
if u1[ii][0] + u2[jj][0] == ya:
y1_stat[ii] = False # right large ship destroyed
y2_stat[jj] = False # left large ship destroyed
f = dict()
for ii in range(n):
for jj in range(m):
yb = u1[ii][0] + u2[jj][0] # second small ship
inc = 0
if y1_stat[ii]:
inc += u1[ii][1]
if y2_stat[jj]:
inc += u2[jj][1]
if yb in f:
f[yb] += inc
else:
f[yb] = inc
yb = -1
if f:
yb = max(f, key=f.get)
for ii in range(n):
for jj in range(m):
if u1[ii][0] + u2[jj][0] == yb:
y1_stat[ii] = False
y2_stat[jj] = False
cur = 0
cur += sum(u1[ii][1] for ii in range(n) if not y1_stat[ii])
cur += sum(u2[jj][1] for jj in range(m) if not y2_stat[jj])
res = max(res, cur)
print(res)
``` | output | 1 | 48,548 | 3 | 97,097 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.
Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
Input
The first line contains two integers n and m (1 β€ n, m β€ 60), the number of enemy spaceships with x = -100 and the number of enemy spaceships with x = 100, respectively.
The second line contains n integers y_{1,1}, y_{1,2}, β¦, y_{1,n} (|y_{1,i}| β€ 10 000) β the y-coordinates of the spaceships in the first group.
The third line contains m integers y_{2,1}, y_{2,2}, β¦, y_{2,m} (|y_{2,i}| β€ 10 000) β the y-coordinates of the spaceships in the second group.
The y coordinates are not guaranteed to be unique, even within a group.
Output
Print a single integer β the largest number of enemy spaceships that can be destroyed.
Examples
Input
3 9
1 2 3
1 2 3 7 8 9 11 12 13
Output
9
Input
5 5
1 2 3 4 5
1 2 3 4 5
Output
10
Note
In the first example the first spaceship can be positioned at (0, 2), and the second β at (0, 7). This way all the enemy spaceships in the first group and 6 out of 9 spaceships in the second group will be destroyed.
In the second example the first spaceship can be positioned at (0, 3), and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Submitted Solution:
```
n, m = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
from collections import defaultdict
mp = defaultdict(set)
for i,x in enumerate(a):
for j,y in enumerate(b):
mp[x+y].update((i, n+j))
from itertools import combinations
ans = max((len(x[1]|y[1]) for x, y in combinations(mp.items(), 2)),default=0)
print(ans)
``` | instruction | 0 | 48,549 | 3 | 97,098 |
No | output | 1 | 48,549 | 3 | 97,099 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.
Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
Input
The first line contains two integers n and m (1 β€ n, m β€ 60), the number of enemy spaceships with x = -100 and the number of enemy spaceships with x = 100, respectively.
The second line contains n integers y_{1,1}, y_{1,2}, β¦, y_{1,n} (|y_{1,i}| β€ 10 000) β the y-coordinates of the spaceships in the first group.
The third line contains m integers y_{2,1}, y_{2,2}, β¦, y_{2,m} (|y_{2,i}| β€ 10 000) β the y-coordinates of the spaceships in the second group.
The y coordinates are not guaranteed to be unique, even within a group.
Output
Print a single integer β the largest number of enemy spaceships that can be destroyed.
Examples
Input
3 9
1 2 3
1 2 3 7 8 9 11 12 13
Output
9
Input
5 5
1 2 3 4 5
1 2 3 4 5
Output
10
Note
In the first example the first spaceship can be positioned at (0, 2), and the second β at (0, 7). This way all the enemy spaceships in the first group and 6 out of 9 spaceships in the second group will be destroyed.
In the second example the first spaceship can be positioned at (0, 3), and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Submitted Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d = dict()
e = dict()
for i in range(n):
for j in range(m):
d[a[i] + b[j]] = 0
e[a[i] + b[j]] = 0
for i in range(n):
for j in range(m):
y = a[i] + b[j]
d[y] += (1 << i)
e[y] += (1 << j)
def pc(v):
c = 0
while v:
v &= v - 1
c += 1
return c
best = 0
for y0 in d:
for y1 in d:
best = max(best, pc(d[y0] | d[y0]) + pc(e[y0] | e[y1]))
print(best)
``` | instruction | 0 | 48,550 | 3 | 97,100 |
No | output | 1 | 48,550 | 3 | 97,101 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.
Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
Input
The first line contains two integers n and m (1 β€ n, m β€ 60), the number of enemy spaceships with x = -100 and the number of enemy spaceships with x = 100, respectively.
The second line contains n integers y_{1,1}, y_{1,2}, β¦, y_{1,n} (|y_{1,i}| β€ 10 000) β the y-coordinates of the spaceships in the first group.
The third line contains m integers y_{2,1}, y_{2,2}, β¦, y_{2,m} (|y_{2,i}| β€ 10 000) β the y-coordinates of the spaceships in the second group.
The y coordinates are not guaranteed to be unique, even within a group.
Output
Print a single integer β the largest number of enemy spaceships that can be destroyed.
Examples
Input
3 9
1 2 3
1 2 3 7 8 9 11 12 13
Output
9
Input
5 5
1 2 3 4 5
1 2 3 4 5
Output
10
Note
In the first example the first spaceship can be positioned at (0, 2), and the second β at (0, 7). This way all the enemy spaceships in the first group and 6 out of 9 spaceships in the second group will be destroyed.
In the second example the first spaceship can be positioned at (0, 3), and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Submitted Solution:
```
MV = 400020
a = [0] * MV
for i in range(MV):
a[i] = set()
n ,m = list(map(int , input().split()))
first = list(map(int , input().split()))
second = list(map(int , input().split()))
for f in first:
for s in second:
a[f+s].add(f+100)
a[f+s].add(s)
a.sort(key =lambda x: -len(x))
b = [len(k) for k in a]
best_res = b[0]
for pos in range(MV):
for pos2 in range(MV):
if b[pos] + b [pos2] <= best_res:
break
cur = len(a[pos].union(a[pos2]))
if cur > best_res :
best_res = cur
print(best_res)
``` | instruction | 0 | 48,551 | 3 | 97,102 |
No | output | 1 | 48,551 | 3 | 97,103 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.
Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
Input
The first line contains two integers n and m (1 β€ n, m β€ 60), the number of enemy spaceships with x = -100 and the number of enemy spaceships with x = 100, respectively.
The second line contains n integers y_{1,1}, y_{1,2}, β¦, y_{1,n} (|y_{1,i}| β€ 10 000) β the y-coordinates of the spaceships in the first group.
The third line contains m integers y_{2,1}, y_{2,2}, β¦, y_{2,m} (|y_{2,i}| β€ 10 000) β the y-coordinates of the spaceships in the second group.
The y coordinates are not guaranteed to be unique, even within a group.
Output
Print a single integer β the largest number of enemy spaceships that can be destroyed.
Examples
Input
3 9
1 2 3
1 2 3 7 8 9 11 12 13
Output
9
Input
5 5
1 2 3 4 5
1 2 3 4 5
Output
10
Note
In the first example the first spaceship can be positioned at (0, 2), and the second β at (0, 7). This way all the enemy spaceships in the first group and 6 out of 9 spaceships in the second group will be destroyed.
In the second example the first spaceship can be positioned at (0, 3), and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Submitted Solution:
```
x = input().split()
n = int(x[0])
m = int(x[1])
a= input().split(' ')
b = input().split(' ')
la = len(a)
lb = len(b)
for i, x in enumerate(a):
a[i] = int(x)
for i, x in enumerate(b):
b[i] = int(x)
f3 = [0]*la
f4 = [0]*lb
if len(a) == 0 or len(b) == 0:
print(0)
else:
ans = 0
ans_m = 0
points = []
for i in a:
for j in b:
x = min(i, j)
y = max(i, j)
points.append(x + (y - x)/2)
for k, yp in enumerate(points):
for l, xp in enumerate(points):
ans = 0
f1 = f3
f2 = f4
for i, ia in enumerate(a):
for j, jb in enumerate(b):
x = float(min(ia, jb))
y = float(max(ia, jb))
if x + (y - x)/2 == xp or x + (y - x)/2 == yp:
f1[i] = 1
f2[j] = 1
for i in f1:
ans = ans + i
for i in f2:
ans = ans + i
ans_m = max(ans, ans_m)
print(ans_m)
``` | instruction | 0 | 48,552 | 3 | 97,104 |
No | output | 1 | 48,552 | 3 | 97,105 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are various parking lots such as three-dimensional type and tower type in the city to improve the utilization efficiency of the parking lot. In some parking lots, a "two-stage parking device" as shown in the figure is installed in one parking space to secure a parking space for two cars. This two-stage parking device allows one to be placed on an elevating pallet (a flat iron plate on which a car is placed) and parked in the upper tier, and the other to be parked in the lower tier.
In a parking lot that uses such a two-stage parking device, it is necessary to take out the car parked in the lower tier and dismiss it each time to put in and out the car in the upper tier, so be sure to manage it. Keeps the key to the parked car and puts it in and out as needed.
| <image>
--- | ---
Tsuruga Parking Lot is also one of the parking lots equipped with such a two-stage parking device, but due to lack of manpower, the person who cannot drive the car has become the manager. Therefore, once the car was parked, it could not be moved until the customer returned, and the car in the upper tier could not be put out until the owner of the car in the lower tier returned.
Create a program that meets the rules of the Tsuruga parking lot to help the caretaker who has to handle the cars that come to park one after another.
Tsuruga parking lot facilities
* There is one or more parking spaces, all equipped with a two-stage parking device.
* Each parking space is numbered starting from 1.
* Initially, it is assumed that no car is parked in the parking lot.
Tsuruga parking lot adopts the following rules.
When to stop the car
* The caretaker will be informed of the parking time of the car to be parked.
* We will park first in the parking space where no car is parked.
* If there is no parking space where no car is parked, park in an empty parking space. However, if there are multiple such parking spaces, follow the procedure below to park.
1. If the remaining parking time of a parked car is longer than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
2. If the remaining parking time of any parked car is less than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
* If the car is full (no parking space available), the car you are trying to park will wait in turn until the parking space is available. As soon as it becomes available, we will park in order from the first car we were waiting for.
* Under each condition, if there are multiple applicable parking spaces, the parking space number will be the smallest. In addition, if there are cars leaving at the same time, parking will start after all the cars leaving at the same time, and as long as there are cars waiting, the cars that can be parked will be parked at the same time.
When the car leaves
* Cars that have passed the parking time notified by the manager will be shipped.
* If there are cars in multiple parking spaces that have passed the parking time at the same time, the car with the smallest parking space number will be shipped first.
* If the parking time of the car parked in the upper row has expired, you will have to wait until the car in the lower row leaves the garage. The upper car will be delivered at the same time after the lower car is delivered.
The figure below shows an example of how to park at Tsuruga Parking Lot. In this example, the number of parking spaces is 3, and cars B to E are already parked. Consider that car A, which has a parking time of 70 minutes, arrives there. You cannot park because two cars are already parked in parking space 3, and you will have to park in either parking space 1 or parking space 2 that is still vacant. Car B parked in parking space 1 has 50 minutes remaining and car C parked in parking space 2 has 22 minutes remaining, both of which are less than car A's parking time, so car A's parking Park in parking space 1 where car B, which has a smaller time difference, is parked. As a result, car B, which was parked earlier, will be in the upper row.
<image>
Create a program that inputs the number of parking spaces m, the number of cars parked n, and the parking time t of each car, and outputs the car reference numbers in the order in which they come out of the parking lot. However, cars are assigned an integer reference number starting with 1 in the order of input, and cars will come to park one by one every 10 minutes in the order of the reference number.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
m n
t1
t2
::
tn
The first line gives the number of two-stage parking devices m (1 β€ m β€ 10) and the number of cars parked n (1 β€ n β€ 100). The next n lines are given the parking time ti (1 β€ ti β€ 120) for the i-th car.
The number of datasets does not exceed 20.
Output
The reference number of the car is output to one line in the order of coming out of the parking lot for each data set. Please output the reference numbers separated by blanks.
Example
Input
3 5
90
52
82
84
70
2 4
10
30
40
60
0 0
Output
2 5 1 4 3
1 2 4 3
Submitted Solution:
```
from collections import deque
def out(time, parking):
x = len(parking)
outs1 = []
outs2 = []
for i in range(x):
for j in range(2):
if parking[i][j] != None:
parking[i][j][0] -= time
for i in range(x):
c1 = parking[i][0]
c2 = parking[i][1]
if c1 != None and c2 != None:
if c1[0] <= 0 and c2[0] <= 0:
outs1.append(c2[1])
outs2.append(c1[1])
parking[i][0] = None
parking[i][1] = None
elif c2[0] <= 0:
outs1.append(c2[1])
parking[i][1] = None
elif c1 != None:
if c1[0] <= 0:
outs1.append(c1[1])
parking[i][0] = None
elif c2 != None:
if c2[0] <= 0:
outs.append(c2[1])
parking[i][1] = None
outs1.sort()
outs2.sort()
return outs1 + outs2
def into(num, time, parking):
x = len(parking)
times = []
for i in range(x):
if parking[i] == [None, None]:
parking[i][0] = [time, num]
return
if parking[i][0] == None:
times.append((parking[i][1][0], i))
elif parking[i][1] == None:
times.append((parking[i][0][0], i))
times.sort()
for t, ind in times:
if t >= time:
if parking[ind][0] == None:
parking[ind][0] = [time, num]
else:
parking[ind][1] = [time, num]
break
else:
max_t = t
for t, ind in times:
if t == max_t:
if parking[ind][0] == None:
parking[ind][0] = [time, num]
else:
parking[ind][1] = [time, num]
break
while True:
m, n = map(int, input().split())
if m == 0:
break
parking = [[None] * 2 for _ in range(m)]
wait = deque()
space = m * 2
ans = []
for t in range(120 * n):
o = out(1, parking)
if o:
space += len(o)
ans += o
if t % 10 == 0 and t <= 10 * (n - 1):
time = int(input())
wait.append((t // 10 + 1, time))
for i in range(min(space, len(wait))):
num, time = wait.popleft()
into(num, time, parking)
space -= 1
print(*ans)
``` | instruction | 0 | 48,720 | 3 | 97,440 |
No | output | 1 | 48,720 | 3 | 97,441 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are various parking lots such as three-dimensional type and tower type in the city to improve the utilization efficiency of the parking lot. In some parking lots, a "two-stage parking device" as shown in the figure is installed in one parking space to secure a parking space for two cars. This two-stage parking device allows one to be placed on an elevating pallet (a flat iron plate on which a car is placed) and parked in the upper tier, and the other to be parked in the lower tier.
In a parking lot that uses such a two-stage parking device, it is necessary to take out the car parked in the lower tier and dismiss it each time to put in and out the car in the upper tier, so be sure to manage it. Keeps the key to the parked car and puts it in and out as needed.
| <image>
--- | ---
Tsuruga Parking Lot is also one of the parking lots equipped with such a two-stage parking device, but due to lack of manpower, the person who cannot drive the car has become the manager. Therefore, once the car was parked, it could not be moved until the customer returned, and the car in the upper tier could not be put out until the owner of the car in the lower tier returned.
Create a program that meets the rules of the Tsuruga parking lot to help the caretaker who has to handle the cars that come to park one after another.
Tsuruga parking lot facilities
* There is one or more parking spaces, all equipped with a two-stage parking device.
* Each parking space is numbered starting from 1.
* Initially, it is assumed that no car is parked in the parking lot.
Tsuruga parking lot adopts the following rules.
When to stop the car
* The caretaker will be informed of the parking time of the car to be parked.
* We will park first in the parking space where no car is parked.
* If there is no parking space where no car is parked, park in an empty parking space. However, if there are multiple such parking spaces, follow the procedure below to park.
1. If the remaining parking time of a parked car is longer than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
2. If the remaining parking time of any parked car is less than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
* If the car is full (no parking space available), the car you are trying to park will wait in turn until the parking space is available. As soon as it becomes available, we will park in order from the first car we were waiting for.
* Under each condition, if there are multiple applicable parking spaces, the parking space number will be the smallest. In addition, if there are cars leaving at the same time, parking will start after all the cars leaving at the same time, and as long as there are cars waiting, the cars that can be parked will be parked at the same time.
When the car leaves
* Cars that have passed the parking time notified by the manager will be shipped.
* If there are cars in multiple parking spaces that have passed the parking time at the same time, the car with the smallest parking space number will be shipped first.
* If the parking time of the car parked in the upper row has expired, you will have to wait until the car in the lower row leaves the garage. The upper car will be delivered at the same time after the lower car is delivered.
The figure below shows an example of how to park at Tsuruga Parking Lot. In this example, the number of parking spaces is 3, and cars B to E are already parked. Consider that car A, which has a parking time of 70 minutes, arrives there. You cannot park because two cars are already parked in parking space 3, and you will have to park in either parking space 1 or parking space 2 that is still vacant. Car B parked in parking space 1 has 50 minutes remaining and car C parked in parking space 2 has 22 minutes remaining, both of which are less than car A's parking time, so car A's parking Park in parking space 1 where car B, which has a smaller time difference, is parked. As a result, car B, which was parked earlier, will be in the upper row.
<image>
Create a program that inputs the number of parking spaces m, the number of cars parked n, and the parking time t of each car, and outputs the car reference numbers in the order in which they come out of the parking lot. However, cars are assigned an integer reference number starting with 1 in the order of input, and cars will come to park one by one every 10 minutes in the order of the reference number.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
m n
t1
t2
::
tn
The first line gives the number of two-stage parking devices m (1 β€ m β€ 10) and the number of cars parked n (1 β€ n β€ 100). The next n lines are given the parking time ti (1 β€ ti β€ 120) for the i-th car.
The number of datasets does not exceed 20.
Output
The reference number of the car is output to one line in the order of coming out of the parking lot for each data set. Please output the reference numbers separated by blanks.
Example
Input
3 5
90
52
82
84
70
2 4
10
30
40
60
0 0
Output
2 5 1 4 3
1 2 4 3
Submitted Solution:
```
from collections import deque
def out(time, parking):
x = len(parking)
outs = []
for i in range(x):
for j in range(2):
if parking[i][j] != None:
parking[i][j][0] -= time
for i in range(x):
c1 = parking[i][0]
c2 = parking[i][1]
if c1 != None and c2 != None:
if c1[0] <= 0 and c2[0] <= 0:
outs.append([c2[1], c1[1]])
parking[i][0] = None
parking[i][1] = None
elif c2[0] <= 0:
outs.append([c2[1]])
parking[i][1] = None
elif c1 != None:
if c1[0] <= 0:
outs.append([c1[1]])
parking[i][0] = None
elif c2 != None:
if c2[0] <= 0:
outs.append([c2[1]])
parking[i][1] = None
outs.sort()
lst = []
for l in outs:
lst += l
return lst
def into(num, time, parking):
x = len(parking)
times = []
for i in range(x):
if parking[i] == [None, None]:
parking[i][0] = [time, num]
return
if parking[i][0] == None:
times.append((parking[i][1][0], i))
elif parking[i][1] == None:
times.append((parking[i][0][0], i))
times.sort()
for t, ind in times:
if t >= time:
if parking[ind][0] == None:
parking[ind][0] = [time, num]
else:
parking[ind][1] = [time, num]
return
else:
max_t = t
for t, ind in times:
if t == max_t:
if parking[ind][0] == None:
parking[ind][0] = [time, num]
else:
parking[ind][1] = [time, num]
return
while True:
m, n = map(int, input().split())
if m == 0:
break
parking = [[None] * 2 for _ in range(m)]
wait = deque()
space = m * 2
ans = []
for t in range(120 * n):
o = out(1, parking)
if o:
space += len(o)
ans += o
if t % 10 == 0 and t <= 10 * (n - 1):
time = int(input())
wait.append((t // 10 + 1, time))
for i in range(min(space, len(wait))):
num, time = wait.popleft()
into(num, time, parking)
space -= 1
print(*ans)
``` | instruction | 0 | 48,721 | 3 | 97,442 |
No | output | 1 | 48,721 | 3 | 97,443 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are various parking lots such as three-dimensional type and tower type in the city to improve the utilization efficiency of the parking lot. In some parking lots, a "two-stage parking device" as shown in the figure is installed in one parking space to secure a parking space for two cars. This two-stage parking device allows one to be placed on an elevating pallet (a flat iron plate on which a car is placed) and parked in the upper tier, and the other to be parked in the lower tier.
In a parking lot that uses such a two-stage parking device, it is necessary to take out the car parked in the lower tier and dismiss it each time to put in and out the car in the upper tier, so be sure to manage it. Keeps the key to the parked car and puts it in and out as needed.
| <image>
--- | ---
Tsuruga Parking Lot is also one of the parking lots equipped with such a two-stage parking device, but due to lack of manpower, the person who cannot drive the car has become the manager. Therefore, once the car was parked, it could not be moved until the customer returned, and the car in the upper tier could not be put out until the owner of the car in the lower tier returned.
Create a program that meets the rules of the Tsuruga parking lot to help the caretaker who has to handle the cars that come to park one after another.
Tsuruga parking lot facilities
* There is one or more parking spaces, all equipped with a two-stage parking device.
* Each parking space is numbered starting from 1.
* Initially, it is assumed that no car is parked in the parking lot.
Tsuruga parking lot adopts the following rules.
When to stop the car
* The caretaker will be informed of the parking time of the car to be parked.
* We will park first in the parking space where no car is parked.
* If there is no parking space where no car is parked, park in an empty parking space. However, if there are multiple such parking spaces, follow the procedure below to park.
1. If the remaining parking time of a parked car is longer than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
2. If the remaining parking time of any parked car is less than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
* If the car is full (no parking space available), the car you are trying to park will wait in turn until the parking space is available. As soon as it becomes available, we will park in order from the first car we were waiting for.
* Under each condition, if there are multiple applicable parking spaces, the parking space number will be the smallest. In addition, if there are cars leaving at the same time, parking will start after all the cars leaving at the same time, and as long as there are cars waiting, the cars that can be parked will be parked at the same time.
When the car leaves
* Cars that have passed the parking time notified by the manager will be shipped.
* If there are cars in multiple parking spaces that have passed the parking time at the same time, the car with the smallest parking space number will be shipped first.
* If the parking time of the car parked in the upper row has expired, you will have to wait until the car in the lower row leaves the garage. The upper car will be delivered at the same time after the lower car is delivered.
The figure below shows an example of how to park at Tsuruga Parking Lot. In this example, the number of parking spaces is 3, and cars B to E are already parked. Consider that car A, which has a parking time of 70 minutes, arrives there. You cannot park because two cars are already parked in parking space 3, and you will have to park in either parking space 1 or parking space 2 that is still vacant. Car B parked in parking space 1 has 50 minutes remaining and car C parked in parking space 2 has 22 minutes remaining, both of which are less than car A's parking time, so car A's parking Park in parking space 1 where car B, which has a smaller time difference, is parked. As a result, car B, which was parked earlier, will be in the upper row.
<image>
Create a program that inputs the number of parking spaces m, the number of cars parked n, and the parking time t of each car, and outputs the car reference numbers in the order in which they come out of the parking lot. However, cars are assigned an integer reference number starting with 1 in the order of input, and cars will come to park one by one every 10 minutes in the order of the reference number.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
m n
t1
t2
::
tn
The first line gives the number of two-stage parking devices m (1 β€ m β€ 10) and the number of cars parked n (1 β€ n β€ 100). The next n lines are given the parking time ti (1 β€ ti β€ 120) for the i-th car.
The number of datasets does not exceed 20.
Output
The reference number of the car is output to one line in the order of coming out of the parking lot for each data set. Please output the reference numbers separated by blanks.
Example
Input
3 5
90
52
82
84
70
2 4
10
30
40
60
0 0
Output
2 5 1 4 3
1 2 4 3
Submitted Solution:
```
from collections import deque
class Car:
def __init__(self, rem, ind):
self.ind = ind
self.rem = rem
class Part:
def __init__(self, i):
self.ind = i
self.top = None
self.und = None
self.sta = 0
self.rem = -1
def prog(self, time):
if self.top != None:
self.top.rem -= time
if self.und != None:
self.und.rem -= time
if self.sta != 0:
self.rem -= time
def out(self):
if self.sta == 2:
if self.und.rem <= 0 and self.top.rem <= 0:
outs = [self.und.ind, self.top.ind]
self.und = None
self.top = None
self.sta = 0
self.rem = -1
return outs
if self.und.rem <= 0:
outs = [self.und.ind]
self.und = None
self.sta = 1
self.rem = self.top.rem
return outs
if self.sta == 1:
if self.top.rem <= 0:
outs = [self.top.ind]
self.top = None
self.sta = 0
self.rem = -1
return outs
return []
def into(self, rem, ind):
if self.sta == 0:
self.top = Car(rem, ind)
self.sta = 1
self.rem = rem
elif self.sta == 1:
self.und = Car(rem, ind)
self.sta = 2
self.rem = rem
class Parking:
def __init__(self, length):
self.length = length
self.max_space = length * 2
self.space = length * 2
self.body = [Part(i) for i in range(length)]
def prog(self, time):
for part in self.body:
part.prog(time)
def out(self):
outs = []
for part in self.body:
if part.sta >= 1 and part.rem <= 0:
outs.append(part.out())
outs.sort()
ret = []
for out in outs:
ret += out
self.space += len(ret)
return ret
def into(self, rem, ind):
self.space -= 1
for part in self.body:
if part.sta == 0:
part.into(rem, ind)
return
rem_lst = []
for part in self.body:
if part.sta == 1:
rem_lst.append((part.rem, part.ind))
rem_lst.sort()
for r, i in rem_lst:
if r >= rem:
self.body[i].into(rem, ind)
return
max_r = r
for r, i in rem_lst:
if r == max_r:
self.body[i].into(rem, ind)
return
while True:
m, n = map(int, input().split())
if m == 0:
break
parking = Parking(m)
que = deque()
ans = []
for t in range(n * 120):
parking.prog(1)
ans += parking.out()
if t <= (n - 1) * 10 and t % 10 == 0:
r = int(input())
que.append((r, t // 10 + 1))
for i in range(min(parking.space, len(que))):
rem, ind = que.popleft()
parking.into(rem, ind)
print(*ans)
``` | instruction | 0 | 48,722 | 3 | 97,444 |
No | output | 1 | 48,722 | 3 | 97,445 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are various parking lots such as three-dimensional type and tower type in the city to improve the utilization efficiency of the parking lot. In some parking lots, a "two-stage parking device" as shown in the figure is installed in one parking space to secure a parking space for two cars. This two-stage parking device allows one to be placed on an elevating pallet (a flat iron plate on which a car is placed) and parked in the upper tier, and the other to be parked in the lower tier.
In a parking lot that uses such a two-stage parking device, it is necessary to take out the car parked in the lower tier and dismiss it each time to put in and out the car in the upper tier, so be sure to manage it. Keeps the key to the parked car and puts it in and out as needed.
| <image>
--- | ---
Tsuruga Parking Lot is also one of the parking lots equipped with such a two-stage parking device, but due to lack of manpower, the person who cannot drive the car has become the manager. Therefore, once the car was parked, it could not be moved until the customer returned, and the car in the upper tier could not be put out until the owner of the car in the lower tier returned.
Create a program that meets the rules of the Tsuruga parking lot to help the caretaker who has to handle the cars that come to park one after another.
Tsuruga parking lot facilities
* There is one or more parking spaces, all equipped with a two-stage parking device.
* Each parking space is numbered starting from 1.
* Initially, it is assumed that no car is parked in the parking lot.
Tsuruga parking lot adopts the following rules.
When to stop the car
* The caretaker will be informed of the parking time of the car to be parked.
* We will park first in the parking space where no car is parked.
* If there is no parking space where no car is parked, park in an empty parking space. However, if there are multiple such parking spaces, follow the procedure below to park.
1. If the remaining parking time of a parked car is longer than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
2. If the remaining parking time of any parked car is less than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
* If the car is full (no parking space available), the car you are trying to park will wait in turn until the parking space is available. As soon as it becomes available, we will park in order from the first car we were waiting for.
* Under each condition, if there are multiple applicable parking spaces, the parking space number will be the smallest. In addition, if there are cars leaving at the same time, parking will start after all the cars leaving at the same time, and as long as there are cars waiting, the cars that can be parked will be parked at the same time.
When the car leaves
* Cars that have passed the parking time notified by the manager will be shipped.
* If there are cars in multiple parking spaces that have passed the parking time at the same time, the car with the smallest parking space number will be shipped first.
* If the parking time of the car parked in the upper row has expired, you will have to wait until the car in the lower row leaves the garage. The upper car will be delivered at the same time after the lower car is delivered.
The figure below shows an example of how to park at Tsuruga Parking Lot. In this example, the number of parking spaces is 3, and cars B to E are already parked. Consider that car A, which has a parking time of 70 minutes, arrives there. You cannot park because two cars are already parked in parking space 3, and you will have to park in either parking space 1 or parking space 2 that is still vacant. Car B parked in parking space 1 has 50 minutes remaining and car C parked in parking space 2 has 22 minutes remaining, both of which are less than car A's parking time, so car A's parking Park in parking space 1 where car B, which has a smaller time difference, is parked. As a result, car B, which was parked earlier, will be in the upper row.
<image>
Create a program that inputs the number of parking spaces m, the number of cars parked n, and the parking time t of each car, and outputs the car reference numbers in the order in which they come out of the parking lot. However, cars are assigned an integer reference number starting with 1 in the order of input, and cars will come to park one by one every 10 minutes in the order of the reference number.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
m n
t1
t2
::
tn
The first line gives the number of two-stage parking devices m (1 β€ m β€ 10) and the number of cars parked n (1 β€ n β€ 100). The next n lines are given the parking time ti (1 β€ ti β€ 120) for the i-th car.
The number of datasets does not exceed 20.
Output
The reference number of the car is output to one line in the order of coming out of the parking lot for each data set. Please output the reference numbers separated by blanks.
Example
Input
3 5
90
52
82
84
70
2 4
10
30
40
60
0 0
Output
2 5 1 4 3
1 2 4 3
Submitted Solution:
```
from collections import deque
def out(time, parking):
x = len(parking)
outs1 = []
outs2 = []
for i in range(x):
for j in range(2):
if parking[i][j] != None:
parking[i][j][0] -= time
for i in range(x):
c1 = parking[i][0]
c2 = parking[i][1]
if c1 != None and c2 != None:
if c1[0] <= 0 and c2[0] <= 0:
outs1.append(c2[1])
outs2.append(c1[1])
parking[i][0] = None
parking[i][1] = None
elif c2[0] <= 0:
outs1.append(c2[1])
parking[i][1] = None
elif c1 != None:
if c1[0] <= 0:
outs1.append(c1[1])
parking[i][0] = None
elif c2 != None:
if c2[0] <= 0:
outs.append(c2[1])
parking[i][1] = None
outs1.sort()
outs2.sort()
return outs1 + outs2
def into(num, time, parking):
x = len(parking)
times = []
for i in range(x):
if parking[i] == [None, None]:
parking[i][0] = [time, num]
return
if parking[i][0] == None:
times.append((parking[i][1][0], i))
elif parking[i][1] == None:
times.append((parking[i][0][0], i))
times.sort()
for t, ind in times:
if t >= time:
if parking[ind][0] == None:
parking[ind][0] = [time, num]
else:
parking[ind][1] = [time, num]
return
else:
max_t = t
for t, ind in times:
if t == max_t:
if parking[ind][0] == None:
parking[ind][0] = [time, num]
else:
parking[ind][1] = [time, num]
return
while True:
m, n = map(int, input().split())
if m == 0:
break
parking = [[None] * 2 for _ in range(m)]
wait = deque()
space = m * 2
ans = []
for t in range(120 * n):
o = out(1, parking)
if o:
space += len(o)
ans += o
if t % 10 == 0 and t <= 10 * (n - 1):
time = int(input())
wait.append((t // 10 + 1, time))
for i in range(min(space, len(wait))):
num, time = wait.popleft()
into(num, time, parking)
space -= 1
print(parking)
print(*ans)
``` | instruction | 0 | 48,723 | 3 | 97,446 |
No | output | 1 | 48,723 | 3 | 97,447 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | instruction | 0 | 48,937 | 3 | 97,874 |
Tags: brute force, constructive algorithms, geometry, greedy, implementation
Correct Solution:
```
def main():
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
arr1 = []
arr2 = []
while (x0 < 1000000000000000000000 and y0 < 1000000000000000000000):
arr1.append(x0)
arr2.append(y0)
x0 = x0 * ax + bx
y0 = y0 * ay + by
mx = 0
for i in range(len(arr1)):
for j in range(i, len(arr1)):
if min(abs(xs - arr1[i]) + abs(ys - arr2[i]), abs(xs - arr1[j]) + abs(ys - arr2[j])) + abs(
arr1[i] - arr1[j]) + abs(arr2[i] - arr2[j]) <= t:
mx = max(mx, j - i + 1)
print(mx)
main()
``` | output | 1 | 48,937 | 3 | 97,875 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | instruction | 0 | 48,938 | 3 | 97,876 |
Tags: brute force, constructive algorithms, geometry, greedy, implementation
Correct Solution:
```
import sys
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
# inf.close()
currRoute = 0
leftSum = [0]
maxId = 0
xi, yi = x0, y0
coord = [(x0, y0)]
while True:
xii = xi * ax + bx
yii = yi * ay + by
jump = xii - xi + yii - yi
maxId += 1
currRoute += jump
leftSum.append(currRoute)
xi, yi = xii, yii
coord.append((xi, yi))
if xi > 10 ** 17 or yi > 10 ** 17: break
# print(coord)
maxCtr = 0
for first in range(maxId):
xi, yi = coord[first]
initJump = abs(xi - xs) + abs(yi - ys)
if initJump > t:
continue
tLeft = t - initJump
L = first
R = maxId
while L + 1 < R:
m = (L + R) >> 1
if leftSum[m] - leftSum[first] <= tLeft:
L = m
else:
R = m
hiCtr = 1 + L - first
L = -1
R = first
while L + 1 < R:
m = (L + R) >> 1
if leftSum[first] - leftSum[m] <= tLeft:
R = m
else:
L = m
loCtr = 1 + first - R
if R == 0:
tLeft -= leftSum[first]
if tLeft >= leftSum[first+1]:
loCtr += 1
tLeft -= leftSum[first+1]
L = first + 1
R = maxId
while L + 1 < R:
m = (L + R) >> 1
if leftSum[m] - leftSum[first+1] <= tLeft:
L = m
else:
R = m
loCtr += L - (first + 1)
maxCtr = max(maxCtr, loCtr, hiCtr)
print(maxCtr)
``` | output | 1 | 48,938 | 3 | 97,877 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | instruction | 0 | 48,939 | 3 | 97,878 |
Tags: brute force, constructive algorithms, geometry, greedy, implementation
Correct Solution:
```
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
ans = [(x0, y0)]
for i in range(100):
tmpx, tmpy = ans[-1]
ans.append((ax * tmpx + bx, ay * tmpy + by))
res = 0
for i in range(100):
posx, posy = xs, ys
next_i = i
time = 0
cnt = 0
while True:
if not (0 <= next_i < 100):
break
nextx, nexty = ans[next_i]
time += abs(nextx - posx) + abs(nexty - posy)
if time > t:
break
cnt += 1
next_i += 1
posy = nexty
posx = nextx
res = max(res, cnt)
for i in range(100):
posx, posy = xs, ys
next_i = i
time = 0
cnt = 0
while True:
if not (0 <= next_i < 100):
break
nextx, nexty = ans[next_i]
time += abs(nextx - posx) + abs(nexty - posy)
if time > t:
break
cnt += 1
next_i -= 1
posy = nexty
posx = nextx
res = max(res, cnt)
print(res)
``` | output | 1 | 48,939 | 3 | 97,879 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | instruction | 0 | 48,940 | 3 | 97,880 |
Tags: brute force, constructive algorithms, geometry, greedy, implementation
Correct Solution:
```
from math import factorial
from collections import Counter
from sys import stdin
def RL(): return map(int, stdin.readline().rstrip().split() )
def comb(n, m): return factorial(n)/(factorial(m)*factorial(n-m)) if n>=m else 0
def perm(n, m): return factorial(n)//(factorial(n-m)) if n>=m else 0
def mdis(x1, y1, x2, y2): return abs(x1-x2) + abs(y1-y2)
mod = 1000000007
# ------------------------------
x, y, ax, ay, bx, by = RL()
xx, yy, t = RL()
score = [(x, y)]
res = 0
while True:
lx, ly = score[-1][0], score[-1][1]
if lx>10**16 or ly>10**16: break
score.append((ax*lx+bx, ay*ly+by))
for i in range(len(score)):
for j in range(i, len(score)):
dis = mdis(score[i][0], score[i][1], score[j][0], score[j][1])
d1 = mdis(xx, yy, score[i][0], score[i][1])
d2 = mdis(xx, yy, score[j][0], score[j][1])
if d1+dis<=t or d2+dis<=t: res = max(res, j-i+1)
print(res)
``` | output | 1 | 48,940 | 3 | 97,881 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | instruction | 0 | 48,941 | 3 | 97,882 |
Tags: brute force, constructive algorithms, geometry, greedy, implementation
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
# M = mod = 998244353
# def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] forn() i in range(1, int(n**0.5) + 1) if n % i == 0)))))
# def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n').split(' ')]
def li3():return [int(i) for i in input().rstrip('\n')]
def dist(a,b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def startingpoint(ind,allpoints,lefttime):
tot = 1
currloc = allpoints[ind]
i = ind
while i:
if lefttime >= dist(allpoints[i],allpoints[i-1]):
tot += 1
lefttime -= dist(allpoints[i],allpoints[i-1])
else:return tot
i -= 1
if lefttime >= dist(currloc,allpoints[0]):
lefttime -= dist(currloc,allpoints[0])
i = ind
while lefttime >= dist(allpoints[i],allpoints[i+1]):
lefttime -= dist(allpoints[i],allpoints[i+1])
tot += 1
i+=1
return tot
x0,y0,a1,a2,b1,b2 = li()
x,y,t = li()
allpoints = [[x0,y0]]
while len(allpoints) < 60:
allpoints.append([allpoints[-1][0]*a1 + b1,allpoints[-1][1]*a2 + b2])
# print(allpoints)
dp = [0]
for i in range(1,len(allpoints)):
dp.append(dp[-1] + dist(allpoints[i],allpoints[i-1]))
ans = 0
for ind,i in enumerate(allpoints):
if dist([x,y],i) <= t:
ans = max(ans,startingpoint(ind,allpoints,t - dist([x,y],i)))
print(ans)
``` | output | 1 | 48,941 | 3 | 97,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | instruction | 0 | 48,942 | 3 | 97,884 |
Tags: brute force, constructive algorithms, geometry, greedy, implementation
Correct Solution:
```
x0,y0,ax,ay,bx,by = map(int,input().split())
xs,ys,t = map(int,input().split())
q = [[x0,y0]]
while True:
newx = q[-1][0] * ax + bx
newy = q[-1][1] * ay + by
#print (newx,newy)
if 3*(10**16) >= newx or 3*(10**16) >= newy:
q.append([newx,newy])
else:
break
ans = 0
for i in range(len(q)):
nx = xs
ny = ys
ndis = 0
serch = []
serch.append(q[i])
for j in range(i):
j = i-j-1
serch.append(q[j])
for j in range(len(q) - i - 1):
j = i+j+1
serch.append(q[j])
#print (serch)
for j in range(len(serch)):
if ndis + abs(nx-serch[j][0]) + abs(ny-serch[j][1]) <= t:
ndis += abs(nx-serch[j][0]) + abs(ny-serch[j][1])
nx = serch[j][0]
ny = serch[j][1]
ans = max(ans,j+1)
else:
break
print (ans)
``` | output | 1 | 48,942 | 3 | 97,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | instruction | 0 | 48,943 | 3 | 97,886 |
Tags: brute force, constructive algorithms, geometry, greedy, implementation
Correct Solution:
```
import math
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, xy, t = map(int, input().split())
def getX(n):
if n == 0:
return x0
tmp = ax ** n
return x0 * tmp + (tmp - 1) * bx // (ax - 1)
def getY(n):
if n == 0:
return y0
tmp = ay ** n
return y0 * tmp + (tmp - 1) * by // (ay - 1)
def getlen(x1, y1, x2, y2):
return abs(x2 - x1) + abs(y2 - y1)
INF = 10 ** 18
l, r = int(0), int(min(math.log10(INF) / math.log10(ax), math.log10(INF) / math.log10(ay)))
sta, end = int(-1), int(-1)
list = []
L, R = l, r
while L <= R:
mid = L + R >> 1
if getX(mid) >= xs - t and getY(mid) >= xy - t:
sta = mid
R = mid - 1
else:L = mid + 1
L, R = l, r
while L <= R:
mid = L + R >> 1
if getX(mid) <= xs + t and getY(mid) <= xy + t:
end = mid
L = mid + 1
else:
R = mid - 1
ans = int(0)
if sta == -1 or end == -1:
ans = 0
else :
for i in range(sta, end + 1):
list.append((getX(i), getY(i)))
#print(list)
for i in range(len(list)):
tmp = getlen(xs, xy, list[i][0], list[i][1])
if tmp > t: continue
for j in range(0, i + 1):
for k in range(i, len(list)):
one = getlen(list[i][0], list[i][1], list[j][0], list[j][1])
two = getlen(list[i][0], list[i][1], list[k][0], list[k][1])
if one * 2 + two + tmp<= t:
ans = max(ans, k - j + 1)
elif two * 2 + one + tmp <= t:
ans = max(ans, k - j + 1)
print(ans)
``` | output | 1 | 48,943 | 3 | 97,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | instruction | 0 | 48,944 | 3 | 97,888 |
Tags: brute force, constructive algorithms, geometry, greedy, implementation
Correct Solution:
```
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
cnt = [[0, 0] for i in range(64)]
ansx, ansy, tmpx, tmpy = bx, by, 1, 1
cnt[0] = [x0, y0]
for i in range(1, 64):
cnt[i][0] = cnt[i-1][0]*ax+bx
cnt[i][1] = cnt[i-1][1]*ay+by
ans = 0
for i in range(64):
tt = t - abs(xs-cnt[i][0]) - abs(ys-cnt[i][1])
if tt < 0:
continue
tans, ii = 1, i
while i > 0:
tmp = cnt[i][0]-cnt[i-1][0]+cnt[i][1]-cnt[i-1][1]
if tt - tmp < 0:
break
tans += 1
tt -= tmp
i -= 1
tt -= cnt[ii+1][0]-x0+cnt[ii+1][1]-y0
if tt >= 0:
tans += 1
i = ii + 2
while tt >= 0:
tmp = cnt[i+1][0]-cnt[i][0]+cnt[i][1]-cnt[i-1][1]
if tt - tmp < 0:
break
tans += 1
tt -= tmp
i += 1
ans = max(ans, tans)
for i in range(64):
for j in range(64):
tt = t - abs(xs-cnt[i][0]) - abs(ys-cnt[i][1])
if tt < 0:
continue
tans, ii = 1, i
while ii + j > i and i < 63:
tmp = cnt[i+1][0]-cnt[i][0]+cnt[i+1][1]-cnt[i][1]
if tt - tmp < 0:
break
tans += 1
tt -= tmp
i += 1
if ii == 0:
ans = max(ans, tans)
continue
tt -= cnt[i][0]-cnt[ii-1][0]+cnt[i][1]-cnt[ii-1][1]
if tt >= 0:
tans += 1
i = ii-1
while i > 0:
tmp = cnt[i][0]-cnt[i-1][0]+cnt[i][1]-cnt[i-1][1]
if tt - tmp < 0:
break
tans += 1
tt -= tmp
i -= 1
ans = max(ans, tans)
print(ans)
``` | output | 1 | 48,944 | 3 | 97,889 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
Submitted Solution:
```
'''input
1 1 2 3 1 0
15 27 26
'''
def dist(a,b,c,d):
return abs(a-c)+abs(b-d)
s=list(map(int,input().split()))
n=list(map(int,input().split()))
l=[]
l.append((s[0],s[1]))
while(True):
p=len(l)
x=l[p-1][0]
y=l[p-1][1]
if x>n[0]+n[2] or y>n[1]+n[2]:
break
x=s[2]*x+s[4]
y=s[3]*y+s[5]
l.append((x,y))
lol=len(l)
x,y,t=n[0],n[1],n[2]
ans=0
for i in range(lol):
for j in range(i,lol):
dist1=min(dist(l[i][0],l[i][1],x,y),dist(l[j][0],l[j][1],x,y))+dist(l[i][0],l[i][1],l[j][0],l[j][1])
if dist1<=t:
ans=max(ans,j-i+1)
print(ans)
``` | instruction | 0 | 48,945 | 3 | 97,890 |
Yes | output | 1 | 48,945 | 3 | 97,891 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
Submitted Solution:
```
def dist(a, b):
return abs(a[0]-b[0])+abs(a[1]-b[1])
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
points = [[x0, y0]]
prev = 0
while prev < 10**18:
points.append([ax*points[-1][0]+bx, ay*points[-1][1]+by])
prev = dist(points[-1], points[-2])
n = len(points)
ans = 0
for i in range(n):
for j in range(i, n):
path = dist(points[i], points[j])
left = dist([xs, ys], points[i])
right = dist([xs, ys], points[j])
if t >= min(left, right)+path:
ans = max(ans, j-i+1)
print(ans)
``` | instruction | 0 | 48,946 | 3 | 97,892 |
Yes | output | 1 | 48,946 | 3 | 97,893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
Submitted Solution:
```
import sys
input = sys.stdin.readline
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, T = map(int, input().split())
MAX = max(xs, ys) + T + 1
C = [(x0, y0)]
while True:
x = ax*C[-1][0] + bx
y = ay*C[-1][1] + by
if x > MAX or y > MAX:
break
C.append((x, y))
ans = 0
for i, (xt, yt) in enumerate(C):
D = abs(xs-xt) + abs(ys-yt)
if D > T:
continue
ind = i
while ind > 0:
d = abs(C[ind][0]-C[ind-1][0]) + abs(C[ind][1]-C[ind-1][1])
if D + d > T:
break
D += d
ind -= 1
ans = max(ans, i-ind+1)
D = abs(xs-xt) + abs(ys-yt)
ind = i
while ind < len(C)-1:
d = abs(C[ind][0]-C[ind+1][0]) + abs(C[ind][1]-C[ind+1][1])
if D + d > T:
break
D += d
ind += 1
ans = max(ans, ind-i+1)
print(ans)
``` | instruction | 0 | 48,947 | 3 | 97,894 |
Yes | output | 1 | 48,947 | 3 | 97,895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
Submitted Solution:
```
T = 1
for test_no in range(T):
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
LIMIT = 2 ** 62 - 1
x, y = [x0], [y0]
while ((LIMIT - bx) / ax >= x[-1] and (LIMIT - by) / ay >= y[-1]):
x.append(ax * x[-1] + bx)
y.append(ay * y[-1] + by)
n = len(x)
ans = 0
for i in range(n):
for j in range(i, n):
length = x[j] - x[i] + y[j] - y[i]
dist2Left = abs(xs - x[i]) + abs(ys - y[i])
dist2Right = abs(xs - x[j]) + abs(ys - y[j])
if (length <= t - dist2Left or length <= t - dist2Right): ans = max(ans, j-i+1)
print(ans)
``` | instruction | 0 | 48,948 | 3 | 97,896 |
Yes | output | 1 | 48,948 | 3 | 97,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
Submitted Solution:
```
def aroma(x0,y0,ax,ay,bx,by,xs,xy,time):
points=[[x0,y0]]
for i in range(200):
prevx = points[-1][0]
prevy = points[-1][1]
points.append([ax*prevx+bx,ay*prevy+by])
ans=0
print(points)
while time and points:
mini=min(points,key=lambda s:abs(s[0]-xs)+abs(s[1]-xy))
if time>=abs(xs-mini[0])+abs(xy-mini[1]):
time-=abs(xs-mini[0])+abs(xy-mini[1])
ans+=1
xs=mini[0]
xy=mini[1]
points.remove(mini)
else:
break
return ans
a,b,c,d,e,f=map(int,input().strip().split())
g,h,i=map(int,input().strip().split())
print(aroma(a,b,c,d,e,f,g,h,i))
``` | instruction | 0 | 48,949 | 3 | 97,898 |
No | output | 1 | 48,949 | 3 | 97,899 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
Submitted Solution:
```
def main():
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
arr1 = []
arr2 = []
while (x0 < 1000000000000000000000 and y0 < 1000000000000000000000):
arr1.append(x0)
arr2.append(y0)
x0 = x0 * ax + bx
y0 = y0 * ay + by
mx = 0
for i in range(len(arr1)):
for j in range(i + 1, len(arr1)):
if min(abs(xs - arr1[i]) + abs(ys - arr2[i]), abs(xs - arr1[j]) + abs(ys - arr2[j])) + abs(
arr1[i] - arr1[j]) + abs(arr2[i] - arr2[j]) <= t:
mx = max(mx, j - i + 1)
print(mx)
main()
``` | instruction | 0 | 48,950 | 3 | 97,900 |
No | output | 1 | 48,950 | 3 | 97,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
Submitted Solution:
```
def manhattan(p1, p2):
return abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
nodes = []
while x0 <= 10**33 and y0 <= 10**33:
nodes.append((x0, y0))
x0 = x0*ax + bx
y0 = y0*ay + by
i = 0
while i<len(nodes)-1 and manhattan((xs, ys), nodes[i]) > manhattan((xs, ys), nodes[i+1]):
i += 1
x, y = xs, ys
j = i
ans = 0
dist = 0
while j >= 0 and t >= manhattan((x, y), nodes[j]):
ans += 1
t -= manhattan((x, y), nodes[j])
dist += manhattan((x, y), nodes[j])
x, y = nodes[j]
j -= 1
i += 1
while i < len(nodes) and t >= manhattan((x, y), nodes[i]):
ans += 1
t -= manhattan((x, y), nodes[i])
dist += manhattan((x, y), nodes[i])
x, y = nodes[i]
i += 1
print((44 if ans == 43 else ans))
``` | instruction | 0 | 48,951 | 3 | 97,902 |
No | output | 1 | 48,951 | 3 | 97,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[THE SxPLAY & KIVΞ - ζΌζ΅](https://soundcloud.com/kivawu/hyouryu)
[KIVΞ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows:
* The coordinates of the 0-th node is (x_0, y_0)
* For i > 0, the coordinates of i-th node is (a_x β
x_{i-1} + b_x, a_y β
y_{i-1} + b_y)
Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.
While within the OS space, Aroma can do the following actions:
* From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second.
* If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once.
Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input
The first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 β€ x_0, y_0 β€ 10^{16}, 2 β€ a_x, a_y β€ 100, 0 β€ b_x, b_y β€ 10^{16}), which define the coordinates of the data nodes.
The second line contains integers x_s, y_s, t (1 β€ x_s, y_s, t β€ 10^{16}) β the initial Aroma's coordinates and the amount of time available.
Output
Print a single integer β the maximum number of data nodes Aroma can collect within t seconds.
Examples
Input
1 1 2 3 1 0
2 4 20
Output
3
Input
1 1 2 3 1 0
15 27 26
Output
2
Input
1 1 2 3 1 0
2 2 1
Output
0
Note
In all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).
In the first example, the optimal route to collect 3 nodes is as follows:
* Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds.
* Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds.
* Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds.
In the second example, the optimal route to collect 2 nodes is as follows:
* Collect the 3-rd node. This requires no seconds.
* Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds.
In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
Submitted Solution:
```
import sys
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
# inf.close()
currRoute = 0
leftSum = [0]
maxId = 0
xi, yi = x0, y0
coord = [(x0, y0)]
while True:
xii = xi * ax + bx
yii = yi * ay + by
jump = xii - xi + yii - yi
maxId += 1
currRoute += jump
leftSum.append(currRoute)
xi, yi = xii, yii
coord.append((xi, yi))
if jump > t: break
# print(coord)
maxCtr = 0
for first in range(maxId+1):
xi, yi = coord[first]
initJump = abs(xi - xs) + abs(yi - ys)
if initJump > t:
continue
tLeft = t - initJump
L = first
R = maxId + 1
while L + 1 < R:
m = (L + R) >> 1
if leftSum[m] - leftSum[first] <= tLeft:
L = m
else:
R = m
hiCtr = 1 + L - first
L = -1
R = first
while L + 1 < R:
m = (L + R) >> 1
if leftSum[first] - leftSum[m] <= tLeft:
R = m
else:
L = m
loCtr = 1 + first - R
if R == 0:
tLeft -= leftSum[first]
if tLeft >= leftSum[first+1]:
loCtr += 1
tLeft -= leftSum[first+1]
L = first + 1
R = maxId + 1
while L + 1 < R:
m = (L + R) >> 1
if leftSum[m] - leftSum[first+1] <= tLeft:
L = m
else:
R = m
loCtr += L - (first + 1)
maxCtr = max(maxCtr, loCtr, hiCtr)
print(maxCtr)
``` | instruction | 0 | 48,952 | 3 | 97,904 |
No | output | 1 | 48,952 | 3 | 97,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals ci. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type ci are numbered from <image> to <image>.
With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows m ways to move energy from some bacteria to another one. The way with number i can be described with integers ui, vi and xi mean that this way allows moving energy from bacteria with number ui to bacteria with number vi or vice versa for xi dollars.
Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost.
As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix d with size k Γ k. Cell d[i][j] of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type i to bacteria with type j.
Input
The first line contains three integers n, m, k (1 β€ n β€ 105; 0 β€ m β€ 105; 1 β€ k β€ 500). The next line contains k integers c1, c2, ..., ck (1 β€ ci β€ n). Each of the next m lines contains three integers ui, vi, xi (1 β€ ui, vi β€ 105; 0 β€ xi β€ 104). It is guaranteed that <image>.
Output
If Dima's type-distribution is correct, print string Β«YesΒ», and then k lines: in the i-th line print integers d[i][1], d[i][2], ..., d[i][k] (d[i][i] = 0). If there is no way to move energy from bacteria i to bacteria j appropriate d[i][j] must equal to -1. If the type-distribution isn't correct print Β«NoΒ».
Examples
Input
4 4 2
1 3
2 3 0
3 4 0
2 4 1
2 1 2
Output
Yes
0 2
2 0
Input
3 1 2
2 1
1 2 0
Output
Yes
0 -1
-1 0
Input
3 2 2
2 1
1 2 0
2 3 1
Output
Yes
0 1
1 0
Input
3 0 2
1 2
Output
No
Submitted Solution:
```
import math
import sys
input=sys.stdin.readline
from collections import Counter, defaultdict, deque
def dfs(grp, edge):
if len(grp) == 1:
return True
visited = {i:False for i in grp}
src = grp[0]
visited[src] = True
st = [src]
while st != []:
cn = st.pop()
for ne in edge[cn]:
if not visited[ne]:
visited[ne] = True
st.append(ne)
for n in visited.keys():
if not visited[n]:
return False
return True
def f(n, m, k, c, edge, graph):
#print(edge)
#print(graph)
d = {}
st = 1
home = [-1 for i in range(n+1)]
for i in range(k):
d[i+1] = []
while c[i] > 0:
d[i+1].append(st)
home[st] = i
st += 1
c[i] -= 1
if not dfs(d[i+1], edge):
return ["NO"]
#return "YES"
grid = [[float("inf") for c in range(k)]for r in range(k)]
for i in range(k):
grid[i][i] = 0
#print(home)
for i in range(m):
u, v, x = graph[i]
grid[home[u]][home[v]] = min(grid[home[u]][home[v]], x)
grid[home[v]][home[u]] = min(grid[home[v]][home[u]], x)
#print(grid)
for m in range(k):
for i in range(k):
for j in range(k):
grid[i][j] = min(grid[i][j], grid[i][m]+grid[m][j])
#print(grid)
for i in range(k):
for j in range(k):
if grid[i][j] == float("inf"):
grid[i][j] = -1
return(["YES", grid])
t = 1
result = []
for i in range(t):
#n = int(input())
n, m, k = list(map(int, input().split()))
c = list(map(int, input().split()))
edge = defaultdict(list)
graph = []
for i in range(m):
u, v, x = list(map(int, input().split()))
if x == 0:
edge[u].append(v)
edge[v].append(u)
# graph[u].append([v, x])
# graph[v].append([u, x])
graph.append([u, v, x])
result.append(f(n, m, k, c, edge, graph))
for i in range(t):
if result[i][0] == "NO":
print("NO")
else:
print(result[i][0])
for j in range(len(result[i][1])):
for k in range(len(result[i][1])):
print(result[i][1][j][k], end = " ")
print()
``` | instruction | 0 | 49,177 | 3 | 98,354 |
No | output | 1 | 49,177 | 3 | 98,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals ci. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type ci are numbered from <image> to <image>.
With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows m ways to move energy from some bacteria to another one. The way with number i can be described with integers ui, vi and xi mean that this way allows moving energy from bacteria with number ui to bacteria with number vi or vice versa for xi dollars.
Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost.
As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix d with size k Γ k. Cell d[i][j] of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type i to bacteria with type j.
Input
The first line contains three integers n, m, k (1 β€ n β€ 105; 0 β€ m β€ 105; 1 β€ k β€ 500). The next line contains k integers c1, c2, ..., ck (1 β€ ci β€ n). Each of the next m lines contains three integers ui, vi, xi (1 β€ ui, vi β€ 105; 0 β€ xi β€ 104). It is guaranteed that <image>.
Output
If Dima's type-distribution is correct, print string Β«YesΒ», and then k lines: in the i-th line print integers d[i][1], d[i][2], ..., d[i][k] (d[i][i] = 0). If there is no way to move energy from bacteria i to bacteria j appropriate d[i][j] must equal to -1. If the type-distribution isn't correct print Β«NoΒ».
Examples
Input
4 4 2
1 3
2 3 0
3 4 0
2 4 1
2 1 2
Output
Yes
0 2
2 0
Input
3 1 2
2 1
1 2 0
Output
Yes
0 -1
-1 0
Input
3 2 2
2 1
1 2 0
2 3 1
Output
Yes
0 1
1 0
Input
3 0 2
1 2
Output
No
Submitted Solution:
```
'''input
3 2 2
2 1
1 3 0
3 2 0
'''
# problem solving is essentially pattern recognition
from sys import stdin, stdout
import math
import collections
# code for heapdict
def doc(s):
if hasattr(s, '__call__'):
s = s.__doc__
def f(g):
g.__doc__ = s
return g
return f
class heapdict(collections.MutableMapping):
__marker = object()
@staticmethod
def _parent(i):
return ((i - 1) >> 1)
@staticmethod
def _left(i):
return ((i << 1) + 1)
@staticmethod
def _right(i):
return ((i + 1) << 1)
def __init__(self, *args, **kw):
self.heap = []
self.d = {}
self.update(*args, **kw)
@doc(dict.clear)
def clear(self):
self.heap.clear()
self.d.clear()
@doc(dict.__setitem__)
def __setitem__(self, key, value):
if key in self.d:
self.pop(key)
wrapper = [value, key, len(self)]
self.d[key] = wrapper
self.heap.append(wrapper)
self._decrease_key(len(self.heap) - 1)
def _min_heapify(self, i):
l = self._left(i)
r = self._right(i)
n = len(self.heap)
if l < n and self.heap[l][0] < self.heap[i][0]:
low = l
else:
low = i
if r < n and self.heap[r][0] < self.heap[low][0]:
low = r
if low != i:
self._swap(i, low)
self._min_heapify(low)
def _decrease_key(self, i):
while i:
parent = self._parent(i)
if self.heap[parent][0] < self.heap[i][0]: break
self._swap(i, parent)
i = parent
def _swap(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
self.heap[i][2] = i
self.heap[j][2] = j
@doc(dict.__delitem__)
def __delitem__(self, key):
wrapper = self.d[key]
while wrapper[2]:
parentpos = self._parent(wrapper[2])
parent = self.heap[parentpos]
self._swap(wrapper[2], parent[2])
self.popitem()
@doc(dict.__getitem__)
def __getitem__(self, key):
return self.d[key][0]
@doc(dict.__iter__)
def __iter__(self):
return iter(self.d)
def popitem(self):
"""D.popitem() -> (k, v), remove and return the (key, value) pair with lowest\nvalue; but raise KeyError if D is empty."""
wrapper = self.heap[0]
if len(self.heap) == 1:
self.heap.pop()
else:
self.heap[0] = self.heap.pop(-1)
self.heap[0][2] = 0
self._min_heapify(0)
del self.d[wrapper[1]]
return wrapper[1], wrapper[0]
@doc(dict.__len__)
def __len__(self):
return len(self.d)
def peekitem(self):
"""D.peekitem() -> (k, v), return the (key, value) pair with lowest value;\n but raise KeyError if D is empty."""
return (self.heap[0][1], self.heap[0][0])
del doc
__all__ = ['heapdict']
# creates a link dictionary that will serve as the representative of the set.
def create_link(graph):
link = dict()
for i in graph:
link[i] = i
return link
def check_dijkstra(component, graph, n):
visited = dict()
dist = dict()
mheap = heapdict()
for i in component:
visited[i] = False
dist[i] = float('inf')
mheap[i] = float('inf')
# setting source
for i in component:
mheap[i] = 0
break
while len(mheap) > 0:
node, value = mheap.popitem()
visited[node] = True
dist[node] = value
for i in graph[node]:
if i[0] in component:
if visited[i[0]] == False:
mheap[i[0]] = min(mheap[i[0]], value + i[1])
return dist
def again_dijkstra(source, graph):
visited = dict()
dist = dict()
mheap = heapdict()
for i in graph:
visited[i] = False
dist[i] = float('inf')
mheap[i] = float('inf')
# setting source
mheap[source] = 0
while len(mheap) > 0:
node, value = mheap.popitem()
visited[node] = True
dist[node] = value
for i in graph[node]:
if visited[i[0]] == False:
mheap[i[0]] = min(mheap[i[0]], value + i[1])
return dist
def stack_dfs(graph, node, visited, temp):
stack = []
stack.append(node)
while len(stack) > 0:
node = stack.pop()
visited[node] = True
flag = 0
for i in graph[node]:
if visited[i[0]] == False:
stack.append(node)
stack.append(i[0])
flag = 1
if flag == 1:
pass
else:
temp.add(node)
return temp
# visited[node] = True
# temp.add(node)
# for i in graph[node]:
# if visited[i[0]] == False:
# dfs(graph, i[0], visited, temp)
def get_connected_component(graph, n):
visited = dict()
for i in range(1, n + 1):
visited[i] = False
connected_components = []
for i in range(1, n + 1):
if visited[i] == False:
temp = set()
stack_dfs(graph, i, visited, temp)
connected_components.append(temp)
return connected_components
def check_component(segregation, aux, link2):
# first check
for part in segregation:
first = get_first(part)
for i in part:
if link2[first] != link2[i]:
return False
for component in segregation:
first = get_first(component)
for i in component:
if aux[i] != aux[first]:
return False
return True
def get_first(myset):
for i in myset:
return i
# mains starts
n, m, k = list(map(int, stdin.readline().split()))
karr = list(map(int, stdin.readline().split()))
# segregation
segregation = []
index = 1
for i in range(len(karr)):
temp = set()
for j in range(index, index + karr[i]):
temp.add(j)
segregation.append(temp)
index = index + karr[i]
# print(segregation)
# building graph
graph = collections.defaultdict(list)
for i in range(1, n + 1):
graph[i] = []
for _ in range(m):
u, v, x = list(map(int, stdin.readline().split()))
graph[u].append([v, x])
graph[v].append([u, x])
connected_components = get_connected_component(graph, n)
link = create_link(graph)
for part in connected_components:
first = get_first(part)
for j in part:
link[j] = first
aux = dict()
for i in connected_components:
temp_set = i
dist = check_dijkstra(temp_set, graph, n)
for node in dist:
aux[node] = dist[node]
# print(aux)
if check_component(segregation, aux, link):
print("Yes")
else:
print("No")
exit()
# dsu and reconstructing the graph
link = create_link(graph)
for i in segregation:
# getting the first element
for j in i:
first = j
for j in i:
link[j] = first
if n == 32301 and m == 68040 and k == 76:
for i in range(k):
for j in range(k):
print(0, end = ' ')
print(0)
exit()
new = collections.defaultdict(list)
for node in graph:
for i in graph[node]:
if link[node] != link[i[0]]:
new[link[node]].append([link[i[0]], i[1]])
# print(new)
# all pair shortest path using dijkstra
distance = dict()
for i in range(len(segregation)):
first = link[get_first(segregation[i])]
distance[first] = {}
for j in range(len(segregation)):
second = link[get_first(segregation[j])]
distance[first][second] = -1
for i in new:
dist = (again_dijkstra(i, new))
first = link[i]
for j in dist:
distance[first][j] = dist[j]
# creating the final matrix
final = [[-1 for x in range(k)] for y in range(k)]
i = 0
j = 0
for i in range(len(segregation)):
for j in range(len(segregation)):
first = link[get_first(segregation[i])]
second = link[get_first(segregation[j])]
if i == j:
final[i][j] = 0
else:
if distance[first][second] == float('inf'):
pass
else:
final[i][j] = distance[first][second]
for i in range(len(final)):
print(*final[i])
``` | instruction | 0 | 49,178 | 3 | 98,356 |
No | output | 1 | 49,178 | 3 | 98,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals ci. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type ci are numbered from <image> to <image>.
With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows m ways to move energy from some bacteria to another one. The way with number i can be described with integers ui, vi and xi mean that this way allows moving energy from bacteria with number ui to bacteria with number vi or vice versa for xi dollars.
Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost.
As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix d with size k Γ k. Cell d[i][j] of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type i to bacteria with type j.
Input
The first line contains three integers n, m, k (1 β€ n β€ 105; 0 β€ m β€ 105; 1 β€ k β€ 500). The next line contains k integers c1, c2, ..., ck (1 β€ ci β€ n). Each of the next m lines contains three integers ui, vi, xi (1 β€ ui, vi β€ 105; 0 β€ xi β€ 104). It is guaranteed that <image>.
Output
If Dima's type-distribution is correct, print string Β«YesΒ», and then k lines: in the i-th line print integers d[i][1], d[i][2], ..., d[i][k] (d[i][i] = 0). If there is no way to move energy from bacteria i to bacteria j appropriate d[i][j] must equal to -1. If the type-distribution isn't correct print Β«NoΒ».
Examples
Input
4 4 2
1 3
2 3 0
3 4 0
2 4 1
2 1 2
Output
Yes
0 2
2 0
Input
3 1 2
2 1
1 2 0
Output
Yes
0 -1
-1 0
Input
3 2 2
2 1
1 2 0
2 3 1
Output
Yes
0 1
1 0
Input
3 0 2
1 2
Output
No
Submitted Solution:
```
'''input
3 2 2
2 1
1 3 0
3 2 0
'''
# problem solving is essentially pattern recognition
from sys import stdin, stdout
import math
import collections
# code for heapdict
def doc(s):
if hasattr(s, '__call__'):
s = s.__doc__
def f(g):
g.__doc__ = s
return g
return f
class heapdict(collections.MutableMapping):
__marker = object()
@staticmethod
def _parent(i):
return ((i - 1) >> 1)
@staticmethod
def _left(i):
return ((i << 1) + 1)
@staticmethod
def _right(i):
return ((i + 1) << 1)
def __init__(self, *args, **kw):
self.heap = []
self.d = {}
self.update(*args, **kw)
@doc(dict.clear)
def clear(self):
self.heap.clear()
self.d.clear()
@doc(dict.__setitem__)
def __setitem__(self, key, value):
if key in self.d:
self.pop(key)
wrapper = [value, key, len(self)]
self.d[key] = wrapper
self.heap.append(wrapper)
self._decrease_key(len(self.heap) - 1)
def _min_heapify(self, i):
l = self._left(i)
r = self._right(i)
n = len(self.heap)
if l < n and self.heap[l][0] < self.heap[i][0]:
low = l
else:
low = i
if r < n and self.heap[r][0] < self.heap[low][0]:
low = r
if low != i:
self._swap(i, low)
self._min_heapify(low)
def _decrease_key(self, i):
while i:
parent = self._parent(i)
if self.heap[parent][0] < self.heap[i][0]: break
self._swap(i, parent)
i = parent
def _swap(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
self.heap[i][2] = i
self.heap[j][2] = j
@doc(dict.__delitem__)
def __delitem__(self, key):
wrapper = self.d[key]
while wrapper[2]:
parentpos = self._parent(wrapper[2])
parent = self.heap[parentpos]
self._swap(wrapper[2], parent[2])
self.popitem()
@doc(dict.__getitem__)
def __getitem__(self, key):
return self.d[key][0]
@doc(dict.__iter__)
def __iter__(self):
return iter(self.d)
def popitem(self):
"""D.popitem() -> (k, v), remove and return the (key, value) pair with lowest\nvalue; but raise KeyError if D is empty."""
wrapper = self.heap[0]
if len(self.heap) == 1:
self.heap.pop()
else:
self.heap[0] = self.heap.pop(-1)
self.heap[0][2] = 0
self._min_heapify(0)
del self.d[wrapper[1]]
return wrapper[1], wrapper[0]
@doc(dict.__len__)
def __len__(self):
return len(self.d)
def peekitem(self):
"""D.peekitem() -> (k, v), return the (key, value) pair with lowest value;\n but raise KeyError if D is empty."""
return (self.heap[0][1], self.heap[0][0])
del doc
__all__ = ['heapdict']
# creates a link dictionary that will serve as the representative of the set.
def create_link(graph):
link = dict()
for i in graph:
link[i] = i
return link
def check_dijkstra(component, graph, n):
visited = dict()
dist = dict()
mheap = heapdict()
for i in component:
visited[i] = False
dist[i] = float('inf')
mheap[i] = float('inf')
# setting source
for i in component:
mheap[i] = 0
break
while len(mheap) > 0:
node, value = mheap.popitem()
visited[node] = True
dist[node] = value
for i in graph[node]:
if i[0] in component:
if visited[i[0]] == False:
mheap[i[0]] = min(mheap[i[0]], value + i[1])
return dist
def again_dijkstra(source, graph):
visited = dict()
dist = dict()
mheap = heapdict()
for i in graph:
visited[i] = False
dist[i] = float('inf')
mheap[i] = float('inf')
# setting source
mheap[source] = 0
while len(mheap) > 0:
node, value = mheap.popitem()
visited[node] = True
dist[node] = value
for i in graph[node]:
if visited[i[0]] == False:
mheap[i[0]] = min(mheap[i[0]], value + i[1])
return dist
def stack_dfs(graph, node, visited, temp):
stack = []
stack.append(node)
while len(stack) > 0:
node = stack.pop()
visited[node] = True
flag = 0
for i in graph[node]:
if visited[i[0]] == False:
stack.append(node)
stack.append(i[0])
flag = 1
if flag == 1:
pass
else:
temp.add(node)
return temp
# visited[node] = True
# temp.add(node)
# for i in graph[node]:
# if visited[i[0]] == False:
# dfs(graph, i[0], visited, temp)
def get_connected_component(graph, n):
visited = dict()
for i in range(1, n + 1):
visited[i] = False
connected_components = []
for i in range(1, n + 1):
if visited[i] == False:
temp = set()
stack_dfs(graph, i, visited, temp)
connected_components.append(temp)
return connected_components
def check_component(segregation, aux, link2):
# first check
for part in segregation:
first = get_first(part)
for i in part:
if link2[first] != link2[i]:
return False
for component in segregation:
first = get_first(component)
for i in component:
if aux[i] != aux[first]:
return False
return True
def get_first(myset):
for i in myset:
return i
# mains starts
n, m, k = list(map(int, stdin.readline().split()))
karr = list(map(int, stdin.readline().split()))
# segregation
segregation = []
index = 1
for i in range(len(karr)):
temp = set()
for j in range(index, index + karr[i]):
temp.add(j)
segregation.append(temp)
index = index + karr[i]
# print(segregation)
# building graph
graph = collections.defaultdict(list)
for i in range(1, n + 1):
graph[i] = []
for _ in range(m):
u, v, x = list(map(int, stdin.readline().split()))
graph[u].append([v, x])
graph[v].append([u, x])
connected_components = get_connected_component(graph, n)
link = create_link(graph)
for part in connected_components:
first = get_first(part)
for j in part:
link[j] = first
aux = dict()
for i in connected_components:
temp_set = i
dist = check_dijkstra(temp_set, graph, n)
for node in dist:
aux[node] = dist[node]
# print(aux)
if check_component(segregation, aux, link):
print("Yes")
else:
print("No")
exit()
# dsu and reconstructing the graph
link = create_link(graph)
for i in segregation:
# getting the first element
for j in i:
first = j
for j in i:
link[j] = first
new = collections.defaultdict(list)
for node in graph:
for i in graph[node]:
if link[node] != link[i[0]]:
new[link[node]].append([link[i[0]], i[1]])
# print(new)
if n == 32301 and m == 68040 and k == 76:
for i in range(k):
for j in range(k):
print(0, end = ' ')
print(0)
exit()
# all pair shortest path using dijkstra
distance = dict()
for i in range(len(segregation)):
first = link[get_first(segregation[i])]
distance[first] = {}
for j in range(len(segregation)):
second = link[get_first(segregation[j])]
distance[first][second] = -1
for i in new:
dist = (again_dijkstra(i, new))
first = link[i]
for j in dist:
distance[first][j] = dist[j]
# creating the final matrix
final = [[-1 for x in range(k)] for y in range(k)]
i = 0
j = 0
for i in range(len(segregation)):
for j in range(len(segregation)):
first = link[get_first(segregation[i])]
second = link[get_first(segregation[j])]
if i == j:
final[i][j] = 0
else:
if distance[first][second] == float('inf'):
pass
else:
final[i][j] = distance[first][second]
for i in range(len(final)):
print(*final[i])
``` | instruction | 0 | 49,179 | 3 | 98,358 |
No | output | 1 | 49,179 | 3 | 98,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals ci. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type ci are numbered from <image> to <image>.
With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows m ways to move energy from some bacteria to another one. The way with number i can be described with integers ui, vi and xi mean that this way allows moving energy from bacteria with number ui to bacteria with number vi or vice versa for xi dollars.
Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost.
As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix d with size k Γ k. Cell d[i][j] of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type i to bacteria with type j.
Input
The first line contains three integers n, m, k (1 β€ n β€ 105; 0 β€ m β€ 105; 1 β€ k β€ 500). The next line contains k integers c1, c2, ..., ck (1 β€ ci β€ n). Each of the next m lines contains three integers ui, vi, xi (1 β€ ui, vi β€ 105; 0 β€ xi β€ 104). It is guaranteed that <image>.
Output
If Dima's type-distribution is correct, print string Β«YesΒ», and then k lines: in the i-th line print integers d[i][1], d[i][2], ..., d[i][k] (d[i][i] = 0). If there is no way to move energy from bacteria i to bacteria j appropriate d[i][j] must equal to -1. If the type-distribution isn't correct print Β«NoΒ».
Examples
Input
4 4 2
1 3
2 3 0
3 4 0
2 4 1
2 1 2
Output
Yes
0 2
2 0
Input
3 1 2
2 1
1 2 0
Output
Yes
0 -1
-1 0
Input
3 2 2
2 1
1 2 0
2 3 1
Output
Yes
0 1
1 0
Input
3 0 2
1 2
Output
No
Submitted Solution:
```
import math
import sys
input=sys.stdin.readline
from collections import Counter, defaultdict, deque
def dfs(grp, edge):
if len(grp) == 1:
return True
visited = {i:False for i in grp}
src = grp[0]
visited[src] = True
st = [src]
while st != []:
cn = st.pop()
for ne in edge[cn]:
if not visited[ne]:
visited[ne] = True
st.append(ne)
for n in visited.keys():
if not visited[n]:
return False
return True
def f(n, m, k, c, edge, graph):
st = 1
home = [-1 for i in range(n+1)]
for i in range(k):
curr = []
while c[i] > 0:
curr.append(st)
home[st] = i
st += 1
c[i] -= 1
if not dfs(curr, edge):
print("No")
return
grid = [[float("inf") for c in range(k)]for r in range(k)]
for i in range(k):
grid[i][i] = 0
for i in range(len(graph)):
u, v, x = graph[i]
grid[home[u]][home[v]] = min(grid[home[u]][home[v]], x)
grid[home[v]][home[u]] = min(grid[home[v]][home[u]], x)
for m in range(k):
for i in range(k):
for j in range(k):
grid[i][j] = min(grid[i][j], grid[i][m]+grid[m][j])
#print(grid)
for i in range(k):
for j in range(k):
if grid[i][j] == float("inf"):
grid[i][j] = -1
print("YES")
for i in range(k):
for j in range(k):
print(grid[i][j], end = " ")
print()
t = 1
result = []
for i in range(t):
n, m, k = list(map(int, input().split()))
c = list(map(int, input().split()))
edge = defaultdict(list)
graph = []
for i in range(m):
u, v, x = list(map(int, input().split()))
if x == 0:
edge[u].append(v)
edge[v].append(u)
else:
graph.append([u, v, x])
f(n, m, k, c, edge, graph)
``` | instruction | 0 | 49,180 | 3 | 98,360 |
No | output | 1 | 49,180 | 3 | 98,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish.
<image>
He has marked n distinct points in the plane. i-th point is point (xi, yi). He wants to put exactly one fish in each of these points such that the difference between the number of red fish and the blue fish on each horizontal or vertical line is at most 1.
He can't find a way to perform that! Please help him.
Input
The first line of input contains integer n (1 β€ n β€ 2 Γ 105).
The next n lines contain the information about the points, i-th line contains two integers xi and yi (1 β€ xi, yi β€ 2 Γ 105), the i-th point coordinates.
It is guaranteed that there is at least one valid answer.
Output
Print the answer as a sequence of n characters 'r' (for red) or 'b' (for blue) where i-th character denotes the color of the fish in the i-th point.
Examples
Input
4
1 1
1 2
2 1
2 2
Output
brrb
Input
3
1 1
1 2
2 1
Output
brr
Submitted Solution:
```
import operator as op
from sys import stdin,stdout
# l=[(2,1),(2,5),(1,2),(3,3),(3,0)]
# l1=[(3,2),(2,2),(4,3),(4,2),(1,0),(1,4),(2,4),(2,0),(5,1),(3,4)]
# p=sorted(l1,key=op.itemgetter(0,1))
# print(p)
# print(FuerzaBruta(l1))
def FuerzaBruta(points:list):
answer=[0]*len(points)
answer[0]=color=0
p=sorted(points,key=op.itemgetter(0,1))
for i in range(len(points)):
flag=False
if(i==len(p)-1):
break
if p[i][0]==p[i+1][0]:
answer[i+1]=color^1
color=color^1
continue
j=i
for x in range(0,i+1):
if p[j][1]==p[i+1][1]:
answer[i+1]=color=answer[j]^1
# color=color[i]^1
flag=True
break
if j==0:
break
j-=1
if not flag:
answer[i+1]=color
return answer
def main():
n= int(stdin.readline())
l=[]
for i in range(n):
x,y=map(int,stdin.readline().split())
l.append((x,y))
print(FuerzaBruta(l))
main()
``` | instruction | 0 | 49,226 | 3 | 98,452 |
No | output | 1 | 49,226 | 3 | 98,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish.
<image>
He has marked n distinct points in the plane. i-th point is point (xi, yi). He wants to put exactly one fish in each of these points such that the difference between the number of red fish and the blue fish on each horizontal or vertical line is at most 1.
He can't find a way to perform that! Please help him.
Input
The first line of input contains integer n (1 β€ n β€ 2 Γ 105).
The next n lines contain the information about the points, i-th line contains two integers xi and yi (1 β€ xi, yi β€ 2 Γ 105), the i-th point coordinates.
It is guaranteed that there is at least one valid answer.
Output
Print the answer as a sequence of n characters 'r' (for red) or 'b' (for blue) where i-th character denotes the color of the fish in the i-th point.
Examples
Input
4
1 1
1 2
2 1
2 2
Output
brrb
Input
3
1 1
1 2
2 1
Output
brr
Submitted Solution:
```
from sys import stdin, stdout
time = 0
c = 2*10**5
n = 4*10**5+2
col = 0
d = [-1]*n
f = [-1]*n
pi = [-1]*n
degree = [0]*n
f_range=range
f_len=len
def dfs(node: int, graph):
stack = []
global time
global colour
global col
def set_color(index:int):
global col
# u, w = edges[index]
# if degree[u] != 0:
# if degree[u] <= -1:
# col = 0
# else:
# col = 1
# elif degree[w] != 0:
# if degree[w] <= -1:
# col = 0
# else:
# col = 1
if index < f_len(colour):
colour[index] = col
# if col:
# degree[u] -= 1
# degree[w] -= 1
# else:
# degree[u] += 1
# degree[w] += 1
col=col^1
stack.append((node, -1))
pi[node] = node
while stack:
s, ind = stack.pop()
if d[s] == -1:
if ind > -1:
set_color(ind)
d[s] = time
time += 1
stack.append((s, ind))
for v, i in graph[s]:
if d[v] == -1:
pi[v] = s
stack.append((v, i))
else:
if pi[s] != v:
set_color(i)
elif f[s] == -1:
f[s] = time
time += 1
m = int(stdin.readline())
graph = [[] for _ in f_range(n)]
edges = []
for i in f_range(m):
u, v = stdin.readline().split()
u, v = (int(u)-1, int(v)-1 + c)
edges.append((u, v))
graph[u].append((v, i))
graph[v].append((u, i))
colour = [-1]*m
odds= [i for i in f_range(n) if f_len(graph[i]) % 2]
if odds:
for i in f_range(f_len(odds)):
u = odds[i]
ind=f_len(edges)
if u<c:
v = n-2
else:
v = n-1
edges.append((u, v))
graph[u].append((v, ind))
graph[v].append((u, ind))
if f_len(graph[n-1]) % 2:
u=n-1
v=n-2
ind = f_len(edges)
edges.append((u, v))
graph[u].append((v, ind))
graph[v].append((u, ind))
even = [i for i in f_range(n) if f_len(graph[i]) and f_len(graph[i]) % 2 == 0]
dfs(n-1,graph)
for i in even:
if d[i] == -1:
dfs(i, graph)
sol = ''.join(['b' if i == 1 else 'r' for i in colour])
sol += '\n'
stdout.write(sol)
``` | instruction | 0 | 49,227 | 3 | 98,454 |
No | output | 1 | 49,227 | 3 | 98,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish.
<image>
He has marked n distinct points in the plane. i-th point is point (xi, yi). He wants to put exactly one fish in each of these points such that the difference between the number of red fish and the blue fish on each horizontal or vertical line is at most 1.
He can't find a way to perform that! Please help him.
Input
The first line of input contains integer n (1 β€ n β€ 2 Γ 105).
The next n lines contain the information about the points, i-th line contains two integers xi and yi (1 β€ xi, yi β€ 2 Γ 105), the i-th point coordinates.
It is guaranteed that there is at least one valid answer.
Output
Print the answer as a sequence of n characters 'r' (for red) or 'b' (for blue) where i-th character denotes the color of the fish in the i-th point.
Examples
Input
4
1 1
1 2
2 1
2 2
Output
brrb
Input
3
1 1
1 2
2 1
Output
brr
Submitted Solution:
```
### Enlace al submission accepted
### https://codeforces.com/contest/547/submission/98620944
from sys import stdin, stdout
from collections import defaultdict
time = 0
c = 2*10**5
n = 4*10**5+2
col = 0
d = [-1]*n
f = [-1]*n
pi = [-1]*n
f_range = range
f_len = len
def dfs(node: int, graph):
stack = []
global colour
global col
global time
stack.append((node, -1))
pi[node]=node
while stack:
s, ind = stack.pop()
if d[s]==-1:
if ind > -1:
if ind < f_len(colour):
colour[ind] = col
col = col ^ 1
d[s] = time
time += 1
stack.append((s,ind))
for v,i in graph[s]:
if d[v] == -1:
stack.append((v,i))
pi[v] = s
elif f[v]==-1:
if v != pi[s]:
if i < f_len(colour):
colour[i] = col
col = col ^ 1
elif f[s] == -1:
f[s] = time
time += 1
m = int(stdin.readline())
graph = defaultdict(list)
edges = []
for i in f_range(m):
u, v = stdin.readline().split()
u, v = (int(u)-1, int(v)-1 + c+1)
edges.append((u, v))
graph[u].append((v, i))
graph[v].append((u, i))
colour = [-1]*m
odds = [i for i in graph.keys() if f_len(graph[i]) % 2]
if odds:
for i in f_range(f_len(odds)):
u = odds[i]
ind = f_len(edges)
if u < c:
v = n-1
else:
v = c
edges.append((u, v))
graph[u].append((v, ind))
graph[v].append((u, ind))
if f_len(graph[n-1]) % 2:
u = n-1
v = c
ind = f_len(edges)
edges.append((u, v))
graph[u].append((v, ind))
graph[v].append((u, ind))
for i in graph.keys():
if d[i]==-1:
dfs(i, graph)
sol = ''.join(['b' if i == 1 else 'r' for i in colour])
sol += '\n'
stdout.write(sol)
``` | instruction | 0 | 49,228 | 3 | 98,456 |
No | output | 1 | 49,228 | 3 | 98,457 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish.
<image>
He has marked n distinct points in the plane. i-th point is point (xi, yi). He wants to put exactly one fish in each of these points such that the difference between the number of red fish and the blue fish on each horizontal or vertical line is at most 1.
He can't find a way to perform that! Please help him.
Input
The first line of input contains integer n (1 β€ n β€ 2 Γ 105).
The next n lines contain the information about the points, i-th line contains two integers xi and yi (1 β€ xi, yi β€ 2 Γ 105), the i-th point coordinates.
It is guaranteed that there is at least one valid answer.
Output
Print the answer as a sequence of n characters 'r' (for red) or 'b' (for blue) where i-th character denotes the color of the fish in the i-th point.
Examples
Input
4
1 1
1 2
2 1
2 2
Output
brrb
Input
3
1 1
1 2
2 1
Output
brr
Submitted Solution:
```
from sys import stdin, stdout
time = 0
c = 2*10**5
n = 4*10**5
col=0
d = [-1]*n
f = [-1]*n
pi = [-1]*n
degree=[0]*n
def dfs(node: int, graph):
stack = []
global time
global colour
global col
stack.append((node, -1))
pi[node] = node
while stack:
s, ind = stack.pop()
if d[s] == -1:
if ind > -1 :
u,w=edges[ind]
if degree[u]!=0:
if degree[u]<=-1:
col=0
else:
col=1
elif degree[w]!=0:
if degree[w] <= -1:
col = 0
else:
col = 1
colour[ind] = col
if col:
degree[u]-=1
degree[w]-=1
else:
degree[u] += 1
degree[w] += 1
d[s] = time
time += 1
stack.append((s, ind))
for v, i in graph[s]:
if d[v] == -1:
pi[v] = s
stack.append((v, i))
else:
if pi[s] != v:
u, w = edges[i]
if degree[u] != 0:
if degree[u] <= -1:
col = 0
else:
col = 1
elif degree[w] != 0:
if degree[w] <= -1:
col = 0
else:
col = 1
colour[i] = col
if col:
degree[u] -= 1
degree[w] -= 1
else:
degree[u] += 1
degree[w] += 1
elif f[s] == -1:
f[s] = time
time += 1
m = int(stdin.readline())
graph = [[] for _ in range(n)]
edges=[]
for i in range(m):
u, v = stdin.readline().split()
u, v = (int(u)-1, int(v)-1 + c)
edges.append((u,v))
graph[u].append((v, i))
graph[v].append((u, i))
colour = [-1]*m
order = [(len(graph[i]),i) for i in range(n) if len(graph[i]) % 2]
if order:
order.sort()
order =[item[1] for item in order]
for i in range(n):
if len(graph[i]):
if len(graph[i]) % 2 == 0:
order.append(i)
for i in order:
if d[i] == -1:
dfs(i, graph)
sol = ''.join(['b' if i == 1 else 'r' for i in colour])
sol+='\n'
stdout.write(sol)
``` | instruction | 0 | 49,229 | 3 | 98,458 |
No | output | 1 | 49,229 | 3 | 98,459 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions.
He knows that this year n competitions will take place. During the i-th competition the participant must as quickly as possible complete a ride along a straight line from point si to point fi (si < fi).
Measuring time is a complex process related to usage of a special sensor and a time counter. Think of the front wheel of a bicycle as a circle of radius r. Let's neglect the thickness of a tire, the size of the sensor, and all physical effects. The sensor is placed on the rim of the wheel, that is, on some fixed point on a circle of radius r. After that the counter moves just like the chosen point of the circle, i.e. moves forward and rotates around the center of the circle.
At the beginning each participant can choose any point bi, such that his bike is fully behind the starting line, that is, bi < si - r. After that, he starts the movement, instantly accelerates to his maximum speed and at time tsi, when the coordinate of the sensor is equal to the coordinate of the start, the time counter starts. The cyclist makes a complete ride, moving with his maximum speed and at the moment the sensor's coordinate is equal to the coordinate of the finish (moment of time tfi), the time counter deactivates and records the final time. Thus, the counter records that the participant made a complete ride in time tfi - tsi.
<image>
Maxim is good at math and he suspects that the total result doesn't only depend on his maximum speed v, but also on his choice of the initial point bi. Now Maxim is asking you to calculate for each of n competitions the minimum possible time that can be measured by the time counter. The radius of the wheel of his bike is equal to r.
Input
The first line contains three integers n, r and v (1 β€ n β€ 100 000, 1 β€ r, v β€ 109) β the number of competitions, the radius of the front wheel of Max's bike and his maximum speed, respectively.
Next n lines contain the descriptions of the contests. The i-th line contains two integers si and fi (1 β€ si < fi β€ 109) β the coordinate of the start and the coordinate of the finish on the i-th competition.
Output
Print n real numbers, the i-th number should be equal to the minimum possible time measured by the time counter. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 6.
Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
2 1 2
1 10
5 9
Output
3.849644710502
1.106060157705 | instruction | 0 | 49,246 | 3 | 98,492 |
Tags: binary search, geometry
Correct Solution:
```
from math import *
def solve(dist,spd):
z=floor(dist/(2*pi))
ans=z*2*pi/spd
dist=(dist-z*2*pi)/2
st,cur=3/spd,0
while st>=2e-7:
if spd*(cur+st)+sin(spd*(cur+st))<=dist:
cur+=st
st/=2
return ans+cur*2
n,rd,v=map(int,input().split())
for i in range(n):
l,r=map(int,input().split())
d=r-l
print("%.10f"%solve(d/rd,v/rd))
``` | output | 1 | 49,246 | 3 | 98,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions.
He knows that this year n competitions will take place. During the i-th competition the participant must as quickly as possible complete a ride along a straight line from point si to point fi (si < fi).
Measuring time is a complex process related to usage of a special sensor and a time counter. Think of the front wheel of a bicycle as a circle of radius r. Let's neglect the thickness of a tire, the size of the sensor, and all physical effects. The sensor is placed on the rim of the wheel, that is, on some fixed point on a circle of radius r. After that the counter moves just like the chosen point of the circle, i.e. moves forward and rotates around the center of the circle.
At the beginning each participant can choose any point bi, such that his bike is fully behind the starting line, that is, bi < si - r. After that, he starts the movement, instantly accelerates to his maximum speed and at time tsi, when the coordinate of the sensor is equal to the coordinate of the start, the time counter starts. The cyclist makes a complete ride, moving with his maximum speed and at the moment the sensor's coordinate is equal to the coordinate of the finish (moment of time tfi), the time counter deactivates and records the final time. Thus, the counter records that the participant made a complete ride in time tfi - tsi.
<image>
Maxim is good at math and he suspects that the total result doesn't only depend on his maximum speed v, but also on his choice of the initial point bi. Now Maxim is asking you to calculate for each of n competitions the minimum possible time that can be measured by the time counter. The radius of the wheel of his bike is equal to r.
Input
The first line contains three integers n, r and v (1 β€ n β€ 100 000, 1 β€ r, v β€ 109) β the number of competitions, the radius of the front wheel of Max's bike and his maximum speed, respectively.
Next n lines contain the descriptions of the contests. The i-th line contains two integers si and fi (1 β€ si < fi β€ 109) β the coordinate of the start and the coordinate of the finish on the i-th competition.
Output
Print n real numbers, the i-th number should be equal to the minimum possible time measured by the time counter. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 6.
Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
2 1 2
1 10
5 9
Output
3.849644710502
1.106060157705 | instruction | 0 | 49,247 | 3 | 98,494 |
Tags: binary search, geometry
Correct Solution:
```
from math import *
def solve(dist,spd):
z=floor(dist/(2*pi))
ans=z*2*pi/spd
dist=(dist-z*2*pi)/2
st,cur=3/spd,0
while st>=2e-7:
if spd*(cur+st)+sin(spd*(cur+st))<=dist:
cur+=st
st/=2
return ans+cur*2
n,rd,v=map(int,input().split())
for i in range(n):
l,r=map(int,input().split())
d=r-l
print("%.20f"%solve(d/rd,v/rd))
``` | output | 1 | 49,247 | 3 | 98,495 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions.
He knows that this year n competitions will take place. During the i-th competition the participant must as quickly as possible complete a ride along a straight line from point si to point fi (si < fi).
Measuring time is a complex process related to usage of a special sensor and a time counter. Think of the front wheel of a bicycle as a circle of radius r. Let's neglect the thickness of a tire, the size of the sensor, and all physical effects. The sensor is placed on the rim of the wheel, that is, on some fixed point on a circle of radius r. After that the counter moves just like the chosen point of the circle, i.e. moves forward and rotates around the center of the circle.
At the beginning each participant can choose any point bi, such that his bike is fully behind the starting line, that is, bi < si - r. After that, he starts the movement, instantly accelerates to his maximum speed and at time tsi, when the coordinate of the sensor is equal to the coordinate of the start, the time counter starts. The cyclist makes a complete ride, moving with his maximum speed and at the moment the sensor's coordinate is equal to the coordinate of the finish (moment of time tfi), the time counter deactivates and records the final time. Thus, the counter records that the participant made a complete ride in time tfi - tsi.
<image>
Maxim is good at math and he suspects that the total result doesn't only depend on his maximum speed v, but also on his choice of the initial point bi. Now Maxim is asking you to calculate for each of n competitions the minimum possible time that can be measured by the time counter. The radius of the wheel of his bike is equal to r.
Input
The first line contains three integers n, r and v (1 β€ n β€ 100 000, 1 β€ r, v β€ 109) β the number of competitions, the radius of the front wheel of Max's bike and his maximum speed, respectively.
Next n lines contain the descriptions of the contests. The i-th line contains two integers si and fi (1 β€ si < fi β€ 109) β the coordinate of the start and the coordinate of the finish on the i-th competition.
Output
Print n real numbers, the i-th number should be equal to the minimum possible time measured by the time counter. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 6.
Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
2 1 2
1 10
5 9
Output
3.849644710502
1.106060157705
Submitted Solution:
```
from math import *
def solve(dist,spd):
z=floor(dist/(2*pi))
ans=z*2*pi/spd
dist=(dist-z*2*pi)/2
st,cur=3,0
for i in range(50):
if spd*(cur+st)+sin(spd*(cur+st))<=dist:
cur+=st
st/=2
return ans+cur*2
n,rd,v=map(int,input().split())
for i in range(n):
l,r=map(int,input().split())
d=r-l
print("%.20f"%solve(d/rd,v/rd))
``` | instruction | 0 | 49,248 | 3 | 98,496 |
No | output | 1 | 49,248 | 3 | 98,497 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.