message stringlengths 2 48.6k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 318 108k | cluster float64 8 8 | __index_level_0__ int64 636 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day. | instruction | 0 | 52,638 | 8 | 105,276 |
Tags: binary search, flows, graphs
Correct Solution:
```
from collections import deque
class Dinic():
def __init__(self, listEdge, s, t):
self.s = s
self.t = t
self.graph = {}
self.maxCap = 1000000
# dict các node lân cận
# e[0]: from, e[1]: to, e[2]: dung luong
for e in listEdge:
if e[0] not in self.graph:
self.graph[e[0]] = []
if e[1] not in self.graph:
self.graph[e[1]] = []
#to #cap #reveser edge
self.graph[e[0]].append([e[1], e[2], len(self.graph[e[1]])])
self.graph[e[1]].append([e[0], 0, len(self.graph[e[0]])-1])
self.N = len(self.graph.keys())
def bfs(self):
self.dist = {}
self.dist[self.s] = 0
self.curIter = {node:[] for node in self.graph}
Q = deque([self.s])
while(len(Q) > 0):
cur = Q.popleft()
for index,e in enumerate(self.graph[cur]):
# Chỉ add vào các node kế tiếp nếu dung lượng cạnh > 0 và chưa được visit trước đấy
if e[1] > 0 and e[0] not in self.dist:
self.dist[e[0]] = self.dist[cur] + 1
# add vào danh sách node kế tiếp của node hiện tại
self.curIter[cur].append(index)
Q.append(e[0])
def findPath(self, cur, f):
if cur == self.t:
return f
while len(self.curIter[cur]) > 0:
indexEdge = self.curIter[cur][-1]
nextNode = self.graph[cur][indexEdge][0]
remainCap = self.graph[cur][indexEdge][1]
indexPreEdge = self.graph[cur][indexEdge][2]
if remainCap > 0 and self.dist[nextNode] > self.dist[cur]:
#self.next[cur] = indexEdge
flow = self.findPath(nextNode, min(f, remainCap))
if flow > 0:
self.path.append(cur)
self.graph[cur][indexEdge][1] -= flow
self.graph[nextNode][indexPreEdge][1] += flow
#if cur == self.s:
# print(self.path, flow)
return flow
#else:
#self.path.pop()
self.curIter[cur].pop()
return 0
def maxFlow(self):
maxflow = 0
flow = []
while(True):
self.bfs()
if self.t not in self.dist:
break
while(True):
self.path = []
f = self.findPath(self.s, self.maxCap)
#print('iter', self.curIter)
if f == 0:
break
flow.append(f)
maxflow += f
return maxflow
# Tìm tập node thuộc S và T
# sau khi đã tìm được max flow
def residualBfs(self):
Q = deque([self.s])
side = {self.s:'s'}
while(len(Q) > 0):
cur = Q.popleft()
for index,e in enumerate(self.graph[cur]):
if e[1] > 0 and e[0] not in side:
Q.append(e[0])
side[e[0]] = 's'
S = []
T = []
for x in self.graph:
if x in side:
S.append(x)
else:
T.append(x)
return set(S), set(T)
n, m, X = map(int, input().split())
edge = [list(map(int, input().split())) for _ in range(m)]
l, r = 0, 1000000
while r-l>1e-9:
#print(l, r)
md = (r+l) / 2
edge_ = [[u, v, w // md] for u, v, w in edge]
g = Dinic(edge_, 1, n)
maxflow = g.maxFlow()
if maxflow >= X:
l=md
else:
r=md
print(X*r)
``` | output | 1 | 52,638 | 8 | 105,277 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day. | instruction | 0 | 52,639 | 8 | 105,278 |
Tags: binary search, flows, graphs
Correct Solution:
```
from collections import defaultdict, deque
adj = defaultdict(lambda: defaultdict(lambda: 0))
def bfs(graph, inicio, destino, parent):
parent.clear()
queue = deque()
queue.append([inicio, float("Inf")])
parent[inicio] = -2
while (len(queue)):
current, flow = queue.popleft()
for i in adj[current]:
if parent[i] == -1 and graph[current][i] > 0:
parent[i] = current
flow = min(flow, graph[current][i])
if i == destino:
return flow
queue.append((i, flow))
return 0
def maxflow(graph, inicio, destino):
flow = 0
parent = defaultdict(lambda: -1)
while True:
t = bfs(graph, inicio, destino, parent)
if t:
flow += t
current = destino
while current != inicio:
prev = parent[current]
graph[prev][current] -= t
graph[current][prev] += t
current = prev
else:
break
return flow
n, m, x = [int(i) for i in input().split()]
for _ in range(m):
t = [int(i) for i in input().split()]
adj[t[0]][t[1]] = t[2]
def check(k):
meh = defaultdict(lambda: defaultdict(lambda: 0))
for i in adj:
for j in adj[i]:
ww = adj[i][j] // k
meh[i][j] = ww
flow = maxflow(meh, 1, n)
return flow
lo = 1 / x
hi = check(1)
for _ in range(70):
mid = (hi + lo) / 2
if check(mid)>=x:
lo = mid
else:
hi = mid
print(format(lo * x, '.9f'))
``` | output | 1 | 52,639 | 8 | 105,279 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day. | instruction | 0 | 52,640 | 8 | 105,280 |
Tags: binary search, flows, graphs
Correct Solution:
```
from collections import deque
class Dinic():
def __init__(self, listEdge, s, t):
self.s = s
self.t = t
self.graph = {}
self.maxCap = 1000000
# dict các node lân cận
# e[0]: from, e[1]: to, e[2]: dung luong
for e in listEdge:
if e[0] not in self.graph:
self.graph[e[0]] = []
if e[1] not in self.graph:
self.graph[e[1]] = []
#to #cap #reveser edge
self.graph[e[0]].append([e[1], e[2], len(self.graph[e[1]])])
self.graph[e[1]].append([e[0], 0, len(self.graph[e[0]])-1])
self.N = len(self.graph.keys())
def bfs(self):
self.dist = {}
self.dist[self.s] = 0
self.curIter = {node:[] for node in self.graph}
Q = deque([self.s])
while(len(Q) > 0):
cur = Q.popleft()
for index,e in enumerate(self.graph[cur]):
# Chỉ add vào các node kế tiếp nếu dung lượng cạnh > 0 và chưa được visit trước đấy
if e[1] > 0 and e[0] not in self.dist:
self.dist[e[0]] = self.dist[cur] + 1
# add vào danh sách node kế tiếp của node hiện tại
self.curIter[cur].append(index)
Q.append(e[0])
def findPath(self, cur, f):
if cur == self.t:
return f
while len(self.curIter[cur]) > 0:
indexEdge = self.curIter[cur][-1]
nextNode = self.graph[cur][indexEdge][0]
remainCap = self.graph[cur][indexEdge][1]
indexPreEdge = self.graph[cur][indexEdge][2]
if remainCap > 0 and self.dist[nextNode] > self.dist[cur]:
#self.next[cur] = indexEdge
flow = self.findPath(nextNode, min(f, remainCap))
if flow > 0:
self.path.append(cur)
self.graph[cur][indexEdge][1] -= flow
self.graph[nextNode][indexPreEdge][1] += flow
#if cur == self.s:
# print(self.path, flow)
return flow
#else:
#self.path.pop()
self.curIter[cur].pop()
return 0
def maxFlow(self):
maxflow = 0
flow = []
while(True):
self.bfs()
if self.t not in self.dist:
break
while(True):
self.path = []
f = self.findPath(self.s, self.maxCap)
#print('iter', self.curIter)
if f == 0:
break
flow.append(f)
maxflow += f
return maxflow
# Tìm tập node thuộc S và T
# sau khi đã tìm được max flow
def residualBfs(self):
Q = deque([self.s])
side = {self.s:'s'}
while(len(Q) > 0):
cur = Q.popleft()
for index,e in enumerate(self.graph[cur]):
if e[1] > 0 and e[0] not in side:
Q.append(e[0])
side[e[0]] = 's'
S = []
T = []
for x in self.graph:
if x in side:
S.append(x)
else:
T.append(x)
return set(S), set(T)
def is_ok(val, flow, X):
num = 0
for f in flow:
num += f // val
if num >= X:
return True
return False
n, m, X = map(int, input().split())
edge = [list(map(int, input().split())) for _ in range(m)]
l, r = 0, 1000000
while r-l>1e-9:
#print(l, r)
md = (r+l) / 2
edge_ = [[u, v, w // md] for u, v, w in edge]
g = Dinic(edge_, 1, n)
maxflow = g.maxFlow()
if maxflow >= X:
l=md
else:
r=md
print(X*r)
``` | output | 1 | 52,640 | 8 | 105,281 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day. | instruction | 0 | 52,641 | 8 | 105,282 |
Tags: binary search, flows, graphs
Correct Solution:
```
from collections import defaultdict, deque
def bfs(graph, inicio, destino, parent):
parent.clear()
queue = deque()
queue.append([inicio, float("Inf")])
parent[inicio] = -2
while (len(queue)):
current, flow = queue.popleft()
for i in graph[current]:
if parent[i] == -1 and graph[current][i] > 0:
parent[i] = current
flow = min(flow, graph[current][i])
if i == destino:
return flow
queue.append((i, flow))
return 0
def maxflow(graph, inicio, destino):
flow = 0
parent = defaultdict(lambda: -1)
while True:
t = bfs(graph, inicio, destino, parent)
if t:
flow += t
current = destino
while current != inicio:
prev = parent[current]
graph[prev][current] -= t
graph[current][prev] += t
current = prev
else:
break
return flow
n, m, x = [int(i) for i in input().split()]
graph = defaultdict(lambda: defaultdict(lambda: 0))
for _ in range(m):
t = [int(i) for i in input().split()]
graph[t[0]][t[1]] = t[2]
def check(k):
meh = defaultdict(lambda: defaultdict(lambda: 0))
for i in graph:
for j in graph[i]:
ww = graph[i][j] // k
meh[i][j] = ww
flow = maxflow(meh, 1, n)
return flow
lo = 1 / x
hi = check(1)
for _ in range(70):
mid = round((hi + lo) / 2,8)
if hi-lo<=0.0000001:
break
if check(mid)>=x:
lo = round(mid,7)
else:
hi = mid
print(format(lo * x, '.9f'))
``` | output | 1 | 52,641 | 8 | 105,283 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day. | instruction | 0 | 52,642 | 8 | 105,284 |
Tags: binary search, flows, graphs
Correct Solution:
```
from collections import defaultdict, deque
def bfs(graph, inicio, destino, parent):
parent.clear()
queue = deque()
queue.append([inicio, float("Inf")])
parent[inicio] = -2
while (len(queue)):
current, flow = queue.popleft()
for i in graph[current]:
if parent[i] == -1 and graph[current][i] > 0:
parent[i] = current
flow = min(flow, graph[current][i])
if i == destino:
return flow
queue.append((i, flow))
return 0
def maxflow(graph, inicio, destino):
flow = 0
parent = defaultdict(lambda: -1)
while True:
t = bfs(graph, inicio, destino, parent)
if t:
flow += t
current = destino
while current != inicio:
prev = parent[current]
graph[prev][current] -= t
graph[current][prev] += t
current = prev
else:
break
return flow
n, m, x = [int(i) for i in input().split()]
graph = defaultdict(lambda: defaultdict(lambda: 0))
for _ in range(m):
t = [int(i) for i in input().split()]
graph[t[0]][t[1]] = t[2]
def check(k):
meh = defaultdict(lambda: defaultdict(lambda: 0))
for i in graph:
for j in graph[i]:
ww = graph[i][j] // k
meh[i][j] = ww
flow = maxflow(meh, 1, n)
return flow
lo = 1 / x
hi = check(1)
for _ in range(70):
mid = round((hi + lo) / 2,9)
if check(mid)>=x:
lo = round(mid,9)
else:
hi = mid
print(format(lo * x, '.9f'))
``` | output | 1 | 52,642 | 8 | 105,285 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day.
Submitted Solution:
```
import sys
from random import randint
from math import *
class Graph:
verticies = {}
nodesCount = 0
class Vertex:
def __init__(self, label, endPoint=None):
self.label = label
self.edges = []
self.visitedToken = 0
self.endPoint = endPoint
class Edge:
residual = None
def __init__(self, from_, to_, isResidual, maxCapacity):
self.from_ = from_
self.to_ = to_
self.isResidual = isResidual
self.capacity = maxCapacity
self.flow = 0
def augment(self, bootleneck):
self.flow += bootleneck
self.residual.flow -= bootleneck
def remainingCapacity(self):
return self.capacity - self.flow
def addEdge(self, from_, to_, capacity):
from_ = self.verticies[from_]
to_ = self.verticies[to_]
if from_.endPoint and from_.endPoint != to_:
from_ = from_.endPoint
main = self.Edge(from_, to_, False, capacity)
residual = self.Edge(to_, from_, True, 0)
main.residual = residual
residual.residual = main
from_.edges.append(main)
to_.edges.append(residual)
def addVertex(self, label, *args):
self.nodesCount += 1
if args:
capacity = args[0]
key = str(randint(0, sys.maxsize)) + '--' + str(label)
endPoint = self.Vertex(key)
self.verticies[key] = endPoint
self.verticies[label] = self.Vertex(label, endPoint=endPoint)
self.addEdge(label, key, capacity)
else:
self.verticies[label] = self.Vertex(label)
def maxFlow(self, f, t):
f = self.verticies[f]
t = self.verticies[t]
visitedToken = 1
flow = 0
def dfs(node, bootleneck=sys.maxsize):
node.visitedToken = visitedToken
bootleneck_backup = bootleneck
if node == t:
return bootleneck
for edge in node.edges:
if edge.remainingCapacity() == 0 or edge.to_.visitedToken == visitedToken:
continue
bootleneck = dfs(edge.to_, min(
bootleneck, edge.remainingCapacity()))
if bootleneck:
edge.augment(bootleneck)
return bootleneck
else:
bootleneck = bootleneck_backup
return 0
while True:
bootleneck = dfs(f)
if not bootleneck:
break
flow += bootleneck
visitedToken += 1
return flow
n, m, x = map(int, input().split())
matrix = [[0 for _ in range(n+1)] for _ in range(n+1)]
g = Graph()
for i in range(1, n+1):
g.addVertex(i)
for i in range(m):
a, b, c = map(int, input().split())
g.addEdge(a, b, c)
# matrix[a][b] = c
flow = g.maxFlow(1, n)
bpf = x/flow
paths = []
for e in g.verticies[1].edges:
if not e.isResidual:
paths.append(e.flow)
ans = max(paths)/(max(paths) * int(bpf) + (int(bpf) != bpf))*x
print(round(ans*10**10)/10**10)
``` | instruction | 0 | 52,643 | 8 | 105,286 |
No | output | 1 | 52,643 | 8 | 105,287 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day.
Submitted Solution:
```
import sys
from random import randint
from math import ceil
mf=1
class Graph:
verticies = {}
nodesCount = 0
class Vertex:
def __init__(self, label, endPoint=None):
self.label = label
self.edges = []
self.visitedToken = 0
self.endPoint = endPoint
class Edge:
residual = None
def __init__(self, from_, to_, isResidual, maxCapacity):
self.from_ = from_
self.to_ = to_
self.isResidual = isResidual
self.capacity = maxCapacity
self.flow = 0
def augment(self, bootleneck):
self.flow += bootleneck
self.residual.flow -= bootleneck
def remainingCapacity(self):
return self.capacity - self.flow
def addEdge(self, from_, to_, capacity):
from_ = self.verticies[from_]
to_ = self.verticies[to_]
if from_.endPoint and from_.endPoint != to_:
from_ = from_.endPoint
main = self.Edge(from_, to_, False, capacity)
residual = self.Edge(to_, from_, True, 0)
main.residual = residual
residual.residual = main
from_.edges.append(main)
to_.edges.append(residual)
def addVertex(self, label, *args):
self.nodesCount += 1
if args:
capacity = args[0]
key = str(randint(0, sys.maxsize)) + '--' + str(label)
endPoint = self.Vertex(key)
self.verticies[key] = endPoint
self.verticies[label] = self.Vertex(label, endPoint=endPoint)
self.addEdge(label, key, capacity)
else:
self.verticies[label] = self.Vertex(label)
def maxFlow(self, f, t):
f = self.verticies[f]
t = self.verticies[t]
visitedToken = 1
flow = 0
global mf
def dfs(node, bootleneck=sys.maxsize):
node.visitedToken = visitedToken
bootleneck_backup = bootleneck
if node == t:
return bootleneck
for edge in node.edges:
if edge.remainingCapacity() == 0 or edge.to_.visitedToken == visitedToken:
continue
bootleneck = dfs(edge.to_, min(
bootleneck, edge.remainingCapacity()))
if bootleneck:
edge.augment(bootleneck)
return bootleneck
else:
bootleneck = bootleneck_backup
return 0
while True:
bootleneck = dfs(f)
if not bootleneck:
break
flow += bootleneck
mf=max(mf, bootleneck)
visitedToken += 1
return flow
n, m, x = map(int, input().split())
g = Graph()
for i in range(n):
g.addVertex(i+1)
for i in range(m):
g.addEdge(*map(int, input().split()))
flow = g.maxFlow(1, n)
paths = []
ff = ceil(mf*x/flow)
print(mf/ff * x)
``` | instruction | 0 | 52,644 | 8 | 105,288 |
No | output | 1 | 52,644 | 8 | 105,289 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day.
Submitted Solution:
```
from collections import defaultdict, deque
def bfs(graph, inicio, destino, parent):
parent.clear()
queue = deque()
queue.append([inicio, float("Inf")])
parent[inicio] = -2
while (len(queue)):
current, flow = queue.popleft()
for i in graph[current]:
if parent[i] == -1 and graph[current][i] > 0:
parent[i] = current
flow = min(flow, graph[current][i])
if i == destino:
return flow
queue.append((i, flow))
return 0
def maxflow(graph, inicio, destino):
unique = []
path = 0
parent = defaultdict(lambda: -1)
while True:
t = bfs(graph, inicio, destino, parent)
if t:
if t not in unique:
unique.append(t)
path += 1
current = destino
while current != inicio:
prev = parent[current]
graph[prev][current] -= t
current = prev
else:
break
if path == 1:
return "*"+str(unique[0])+"/x"
unique = sum(unique)
if unique > path:
return "*" + str(path) + "/" + str(unique)
return "*" + str(unique) + "/" + str(path)
n, m, x = [int(i) for i in input().split()]
graph = defaultdict(lambda: defaultdict(lambda: 0))
for _ in range(m):
t = [int(i) for i in input().split()]
graph[t[0]][t[1]] = t[2]
print(eval(str(x) + maxflow(graph, 1, n)))
``` | instruction | 0 | 52,645 | 8 | 105,290 |
No | output | 1 | 52,645 | 8 | 105,291 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.
In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.
Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.
Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.
Input
The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.
Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.
Output
Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4 4 3
1 2 2
2 4 1
1 3 1
3 4 2
Output
1.5000000000
Input
5 11 23
1 2 3
2 3 4
3 4 5
4 5 6
1 3 4
2 4 5
3 5 6
1 4 2
2 5 3
1 5 2
3 2 30
Output
10.2222222222
Note
In the first sample, Niwel has three bears. Two bears can choose the path <image>, while one bear can choose the path <image>. Even though the bear that goes on the path <image> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day.
Submitted Solution:
```
import sys
from random import randint
from math import ceil
class Graph:
verticies = {}
nodesCount = 0
class Vertex:
def __init__(self, label, endPoint=None):
self.label = label
self.edges = []
self.visitedToken = 0
self.endPoint = endPoint
class Edge:
residual = None
def __init__(self, from_, to_, isResidual, maxCapacity):
self.from_ = from_
self.to_ = to_
self.isResidual = isResidual
self.capacity = maxCapacity
self.flow = 0
def augment(self, bootleneck):
self.flow += bootleneck
self.residual.flow -= bootleneck
def remainingCapacity(self):
return self.capacity - self.flow
def addEdge(self, from_, to_, capacity):
from_ = self.verticies[from_]
to_ = self.verticies[to_]
if from_.endPoint and from_.endPoint != to_:
from_ = from_.endPoint
main = self.Edge(from_, to_, False, capacity)
residual = self.Edge(to_, from_, True, 0)
main.residual = residual
residual.residual = main
from_.edges.append(main)
to_.edges.append(residual)
def addVertex(self, label, *args):
self.nodesCount += 1
if args:
capacity = args[0]
key = str(randint(0, sys.maxsize)) + '--' + str(label)
endPoint = self.Vertex(key)
self.verticies[key] = endPoint
self.verticies[label] = self.Vertex(label, endPoint=endPoint)
self.addEdge(label, key, capacity)
else:
self.verticies[label] = self.Vertex(label)
def maxflowPath(self, f, t):
vis = [0 for _ in range(len(self.verticies)+1)]
flows = [0 for _ in range(len(self.verticies)+1)]
flows[f] = sys.maxsize
que = [f]
vis[f] = 1
while que:
node = que.pop(0)
for e in self.verticies[node].edges:
flows[e.to_.label] = max(
min(e.capacity, flows[node]), flows[e.to_.label])
if not vis[e.to_.label]:
que.append(e.to_.label)
vis[e.to_.label] = 1
return flows[t]
def maxFlow(self, f, t):
f = self.verticies[f]
t = self.verticies[t]
visitedToken = 1
flow = 0
def dfs(node, bootleneck=sys.maxsize):
node.visitedToken = visitedToken
bootleneck_backup = bootleneck
if node == t:
return bootleneck
for edge in node.edges:
if edge.remainingCapacity() == 0 or edge.to_.visitedToken == visitedToken:
continue
bootleneck = dfs(edge.to_, min(
bootleneck, edge.remainingCapacity()))
if bootleneck:
edge.augment(bootleneck)
return bootleneck
else:
bootleneck = bootleneck_backup
return 0
while True:
bootleneck = dfs(f)
if not bootleneck:
break
flow += bootleneck
visitedToken += 1
return flow
n, m, x = map(int, input().split())
g = Graph()
for i in range(n):
g.addVertex(i+1)
endPoints = []
for i in range(m):
a, b, c = map(int, input().split())
if b == n:
endPoints.append(a)
g.addEdge(a, b, c)
flow = g.maxFlow(1, n)
mf = g.maxflowPath(1, n)
bomp = ceil(mf*x/flow)
print(mf/bomp * x*0.999999)
``` | instruction | 0 | 52,646 | 8 | 105,292 |
No | output | 1 | 52,646 | 8 | 105,293 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42. | instruction | 0 | 52,647 | 8 | 105,294 |
Tags: binary search, dp, greedy
Correct Solution:
```
B1 = 0
B2 = 0
def solve(rem , step , sub):
global B1 , B2
if rem == 0 :
if (step == B1): B2 = max(B2 , sub)
if (step > B1):
B1 = step
B2 = sub
return
cnt = 1
while((cnt+1)**3 <= rem): cnt+=1
solve(rem-cnt**3,step+1 , sub + cnt**3)
if(cnt>0):
solve(cnt**3 - 1 - (cnt-1)**3 , step+1 , sub+ (cnt-1)**3)
x = int(input())
solve(x,0,0)
print(B1,B2)
``` | output | 1 | 52,647 | 8 | 105,295 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42. | instruction | 0 | 52,648 | 8 | 105,296 |
Tags: binary search, dp, greedy
Correct Solution:
```
def g(m, n, s):
if not m: return n, s
k = int(m ** (1 / 3))
x, y = k ** 3, (k - 1) ** 3
return max(g(m - x, n + 1, s + x), g(x - y - 1, n + 1, s + y))
print(*g(int(input()), 0, 0))
``` | output | 1 | 52,648 | 8 | 105,297 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42. | instruction | 0 | 52,649 | 8 | 105,298 |
Tags: binary search, dp, greedy
Correct Solution:
```
def kil(n):
if n<8: return (n,n)
m=2
while m*m*m<=n: m+=1
m-=1
k1,v1=kil(n-m*m*m)
k2,v2=kil(m*m*m-1-(m-1)*(m-1)*(m-1))
return (k1+1,v1+m*m*m) if (k1,v1+m*m*m)>(k2,v2+(m-1)*(m-1)*(m-1)) else (k2+1,v2+(m-1)*(m-1)*(m-1))
n=int(input())
print(*kil(n))
``` | output | 1 | 52,649 | 8 | 105,299 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42. | instruction | 0 | 52,650 | 8 | 105,300 |
Tags: binary search, dp, greedy
Correct Solution:
```
#!/usr/bin/env python3
import sys
# 1 8 27 64 125 216 343 512 729 1000
# 1-7: blocks of size 1
# 8-15: 1 block of size 2, blocks of size 1
# 16-23: 2 blocks of size 2, blocks of size 1
# 24-26: 3 blocks of size 2, blocks of size 1
# 27-34: 1 block of size 3, blocks of size 1
# Maximum will always be when you have the max number of size 1 blocks
def cube_root(x):
v = max(int(x ** (1.0 / 3.0)) - 1, 0)
while (v + 1) ** 3 <= x:
v += 1
return v
def solution(x):
# returns (n_blocks, volume)
#print("solution {}".format(x))
if x <= 7:
return (x, x)
next_smaller = cube_root(x) ** 3
candidate = solution(x - next_smaller)
candidate = (candidate[0] + 1, candidate[1] + next_smaller)
prenext_smaller = cube_root(next_smaller - 1) ** 3
if next_smaller - prenext_smaller > x - next_smaller:
candidate2 = solution(next_smaller - 1)
else:
candidate2 = candidate
if candidate >= candidate2:
return candidate
else:
return candidate2
n = int(input())
s = solution(n)
print(s[0], s[1])
``` | output | 1 | 52,650 | 8 | 105,301 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42. | instruction | 0 | 52,651 | 8 | 105,302 |
Tags: binary search, dp, greedy
Correct Solution:
```
def main():
def f(n):
if n < 8:
return [n, n]
a = int((n + .5) ** 0.3333333333333333)
r1 = f(n - a * a * a)
r1[1] += a * a * a
a -= 1
r2 = f(3 * a * (a + 1))
r2[1] += a * a * a
if r1 < r2:
r1 = r2
r1[0] += 1
return r1
print(*f(int(input())))
if __name__ == '__main__':
main()
``` | output | 1 | 52,651 | 8 | 105,303 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42. | instruction | 0 | 52,652 | 8 | 105,304 |
Tags: binary search, dp, greedy
Correct Solution:
```
def kil(n):
if n<8: return (n,n)
m=int(n**(1/3))
k1,v1=kil(n-m*m*m)
k2,v2=kil(m*m*m-1-(m-1)*(m-1)*(m-1))
return (k1+1,v1+m*m*m) if (k1,v1+m*m*m)>(k2,v2+(m-1)*(m-1)*(m-1)) else (k2+1,v2+(m-1)*(m-1)*(m-1))
n=int(input())
print(*kil(n))
``` | output | 1 | 52,652 | 8 | 105,305 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42. | instruction | 0 | 52,653 | 8 | 105,306 |
Tags: binary search, dp, greedy
Correct Solution:
```
n, c = 0, 0
def dfs(now, m, t):
global n, c
if now == 0:
if m > n:
n, c = m, t
return
i = 1
while i**3 <= now:
i += 1
i -= 1
dfs(now-i**3, m+1, t+i**3)
dfs(i**3-1-(i-1)**3, m+1, t+(i-1)**3)
m = int(input())
dfs(m, 0, 0)
print(n, c)
``` | output | 1 | 52,653 | 8 | 105,307 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42. | instruction | 0 | 52,654 | 8 | 105,308 |
Tags: binary search, dp, greedy
Correct Solution:
```
im = int(input())
best_steps = 0
best_length = 0
def rec(m, steps, substracted):
global best_steps, best_length
if m == 0:
if steps > best_steps:
best_steps = steps
best_length = substracted
elif steps == best_steps:
best_length = max(best_length, substracted)
return
a = 1
while (a + 1)**3 <= m:
a += 1
rec(m - a**3, steps + 1, substracted + a**3)
if a - 1 != 0:
rec(a**3-1-(a-1)**3, steps + 1, substracted + (a-1)**3)
rec(im, 0, 0)
print(best_steps, best_length)
``` | output | 1 | 52,654 | 8 | 105,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.
Submitted Solution:
```
import math
import sys
def get_next(x):
t = (-3 + math.sqrt(12 * x - 3)) / 6.0
t = math.floor(t)
for i in range(max(t - 6, 1), t + 7):
nx = x + i ** 3
if nx < (i + 1) ** 3:
return nx
assert(False)
min_by_level = [0, 1]
for i in range(2, 20):
min_by_level.append(get_next(min_by_level[-1]))
high = int(input())
level = 1
while min_by_level[level] <= high:
level += 1
level -= 1
ans_level = level
ans_number = 0
for i in range(level - 1, -1, -1):
le = 1
rg = 10 ** 5 + 1
while rg - le > 1:
mid = (rg + le) // 2
if high - mid ** 3 >= min_by_level[i]:
le = mid
else:
rg = mid
ans_number += le ** 3
high = min(high - le ** 3, (le + 1) ** 3 - 1 - le ** 3)
print(ans_level, ans_number)
``` | instruction | 0 | 52,655 | 8 | 105,310 |
Yes | output | 1 | 52,655 | 8 | 105,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.
Submitted Solution:
```
import math
m = int(input())
def get_max_edge(x):
c = x ** (1 / 3.0)
return math.floor(c)
max_blocks = 0
max_volume = 0
def solve(m, blocks, volume):
global max_blocks, max_volume
if m == 0:
if blocks > max_blocks or (blocks == max_blocks and volume > max_volume):
max_blocks = blocks
max_volume = volume
return
x = get_max_edge(m)
# print(m, "max edge", x, x **3 )
solve(m - x ** 3, blocks + 1, volume + x ** 3)
if x > 1:
solve(x ** 3 - 1 - (x - 1) ** 3, blocks + 1, volume + (x - 1) ** 3)
solve(m, 0, 0)
print(max_blocks, max_volume)
``` | instruction | 0 | 52,656 | 8 | 105,312 |
Yes | output | 1 | 52,656 | 8 | 105,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.
Submitted Solution:
```
def f(m, cnt, y):
global ans, x
if m == 0: return cnt, y
a = int(m ** (1/3))
k1, k2 = a ** 3, (a - 1) ** 3
return max(f(m - k1, cnt + 1, y + k1), f(k1 - k2 - 1, cnt + 1, y + k2))
print(*f(int(input()), 0, 0))
``` | instruction | 0 | 52,657 | 8 | 105,314 |
Yes | output | 1 | 52,657 | 8 | 105,315 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.
Submitted Solution:
```
import math
def steps(m, dct):
if m <= 7:
return m
if dct.get(m):
return dct[m]
x = math.floor(m**(1/3))
dct[m] = 1 + steps(max(m - x**3, (x**3 - 1) - (x - 1)**3), dct)
return dct[m]
if __name__ == "__main__":
m = int(input())
total_blocks_used = 0
total_vol = 0
steps_dct = {}
while (m > 0):
x = math.floor(m ** (1/3))
if steps(m, steps_dct) == 1 + steps(m - x**3, steps_dct):
m -= x**3
total_vol += x**3
else:
m = x**3 - 1 - (x-1)**3
total_vol += (x-1)**3
total_blocks_used += 1
print(f"{total_blocks_used} {total_vol}")
``` | instruction | 0 | 52,658 | 8 | 105,316 |
Yes | output | 1 | 52,658 | 8 | 105,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.
Submitted Solution:
```
m = int(input())
t = 0
i = 1
j=0
while t +i**3 <= m:
while t+i**3<=m and t + i**3 < (i+1)**3:
t += i**3;
j+=1
i+=1
print(str(j) + " " + str(t))
``` | instruction | 0 | 52,659 | 8 | 105,318 |
No | output | 1 | 52,659 | 8 | 105,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.
Submitted Solution:
```
def f(m, cnt, y):
global ans, x
if m == 0: return cnt, y
a = int(m ** (1/3))
k1, k2 = a ** 3, (a - 1) ** 3
return max(f(m - k1, cnt + 1, y + k1), f(k1 - k2 - 1, cnt + 1, y + k2))
m = int(input())
ans, x = 0, m
f(m, 0, 0)
print(ans, x)
``` | instruction | 0 | 52,660 | 8 | 105,320 |
No | output | 1 | 52,660 | 8 | 105,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.
Submitted Solution:
```
import math
ans=-1
arr=[1]*100005
def find(x):
global ans
if x<8:
return [x,x]
val=int(x**(1/3))
val=val**3
l=find(x-val)
r=find(val-1)
if 1+l[0]>=r[0]:
ans=val+l[1]
return [1+l[0],ans]
elif 1+l[0]<r[0]:
ans=val-1
return [r[0],ans]
x=int(input())
a=find(x)
print(a[0],a[1])
``` | instruction | 0 | 52,661 | 8 | 105,322 |
No | output | 1 | 52,661 | 8 | 105,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.
Submitted Solution:
```
import math
def get_next(x):
t = (-3 + math.sqrt(12 * x - 3)) / 6.0
t = math.floor(t)
for i in range(max(t - 6, 1), t + 7):
nx = x + i ** 3
if nx < (i + 1) ** 3:
return nx, i
assert(False)
def can_be_lower(cur, to_go, high):
if cur > high:
return False
for i in range(to_go):
cur = get_next(cur)[0]
if cur > high:
return False
return True
def get_highest(cur, to_go, le, high):
rg = 10 ** 5 + 123
while rg - le > 1:
mid = (le + rg) // 2
if can_be_lower(cur + mid ** 3, to_go - 1, high):
le = mid
else:
rg = mid
return cur + le ** 3
level = 0
high = int(input())
cur = 1
while cur <= high:
level += 1
cur = get_next(cur)[0]
cur = 1
for i in range(level - 1):
to_go = level - i - 1
nx, mn = get_next(cur)
# print(cur, nx, mn)
cur = get_highest(cur, to_go, mn, high)
print(level, cur)
``` | instruction | 0 | 52,662 | 8 | 105,324 |
No | output | 1 | 52,662 | 8 | 105,325 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6. | instruction | 0 | 52,663 | 8 | 105,326 |
Tags: binary search, strings, two pointers
Correct Solution:
```
n=int(input())
s=input()
c=set(s)
d={i:0 for i in c}
maks=999999
l=0
for i in range(n):
d[s[i]]+=1
if c!=set():
if s[i] in c:
c.remove(s[i])
if c==set():
while True:
d[s[l]]-=1
if d[s[l]]==0:
c.add(s[l])
l+=1
break
l+=1
maks=min(maks,i-l+2)
print(maks)
``` | output | 1 | 52,663 | 8 | 105,327 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6. | instruction | 0 | 52,664 | 8 | 105,328 |
Tags: binary search, strings, two pointers
Correct Solution:
```
n = int(input())
temp = input()
st=[c for c in temp]
temp=set(st)
nT=len(temp)
s={}
for i in temp:
s[i]=0
currT=set()
i=0
j=0
minL=10**10
for i in range(len(st)):
currT.add(st[i])
s[st[i]]+=1
while j<i and (s[st[j]]>1):
s[st[j]]-=1
j+=1
if len(currT)==nT:
minL=min(minL,i-j+1)
print(minL)
``` | output | 1 | 52,664 | 8 | 105,329 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6. | instruction | 0 | 52,665 | 8 | 105,330 |
Tags: binary search, strings, two pointers
Correct Solution:
```
from collections import *
c=Counter()
ans=n=int(input())
s=input()
k=len(set(s))
i=j=t=0
while j<n:
while len(c)<k and j<n: c[s[j]]+=1; j+=1
while len(c)==k:
if j-i<ans: ans=j-i
c[s[i]]-=1
if c[s[i]]==0: del c[s[i]]
i+=1
print(ans)
``` | output | 1 | 52,665 | 8 | 105,331 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6. | instruction | 0 | 52,666 | 8 | 105,332 |
Tags: binary search, strings, two pointers
Correct Solution:
```
from collections import defaultdict
di = defaultdict(int)
n = int(input())
s = input()
cn = len(set(s))
co = 0
def ad(a):
global co,di
if(di[s[a]] == 0):
co += 1
di[s[a]] += 1
return
def re(a):
global co,di
di[s[a]] -= 1
if(di[s[a]] == 0):
co -= 1
return
ad(0)
po = 0
ma = n
for i in range(n):
while(co < cn):
if(po == n-1):
break
po += 1
ad(po)
if(co == cn):
ma = min(ma,po - i + 1)
re(i)
print(ma)
``` | output | 1 | 52,666 | 8 | 105,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6. | instruction | 0 | 52,667 | 8 | 105,334 |
Tags: binary search, strings, two pointers
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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")
import time
start_time = time.time()
import collections as col
import math
from functools import reduce
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
"""
Suppose we're looking at A[i] = k, then we want to know the longest sequence k+1,... starting to the right of i
If there is no such sequence, the answer is one. Otherwise is it 1 + A[j], where j is the leftmost index such that A[j] = k+1
"""
def solve():
N = getInt()
S = getStr()
targ = len(set(S))
letter_set = set()
letter_count = col.defaultdict(int)
ind = 0
j = 0
best = 10**9
while ind < N:
letter_set.add(S[j])
letter_count[S[j]] += 1
while j+1 < N and len(letter_set) < targ:
j += 1
letter_set.add(S[j])
letter_count[S[j]] += 1
#now we've finally got to a point where all letters are in. we can remove the prefix of letters covered in other parts of the string
while ind < N and letter_count[S[ind]] > 1:
letter_count[S[ind]] -= 1
ind += 1
if len(letter_set) < targ:
break
best = min(best,j-ind+1)
letter_count[S[ind]] -= 1
if letter_count[S[ind]] == 0:
letter_set.remove(S[ind])
ind += 1
if j == N-1:
break
j += 1
return best
#for _ in range(getInt()):
print(solve())
``` | output | 1 | 52,667 | 8 | 105,335 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6. | instruction | 0 | 52,668 | 8 | 105,336 |
Tags: binary search, strings, two pointers
Correct Solution:
```
def solve(s, k ):
d= {}
for i in s:
d[i]=1
c = len(d)
# print('c',c)
d= {}
for i in range(k):
if s[i] in d:
d[s[i]]+=1
else:
d[s[i]]=1
if (len(d)==c):
return True
# print('hello')
dif =0
for i in range(k,n) :
if s[i] in d:
if d[s[i]]==0:
dif-=1
d[s[i]]+=1
d[s[i-k]]-=1
if d[s[i-k]]==0:
dif+=1
else:
d[s[i]]=1
d[s[i-k]]-=1
if d[s[i-k]]==0:
dif+=1
# print('lllll')
if (len(d)-dif==c):
return True
return False
if __name__ == '__main__':
n = int(input())
s = str(input())
low=1
high = n
ans=0
while (low<=high) :
mid=(low+high)//2
k = mid
if solve(s,k):
ans = mid
high = mid-1
else:
low=mid+1
# print(mid)
print(ans)
``` | output | 1 | 52,668 | 8 | 105,337 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6. | instruction | 0 | 52,669 | 8 | 105,338 |
Tags: binary search, strings, two pointers
Correct Solution:
```
n = int(input())
s = input()
D = dict()
A = set()
for i in range(n):
if s[i] not in A:
A.add(s[i])
l = 100001
for i in A:
D[i] = 0
g = 0
c = '0'
for i in range(n):
D[s[i]] += 1
q = 0
if c == '0':
for k in A:
if D[k] == 0:
break
else:
q = 1
if q == 1 or s[i] == c:
for k in range(g,i+1):
D[s[k]] -= 1
if D[s[k]] == 0:
D[s[k]] += 1
l = min(l,i-k+1)
g = max(k,0)
c = s[k]
break
print(l)
``` | output | 1 | 52,669 | 8 | 105,339 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6. | instruction | 0 | 52,670 | 8 | 105,340 |
Tags: binary search, strings, two pointers
Correct Solution:
```
n,s=int(input()),input()
dis = len(set(s))
mp = {}
l,r,m,cnt=0,0,99999999,0
for c in s:
if c not in mp:
mp[c]=0
cnt+=1
mp[c]+=1
#print(cnt)
if cnt == dis:
while mp[s[l]]>1:
mp[s[l]]-=1
l+=1
m = min(m,r-l+1)
r+=1
print(m)
``` | output | 1 | 52,670 | 8 | 105,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Submitted Solution:
```
n = int(input())
flats = input()
ans = n
count = {}
for c in flats:
count[c] = 0
all_char = len(count)
j = 0
exist = 0
for i in range(n):
while j < n and exist < all_char:
if count[flats[j]] == 0:
exist += 1
count[flats[j]] += 1
j += 1
if exist == all_char:
ans = min(ans, j - i)
else:
break
count[flats[i]] -= 1
if count[flats[i]] == 0:
exist -= 1
print(ans)
``` | instruction | 0 | 52,671 | 8 | 105,342 |
Yes | output | 1 | 52,671 | 8 | 105,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Submitted Solution:
```
n = int(input())
s = input()
q = len(set(s))
d = dict()
count = 0
ans = 999999999
j = 0
for i in range(n):
if s[i] not in d:
d[s[i]] = 0
count += 1
d[s[i]] += 1
if count == q:
while d[s[j]] > 1:
d[s[j]] -= 1
j += 1
ans = min(ans, i - j + 1)
print(ans)
``` | instruction | 0 | 52,672 | 8 | 105,344 |
Yes | output | 1 | 52,672 | 8 | 105,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Submitted Solution:
```
n = int(input())
s = input()
d = set()
p = {}
D = 0
for i in s:
if i not in d:
d.add(i)
p[i] = D
D += 1
def calc(k):
P = [0] * D
num = 0
for i in range(n):
if i >= k:
P[p[s[i - k]]] -= 1
if P[p[s[i - k]]] == 0:
num -= 1
if P[p[s[i]]] == 0:
P[p[s[i]]] += 1
num += 1
if num == D:
return True
else:
P[p[s[i]]] += 1
return False
l, r = 0, n
while r - l > 1:
mid = (l + r) // 2
if calc(mid):
r = mid
else:
l = mid
print(r)
``` | instruction | 0 | 52,673 | 8 | 105,346 |
Yes | output | 1 | 52,673 | 8 | 105,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Submitted Solution:
```
import sys
n = int(sys.stdin.readline())
line = sys.stdin.readline()
st = set()
dt = dict()
for x in line:
st.add(x)
st.remove('\n')
ans = n
head = 0
for i in range(n):
x = line[i]
if x not in dt:
dt[x] = 1
else:
dt[x] += 1
while head <= i:
x = line[head]
if x in dt and dt[x] > 1:
dt[x] -= 1
head += 1
else:
break
if len(dt) == len(st):
ans = min(ans, i - head + 1)
print(ans)
``` | instruction | 0 | 52,674 | 8 | 105,348 |
Yes | output | 1 | 52,674 | 8 | 105,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Submitted Solution:
```
n = int(input())
l = input()
i = 0
j = len(l)-1
k = len(l)
while (1==1):
di = 0
if j == i:
break
elif j == i+1 and l[i]==l[j]:
k -=1
break
for p in range (i+1 ,j) :
if l[p]==l[i] :
di = 1
break
elif l[p]==l[j] :
di = -1
break
if l[i] == l[j] and (di == 1 or di == -1):
k -= 2
i += 1
j -= 1
elif l[i] == l[j] and di == 0:
k -= 1
i += 1
j -= 1
elif di == 1 :
k -= 1
i += 1
elif di == -1 :
k -= 1
j -= 1
else :
break
print(k)
``` | instruction | 0 | 52,675 | 8 | 105,350 |
No | output | 1 | 52,675 | 8 | 105,351 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Submitted Solution:
```
n=int(input())
s=input()
dic={}
for i in range(n):
if s[i] not in dic:
dic[s[i]]=1
else:
dic[s[i]]+=1
p1,p2=0,n-1
for i in range(n):
if(dic[s[i]]==1):
dic[s[i]]=0
p1=i
break
else:
dic[s[i]]-=1
for i in range(n-1,-1,-1):
if(dic[s[i]]==1):
dic[s[i]]=0
p2=i
break
else:
dic[s[i]]-=1
print(p2-p1+1)
``` | instruction | 0 | 52,676 | 8 | 105,352 |
No | output | 1 | 52,676 | 8 | 105,353 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Submitted Solution:
```
def main():
n = int(input())
s = input()
d = dict.fromkeys(s, 0)
le, res = len(d), [n]
i = j = 0
try:
while True:
while le:
c = s[i]
if d[c]:
d[c] += 1
else:
d[c] = 1
le -= 1
i += 1
while True:
c = s[j]
if d[c] > 1:
d[c] -= 1
else:
res.append(i - j)
d[c], le = 0, 1
break
j += 1
except IndexError:
print(min(res))
if __name__ == "__main__":
main()
``` | instruction | 0 | 52,677 | 8 | 105,354 |
No | output | 1 | 52,677 | 8 | 105,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Input
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
Output
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
Examples
Input
3
AaA
Output
2
Input
7
bcAAcbc
Output
3
Input
6
aaBCCe
Output
5
Note
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Submitted Solution:
```
a=int(input())
from collections import defaultdict
al=defaultdict(int)
z=input()
count=0
for i in range(len(z)):
if(al[z[i]]==0):
count+=1
al[z[i]]=1
dk=defaultdict(int)
l=0
r=0
ans=[]
dount=0
while(l<=r and r<=len(z)-1):
if(dk[z[r]]==0):
dount+=1
dk[z[r]]+=1
else:
dk[z[r]]+=1
if(dount==count):
dk[z[l]]-=1
ans.append(r-l+1)
l+=1
if(dk[z[l-1]]==0):
dount=dount-1
r+=1
continue;
else:
r+=1
print(min(ans))
``` | instruction | 0 | 52,678 | 8 | 105,356 |
No | output | 1 | 52,678 | 8 | 105,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.
Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.
According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.
The elevator has two commands:
* Go up or down one floor. The movement takes 1 second.
* Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator.
Initially the elevator is empty and is located on the floor 1.
You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees.
The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach.
The employees are given in the order they came to the elevator.
Output
Print a single integer — the minimal possible time in seconds.
Examples
Input
2
3 5
5 3
Output
10
Input
2
5 3
3 5
Output
12
Note
Explaination for the first sample <image> t = 0
<image> t = 2
<image> t = 3
<image> t = 5
<image> t = 6
<image> t = 7
<image> t = 9
<image> t = 10 | instruction | 0 | 52,817 | 8 | 105,634 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
# python3
import sys
from collections import namedtuple
def readline(): return map(int, input().split())
def readlines():
for line in sys.stdin.readlines():
yield map(int, line.split())
class State(namedtuple('State', 'payload time floor')):
def hook(self, pivot, a, b):
lo, up = min(pivot, a, self.floor), max(pivot, a, self.floor)
return tuple(x for x in self.payload if x < lo or up < x) + (b,), \
self.time + abs(self.floor - pivot) + abs(pivot - a)
def choices_to_take_next(self, a, b):
floor = self.floor
payload, time = self.hook(floor, a, b)
if len(payload) < 5:
yield payload, time
if floor > a:
pivots = (x for x in self.payload if x > floor)
elif floor == a:
pivots = ()
else:
pivots = (x for x in self.payload if x < floor)
else:
pivots = self.payload
for pivot in pivots:
yield self.hook(pivot, a, b)
def time_to_get_free(payload, floor):
if payload:
lo, up = min(payload), max(payload)
return abs(lo-up) + min(abs(floor-lo), abs(floor-up))
else:
return 0
def main():
n, = readline()
floor = 1
positions = {(): 0} # empty elevator, time = 0
for (a, b) in readlines():
max_acceptable_time = min(positions.values()) + 16 - abs(floor - a)
new_positions = dict()
for payload, time in positions.items():
state = State(payload, time, floor)
for npayload, ntime in state.choices_to_take_next(a, b):
if ntime <= max_acceptable_time:
npayload = tuple(sorted(npayload))
if new_positions.setdefault(npayload, ntime) > ntime:
new_positions[npayload] = ntime
positions = new_positions
floor = a
return min(t + time_to_get_free(p, floor) for p, t in positions.items()) \
+ 2 * n
print(main())
``` | output | 1 | 52,817 | 8 | 105,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.
Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.
According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.
The elevator has two commands:
* Go up or down one floor. The movement takes 1 second.
* Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator.
Initially the elevator is empty and is located on the floor 1.
You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees.
The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach.
The employees are given in the order they came to the elevator.
Output
Print a single integer — the minimal possible time in seconds.
Examples
Input
2
3 5
5 3
Output
10
Input
2
5 3
3 5
Output
12
Note
Explaination for the first sample <image> t = 0
<image> t = 2
<image> t = 3
<image> t = 5
<image> t = 6
<image> t = 7
<image> t = 9
<image> t = 10
Submitted Solution:
```
# python3
import sys
from itertools import chain
from collections import namedtuple
def readline(): return map(int, input().split())
def readlines():
for line in sys.stdin.readlines():
yield map(int, line.split())
class Position(namedtuple('Position', 'payload time')):
# def __eq__(self, other):
# return self.time == other.time \
# and sorted(self.payload) == sorted(other.payload)
def hook(self, floor, pivot, a, b):
lo, up = min(pivot, a), max(pivot, a)
return Position(tuple(x for x in self.payload if x < lo or up < x)
+ (b,),
self.time + abs(floor - pivot) + abs(pivot - a))
def possibilities_to_take_next(self, floor, a, b):
shortest = self.hook(floor, floor, a, b)
if len(shortest.payload) < 5:
yield shortest
if floor > a:
pivots = (x for x in self.payload if x > floor)
elif floor == a:
pivots = self.payload if len(self.payload) == 4 else ()
else:
pivots = (x for x in self.payload if x < floor)
for pivot in pivots:
possibility = self.hook(floor, pivot, a, b)
yield possibility
def time_to_get_free(self, floor):
if self.payload:
lo, up = min(self.payload), max(self.payload)
return self.time + abs(lo-up) + min(abs(floor-lo), abs(floor-up))
else:
return self.time
def main():
n, = readline()
floor = 1
positions = [Position(payload=(), time=0)]
for (a, b) in readlines():
max_acceptable_time = min(pos.time for pos in positions) \
+ 16 - abs(floor - a)
positions = [
possibility for possibility in chain.from_iterable(
p.possibilities_to_take_next(floor, a, b) for p in positions
) if possibility.time <= max_acceptable_time
]
floor = a
return min(p.time_to_get_free(floor) for p in positions) + 2 * n
print(main())
``` | instruction | 0 | 52,818 | 8 | 105,636 |
No | output | 1 | 52,818 | 8 | 105,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.
Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.
According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.
The elevator has two commands:
* Go up or down one floor. The movement takes 1 second.
* Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator.
Initially the elevator is empty and is located on the floor 1.
You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees.
The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach.
The employees are given in the order they came to the elevator.
Output
Print a single integer — the minimal possible time in seconds.
Examples
Input
2
3 5
5 3
Output
10
Input
2
5 3
3 5
Output
12
Note
Explaination for the first sample <image> t = 0
<image> t = 2
<image> t = 3
<image> t = 5
<image> t = 6
<image> t = 7
<image> t = 9
<image> t = 10
Submitted Solution:
```
# python3
import sys
from itertools import chain
from collections import namedtuple
def readline(): return map(int, input().split())
def readlines():
for line in sys.stdin.readlines():
yield map(int, line.split())
class Position(namedtuple('Position', 'payload time')):
# def __eq__(self, other):
# return self.time == other.time \
# and sorted(self.payload) == sorted(other.payload)
def is_not_full(self):
return len(self.payload) < 4
def take(self, b):
self.payload.append(b)
return self
def free(self, x, y):
x, y = sorted((x, y))
return [s for s in self.payload if not x <= s <= y]
def hook(self, start, pivot, finish):
time = self.time + abs(start - pivot) + abs(pivot - finish)
return Position(self.free(pivot, finish), time)
def possibilities_to_take_next(self, floor, a, b):
pivots = [x for x in self.payload if x > floor] \
if a < floor else \
[x for x in self.payload if x < floor] \
if a > floor else \
[] if self.is_not_full() else list(self.payload)
pivots.append(floor)
for pivot in pivots:
possibility = self.hook(floor, pivot, a)
if possibility.is_not_full():
yield possibility.take(b)
def time_to_get_free(self, floor):
if self.payload:
lo, up = min(self.payload), max(self.payload)
return self.time + abs(lo-up) + min(abs(floor-lo), abs(floor-up))
else:
return self.time
# assert sorted(Position(payload=[1, 2, 3, 3, 4, 5, 5, 6, 7], time=3)
# .free(3, 5)) == [1, 2, 6, 7]
# assert Position(payload=[1, 2, 3, 3, 4, 5, 5, 6, 7], time=3)\
# .hook(4, 2, 6) == Position(payload=[1, 7], time=9)
# assert Position(payload=[1, 5], time=0)\
# .take(9) == Position(payload=[1, 5, 9], time=0)
# assert list(Position(payload=[1, 2, 5], time=0)
# .possibilities_to_take_next(4, 2, 9))\
# == [Position(payload=[1, 9], time=4),
# Position(payload=[1, 5, 9], time=2)]
# assert list(Position(payload=[1, 2, 5], time=0)
# .possibilities_to_take_next(4, 5, 1)) \
# == [Position(payload=[1], time=7),
# Position(payload=[1, 1], time=5),
# Position(payload=[1, 1, 2], time=1)]
def main():
n, = readline()
floor = 1
positions = [Position(payload=[], time=0)]
for (a, b) in readlines():
max_accepted_time = (
min(pos.time for pos in positions)
+ (18 - floor - a if floor > a else floor + a - 2)
)
positions = [
p for p in chain.from_iterable(
p.possibilities_to_take_next(floor, a, b) for p in positions
) if p.time <= max_accepted_time
]
floor = a
return min(pos.time_to_get_free(floor) for pos in positions) + 2 * n
print(main())
``` | instruction | 0 | 52,819 | 8 | 105,638 |
No | output | 1 | 52,819 | 8 | 105,639 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.
Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.
According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.
The elevator has two commands:
* Go up or down one floor. The movement takes 1 second.
* Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator.
Initially the elevator is empty and is located on the floor 1.
You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees.
The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach.
The employees are given in the order they came to the elevator.
Output
Print a single integer — the minimal possible time in seconds.
Examples
Input
2
3 5
5 3
Output
10
Input
2
5 3
3 5
Output
12
Note
Explaination for the first sample <image> t = 0
<image> t = 2
<image> t = 3
<image> t = 5
<image> t = 6
<image> t = 7
<image> t = 9
<image> t = 10
Submitted Solution:
```
numOfEmp = int(input())
listOfEmp=[]
for i in range(numOfEmp):
listOfEmp.append(tuple(map(int,input().split())))
elev= 1
time =0
for i in range(0,len(listOfEmp)):
if(i!=0 and listOfEmp[i][0]==listOfEmp[i-1][0]):
fin=listOfEmp[i][1]-elev
if fin<0:
fin =fin*-1
if(listOfEmp[i][1]!=listOfEmp[i-1][1]):
time=time+1
time = time +(fin)
if(listOfEmp[i][1]<listOfEmp[i-1][1]):
time = time-(listOfEmp[i-1][1]-listOfEmp[i][1])
elev =listOfEmp[i][1]
else:
ini= listOfEmp[i][0]-elev
if ini<0:
ini = ini*-1
time= time +(ini)
elev=listOfEmp[i][0]
fin=listOfEmp[i][1]-elev
if fin<0:
fin =fin*-1
time = time +(fin)
time = time+2
elev =listOfEmp[i][1]
print(time)
``` | instruction | 0 | 52,820 | 8 | 105,640 |
No | output | 1 | 52,820 | 8 | 105,641 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.
Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.
According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.
The elevator has two commands:
* Go up or down one floor. The movement takes 1 second.
* Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator.
Initially the elevator is empty and is located on the floor 1.
You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees.
The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach.
The employees are given in the order they came to the elevator.
Output
Print a single integer — the minimal possible time in seconds.
Examples
Input
2
3 5
5 3
Output
10
Input
2
5 3
3 5
Output
12
Note
Explaination for the first sample <image> t = 0
<image> t = 2
<image> t = 3
<image> t = 5
<image> t = 6
<image> t = 7
<image> t = 9
<image> t = 10
Submitted Solution:
```
numOfEmp = int(input())
listOfEmp=[]
for i in range(numOfEmp):
listOfEmp.append(tuple(map(int,input().split())))
elev= 1
time =0
for i in range(0,len(listOfEmp)):
if(i!=0&listOfEmp[i][0]==listOfEmp[i-1][0]):
fin=listOfEmp[i][1]-elev
if fin<0:
fin =fin*-1
time = time +(fin)
elev =listOfEmp[i][1]
else:
ini= listOfEmp[i][0]-elev
if ini<0:
ini = ini*-1
time= time +(ini)
elev=listOfEmp[i][0]
fin=listOfEmp[i][1]-elev
if fin<0:
fin =fin*-1
time = time +(fin)
time = time+2
elev =listOfEmp[i][1]
print(time)
``` | instruction | 0 | 52,821 | 8 | 105,642 |
No | output | 1 | 52,821 | 8 | 105,643 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible. | instruction | 0 | 53,171 | 8 | 106,342 |
Tags: constructive algorithms, math
Correct Solution:
```
n=int(input())
arr=[int(i) for i in input().split()]
for i in arr:
if i%14<=6 and i>14 and i%14>0:
print('YES')
else:
print('NO')
``` | output | 1 | 53,171 | 8 | 106,343 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible. | instruction | 0 | 53,173 | 8 | 106,346 |
Tags: constructive algorithms, math
Correct Solution:
```
n = int(input())
for x in map(int, input().split()):
print("YES" if x > 14 and x % 14 > 0 and x % 14 <= 6 else "NO")
``` | output | 1 | 53,173 | 8 | 106,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible. | instruction | 0 | 53,174 | 8 | 106,348 |
Tags: constructive algorithms, math
Correct Solution:
```
t = int(input())
x = list(map(int, input().split()))
for s in x:
if 1 <= s%14 <= 6 and s//14 >= 1:
print("YES")
else:
print("NO")
``` | output | 1 | 53,174 | 8 | 106,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible. | instruction | 0 | 53,175 | 8 | 106,350 |
Tags: constructive algorithms, math
Correct Solution:
```
n = int(input())
l = []
l = map(int, input().split())
for i in l:
x = False
if i < 15:
x=False
else:
for n in range (1,7):
if ((i-n)%14==0):
x=True
if (x):
print("YES")
else:
print("NO")
``` | output | 1 | 53,175 | 8 | 106,351 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.