output_description stringlengths 15 956 | submission_id stringlengths 10 10 | status stringclasses 3 values | problem_id stringlengths 6 6 | input_description stringlengths 9 2.55k | attempt stringlengths 1 13.7k | problem_description stringlengths 7 5.24k | samples stringlengths 2 2.72k |
|---|---|---|---|---|---|---|---|
For each print command, print a string in a line. | s283416472 | Accepted | p02422 | In the first line, a string $str$ is given. $str$ consists of lowercase
letters. In the second line, the number of commands q is given. In the next q
lines, each command is given in the above mentioned format. | a = input()
b = int(input())
while b > 0:
tmp = input().split(" ")
if tmp[0] == "replace":
a = a[: int(tmp[1])] + tmp[3] + a[int(tmp[2]) + 1 :]
if tmp[0] == "reverse":
tmp2 = "".join(list(a)[int(tmp[1]) : int(tmp[2]) + 1])[::-1]
a = a[: int(tmp[1])] + tmp2 + a[int(tmp[2]) + 1 :]
if tmp[0] == "print":
print(a[int(tmp[1]) : int(tmp[2]) + 1])
b -= 1
| Transformation
Write a program which performs a sequence of commands to a given string $str$.
The command is one of:
* print a b: print from the a-th character to the b-th character of $str$
* reverse a b: reverse from the a-th character to the b-th character of $str$
* replace a b p: replace from the a-th character to the b-th character of $str$ with p
Note that the indices of $str$ start with 0. | [{"input": "abcde\n 3\n replace 1 3 xyz\n reverse 0 2\n print 1 4", "output": "xaze"}, {"input": "xyz\n 3\n print 0 2\n replace 0 2 abc\n print 0 2", "output": "xyz\n abc"}] |
For each print command, print a string in a line. | s467443744 | Accepted | p02422 | In the first line, a string $str$ is given. $str$ consists of lowercase
letters. In the second line, the number of commands q is given. In the next q
lines, each command is given in the above mentioned format. | # 1st line
input_str = input().strip()
# 2nd line
command_max_times = int(input().strip())
command_cnt = 0
while command_cnt < command_max_times:
command_cnt = command_cnt + 1
input_line = input().strip().split(" ")
input_command = input_line[0]
input_sta = int(input_line[1])
input_end = int(input_line[2])
if input_command == "print":
print(input_str[input_sta : input_end + 1])
elif input_command == "replace":
str_replace = input_line[3]
input_str = input_str[:input_sta] + str_replace + input_str[input_end + 1 :]
elif input_command == "reverse":
str_temp = input_str[input_sta : input_end + 1]
input_str = input_str[:input_sta] + str_temp[::-1] + input_str[input_end + 1 :]
| Transformation
Write a program which performs a sequence of commands to a given string $str$.
The command is one of:
* print a b: print from the a-th character to the b-th character of $str$
* reverse a b: reverse from the a-th character to the b-th character of $str$
* replace a b p: replace from the a-th character to the b-th character of $str$ with p
Note that the indices of $str$ start with 0. | [{"input": "abcde\n 3\n replace 1 3 xyz\n reverse 0 2\n print 1 4", "output": "xaze"}, {"input": "xyz\n 3\n print 0 2\n replace 0 2 abc\n print 0 2", "output": "xyz\n abc"}] |
For each print command, print a string in a line. | s371083198 | Accepted | p02422 | In the first line, a string $str$ is given. $str$ consists of lowercase
letters. In the second line, the number of commands q is given. In the next q
lines, each command is given in the above mentioned format. | # coding: utf-8
# Here your code !
def operate_string():
(method, i_first, i_last, str_new) = (
"method",
"i_first",
"i_last",
"replace string",
)
# load data
operations = []
try:
string = input().rstrip()
_ = input()
while True:
line = input().rstrip().split()
operations.append(
{method: line[0], i_first: int(line[1]), i_last: int(line[2])}
)
if len(line) > 3:
operations[-1].update({str_new: line[3]})
except EOFError:
pass
except:
return __inputError()
# operate string
for ope in operations:
if ope[method] == "print":
print(string[ope[i_first] : ope[i_last] + 1])
elif ope[method] == "reverse":
string = reverse_string_by_index(string, ope[i_first], ope[i_last])
elif ope[method] == "replace":
string = replace_string_by_index(
string, ope[str_new], ope[i_first], ope[i_last]
)
else:
return __inputError()
def replace_string_by_index(str_raw, str_new, i_first, i_last):
pre_post_info = __set_pre_post_string(str_raw, i_first, i_last)
if pre_post_info["invalid index"]:
return str_raw
return pre_post_info["pre"] + str_new + pre_post_info["post"]
def reverse_string_by_index(str_raw, i_first, i_last):
pre_post_info = __set_pre_post_string(str_raw, i_first, i_last)
if pre_post_info["invalid index"]:
return str_raw
str_reversed = str_raw[i_last : i_first - 1 : -1]
if i_first == 0:
str_reversed = str_raw[i_last::-1]
return pre_post_info["pre"] + str_reversed + pre_post_info["post"]
def __set_pre_post_string(str_raw, i_first, i_last):
info = {"pre": "", "post": "", "invalid index": False}
info["pre"] = str_raw[:i_first]
info["post"] = "" if (i_last == -1) else str_raw[i_last + 1 :]
info["invalid index"] = len(info["pre"]) + len(info["post"]) >= len(str_raw)
return info
def __inputError():
print("input Error")
return -1
def __Test_reverse_string_by_index(lists):
# list[index] = [str_raw, i_first, i_last]
for item in lists:
print(reverse_string_by_index(item[0], item[1], item[2]))
def __Test_replace_string_by_index(lists):
# list[index] = [str_raw, str_new, i_first, i_last]
for item in lists:
print(replace_string_by_index(item[0], item[1], item[2], item[3]))
# test
if __name__ == "__main__":
operate_string()
"""
__Test_replace_string_by_index ([ ["abc","A",0,1], ["abc","A",-5,-1], ["abc","",1,1], ["","A",0,0], ["abc","A",5,6] ])
#expected results: "Ac", "A", "ac", ""(string error), "abc"(index error)
__Test_reverse_string_by_index ([ ["abc",0,2], ["abc",-5,-1], ["abc",3,3] ])
#expected results: "cba", "cba", "abc"(index error)
"""
| Transformation
Write a program which performs a sequence of commands to a given string $str$.
The command is one of:
* print a b: print from the a-th character to the b-th character of $str$
* reverse a b: reverse from the a-th character to the b-th character of $str$
* replace a b p: replace from the a-th character to the b-th character of $str$ with p
Note that the indices of $str$ start with 0. | [{"input": "abcde\n 3\n replace 1 3 xyz\n reverse 0 2\n print 1 4", "output": "xaze"}, {"input": "xyz\n 3\n print 0 2\n replace 0 2 abc\n print 0 2", "output": "xyz\n abc"}] |
For each print command, print a string in a line. | s889302700 | Accepted | p02422 | In the first line, a string $str$ is given. $str$ consists of lowercase
letters. In the second line, the number of commands q is given. In the next q
lines, each command is given in the above mentioned format. | import copy
function = 0
start = 1
end = 2
replaceStr = 3
reverseStart = 0
reverseEnd = 0
str = 3
reverseTarget = []
reversedStr = []
inStr = list(input())
outStr = copy.deepcopy(inStr)
commandNumber = int(input())
for currentNumber in range(commandNumber):
command = input().split(" ") # [commandName, start, end (replaceStr)]
if command[function] == "print":
printStart = int(command[start])
printEnd = int(command[end])
print("".join(outStr[printStart : printEnd + 1]))
elif command[function] == "reverse":
reverseStart = int(command[start])
reverseEnd = int(command[end])
reverseTarget.append(outStr[reverseStart : reverseEnd + 1])
reversedStr = reverseTarget[-1][::-1]
outStr[reverseStart : reverseEnd + 1] = reversedStr
elif command[function] == "replace":
replaceStart = int(command[start])
replaceEnd = int(command[end])
replaceStr = list(command[str])
outStr[replaceStart : replaceEnd + 1] = replaceStr
| Transformation
Write a program which performs a sequence of commands to a given string $str$.
The command is one of:
* print a b: print from the a-th character to the b-th character of $str$
* reverse a b: reverse from the a-th character to the b-th character of $str$
* replace a b p: replace from the a-th character to the b-th character of $str$ with p
Note that the indices of $str$ start with 0. | [{"input": "abcde\n 3\n replace 1 3 xyz\n reverse 0 2\n print 1 4", "output": "xaze"}, {"input": "xyz\n 3\n print 0 2\n replace 0 2 abc\n print 0 2", "output": "xyz\n abc"}] |
For each print command, print a string in a line. | s829417970 | Accepted | p02422 | In the first line, a string $str$ is given. $str$ consists of lowercase
letters. In the second line, the number of commands q is given. In the next q
lines, each command is given in the above mentioned format. | def souhei(a, b):
c = int(a)
d = int(b)
return [c, d]
moji = input()
moji = list(moji)
P = int(input())
for pp in range(P):
some = list(input().split())
if some[0] == "print":
some[1], some[2] = souhei(some[1], some[2])
for a in range(some[1], some[2] + 1):
if a == some[2]:
print(moji[a])
else:
print(moji[a], end="")
elif some[0] == "reverse":
some[1], some[2] = souhei(some[1], some[2])
nn = 0
m = int((some[1] + some[2]) / 2)
for bb in range(some[1], m + 1):
X = moji[bb]
moji[bb] = moji[some[2] - nn]
moji[some[2] - nn] = X
nn += 1
elif some[0] == "replace":
some[1], some[2] = souhei(some[1], some[2])
g = some[3]
g = list(g)
n = 0
for oo in range(some[1], some[2] + 1):
moji[oo] = g[n]
n += 1
| Transformation
Write a program which performs a sequence of commands to a given string $str$.
The command is one of:
* print a b: print from the a-th character to the b-th character of $str$
* reverse a b: reverse from the a-th character to the b-th character of $str$
* replace a b p: replace from the a-th character to the b-th character of $str$ with p
Note that the indices of $str$ start with 0. | [{"input": "abcde\n 3\n replace 1 3 xyz\n reverse 0 2\n print 1 4", "output": "xaze"}, {"input": "xyz\n 3\n print 0 2\n replace 0 2 abc\n print 0 2", "output": "xyz\n abc"}] |
For each print command, print a string in a line. | s153076118 | Accepted | p02422 | In the first line, a string $str$ is given. $str$ consists of lowercase
letters. In the second line, the number of commands q is given. In the next q
lines, each command is given in the above mentioned format. | s = list(input())
n = int(input())
for i in range(n):
d = input().split(" ")
if d[0] == "replace":
a = int(d[1])
b = int(d[2])
c = list(d[3])
k = 0
for j in range(a, b + 1):
s[j] = c[k]
k += 1
elif d[0] == "reverse":
a = int(d[1])
b = int(d[2])
c = list(s)
k = b
for j in range(a, b + 1):
s[j] = c[k]
k -= 1
else:
a = int(d[1])
b = int(d[2])
for j in range(a, b + 1):
print(s[j], end="")
print("")
| Transformation
Write a program which performs a sequence of commands to a given string $str$.
The command is one of:
* print a b: print from the a-th character to the b-th character of $str$
* reverse a b: reverse from the a-th character to the b-th character of $str$
* replace a b p: replace from the a-th character to the b-th character of $str$ with p
Note that the indices of $str$ start with 0. | [{"input": "abcde\n 3\n replace 1 3 xyz\n reverse 0 2\n print 1 4", "output": "xaze"}, {"input": "xyz\n 3\n print 0 2\n replace 0 2 abc\n print 0 2", "output": "xyz\n abc"}] |
For each print command, print a string in a line. | s170225493 | Accepted | p02422 | In the first line, a string $str$ is given. $str$ consists of lowercase
letters. In the second line, the number of commands q is given. In the next q
lines, each command is given in the above mentioned format. | line = input()
n = int(input())
array = [[i for i in input().split()] for i in range(n)]
for i in range(n):
if array[i][0] == "print":
print(line[int(array[i][1]) : int(array[i][2]) + 1])
elif array[i][0] == "reverse":
if array[i][1] != "0":
reline = line[int(array[i][2]) : int(array[i][1]) - 1 : -1]
else:
reline = line[int(array[i][2]) :: -1]
revara = list(line)
for i2 in range(len(reline)):
revara[int(array[i][1]) + i2] = reline[i2]
for i2 in range(len(revara)):
if i2 == 0:
line = revara[i2]
else:
line += revara[i2]
elif array[i][0] == "replace":
repara = list(line)
inpara = list(array[i][3])
for i2 in range(len(inpara)):
repara[int(array[i][1]) + i2] = inpara[i2]
for i2 in range(len(repara)):
if i2 == 0:
line = repara[i2]
else:
line += repara[i2]
| Transformation
Write a program which performs a sequence of commands to a given string $str$.
The command is one of:
* print a b: print from the a-th character to the b-th character of $str$
* reverse a b: reverse from the a-th character to the b-th character of $str$
* replace a b p: replace from the a-th character to the b-th character of $str$ with p
Note that the indices of $str$ start with 0. | [{"input": "abcde\n 3\n replace 1 3 xyz\n reverse 0 2\n print 1 4", "output": "xaze"}, {"input": "xyz\n 3\n print 0 2\n replace 0 2 abc\n print 0 2", "output": "xyz\n abc"}] |
For each print command, print a string in a line. | s880205653 | Wrong Answer | p02422 | In the first line, a string $str$ is given. $str$ consists of lowercase
letters. In the second line, the number of commands q is given. In the next q
lines, each command is given in the above mentioned format. | str = input()
q = eval(input())
command = []
replace = []
numdata = []
for i in range(q):
x = input()
if "replace" in x:
a, b, c, d = x.split()
replace.append(d)
numdata.append((int(b), int(c)))
else:
a, b, c = x.split()
numdata.append((int(b), int(c)))
command.append(a)
Re = iter(replace)
for i in range(q):
if command[i] == "print":
print(str[numdata[i][0] : numdata[i][1] + 1])
elif command[i] == "reverse":
str = (
str[: numdata[i][0]]
+ str[numdata[i][1] : numdata[i][0] - 1 : -1]
+ str[numdata[i][1] + 1 :]
)
else:
str = str[: numdata[i][0]] + next(Re) + str[numdata[i][1] + 1 :]
| Transformation
Write a program which performs a sequence of commands to a given string $str$.
The command is one of:
* print a b: print from the a-th character to the b-th character of $str$
* reverse a b: reverse from the a-th character to the b-th character of $str$
* replace a b p: replace from the a-th character to the b-th character of $str$ with p
Note that the indices of $str$ start with 0. | [{"input": "abcde\n 3\n replace 1 3 xyz\n reverse 0 2\n print 1 4", "output": "xaze"}, {"input": "xyz\n 3\n print 0 2\n replace 0 2 abc\n print 0 2", "output": "xyz\n abc"}] |
For each query with T_i=2, 3, print the answer.
* * * | s573072522 | Wrong Answer | p02567 | Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i | from copy import copy
class Seg_Tree:
def __init__(self, init_list, init_value, func=min):
il_len = len(init_list)
r = 1
while il_len > r:
r *= 2
self.tree = (
[0 for i in range(r - 1)]
+ copy(init_list)
+ [init_value for i in range(r - il_len)]
)
self.func = func
self.len = r
self.init_value = init_value
for i in range(r - 2, -1, -1):
self.tree[i] = self.func(self.tree[i * 2 + 1], self.tree[i * 2 + 2])
def update(self, x, value):
x += self.len - 1
self.tree[x] = value
x = (x - 1) // 2
while x >= 0:
self.tree[x] = self.func(self.tree[x * 2 + 1], self.tree[x * 2 + 2])
x = (x - 1) // 2
def query(self, l, r, x=0):
xl = x
xr = x
while xl < r - 1:
xl, xr = xl * 2 + 1, xr * 2 + 2
if xr < l or r < xl:
return self.init_value
elif l <= xl and xr <= r:
return self.tree[x]
else:
return self.func(self.query(l, r, x * 2 + 1), self.query(l, r, x * 2 + 2))
n, q = map(int, input().split())
a = list(map(int, input().split()))
st = Seg_Tree(a, -1, max)
for i in range(q):
qu = list(map(int, input().split()))
if qu[0] == 1:
st.update(qu[1] - 1, qu[2])
elif qu[0] == 2:
print(st.query(qu[1] - 1, qu[2] - 1))
else:
l, r = qu[1] - 2, n
while r - l != 1:
t = (l + r) // 2
v = st.query(qu[1] - 1, t)
if v >= qu[2]:
r = t
else:
l = t
print(r + 1)
| Statement
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries
of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead. | [{"input": "5 5\n 1 2 3 2 1\n 2 1 5\n 3 2 3\n 1 3 1\n 2 2 4\n 3 1 3", "output": "3\n 3\n 2\n 6\n \n\n * First query: Print 3, which is the maximum of (A_1,A_2,A_3,A_4,A_5)=(1,2,3,2,1).\n * Second query: Since 3>A_2, j=2 does not satisfy the condition\uff0eSince 3 \\leq A_3, print j=3.\n * Third query: Replace the value of A_3 with 1. It becomes A=(1,2,1,2,1).\n * Fourth query: Print 2, which is the maximum of (A_2,A_3,A_4)=(2,1,2).\n * Fifth query: Since there is no j that satisfies the condition, print j=N+1=6."}] |
For each query with T_i=2, 3, print the answer.
* * * | s133004893 | Wrong Answer | p02567 | Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i | from sys import stdin
class SegmentTree:
_op = None
_e = None
_size = None
_offset = None
_data = None
def __init__(self, size, op, e):
self._op = op
self._e = e
self._size = size
t = 1
while t < size:
t *= 2
self._offset = t - 1
self._data = [0] * (t * 2 - 1)
def build(self, iterable):
op = self._op
data = self._data
data[self._offset : self._offset + self._size] = iterable
for i in range(self._offset - 1, -1, -1):
data[i] = op(data[i * 2 + 1], data[i * 2 + 2])
def update(self, index, value):
op = self._op
data = self._data
i = self._offset + index
data[i] = value
while i >= 1:
i = (i - 1) // 2
data[i] = op(data[i * 2 + 1], data[i * 2 + 2])
def query(self, start, stop):
def iter_segments(data, l, r):
while l < r:
if l & 1 == 0:
yield data[l]
if r & 1 == 0:
yield data[r - 1]
l = l // 2
r = (r - 1) // 2
op = self._op
it = iter_segments(self._data, start + self._offset, stop + self._offset)
result = self._e
for e in it:
result = op(result, e)
return result
readline = stdin.readline
N, Q = map(int, readline().split())
A = list(map(int, readline().split()))
st = SegmentTree(N - 1, max, -1)
st.build(A)
result = []
for _ in range(Q):
q = readline()
if q[0] in "13":
T, X, V = map(int, q.split())
if T == 1:
st.update(X - 1, V)
elif T == 3:
ok = N + 1
ng = X - 1
while abs(ng - ok) > 1:
m = (ok + ng) // 2
if st.query(0, m) > V:
ok = m
else:
ng = m
result.append(ok)
elif q[0] == "2":
T, L, R = map(int, q.split())
result.append(st.query(L - 1, R))
print(*result, sep="\n")
| Statement
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries
of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead. | [{"input": "5 5\n 1 2 3 2 1\n 2 1 5\n 3 2 3\n 1 3 1\n 2 2 4\n 3 1 3", "output": "3\n 3\n 2\n 6\n \n\n * First query: Print 3, which is the maximum of (A_1,A_2,A_3,A_4,A_5)=(1,2,3,2,1).\n * Second query: Since 3>A_2, j=2 does not satisfy the condition\uff0eSince 3 \\leq A_3, print j=3.\n * Third query: Replace the value of A_3 with 1. It becomes A=(1,2,1,2,1).\n * Fourth query: Print 2, which is the maximum of (A_2,A_3,A_4)=(2,1,2).\n * Fifth query: Since there is no j that satisfies the condition, print j=N+1=6."}] |
For each query with T_i=2, 3, print the answer.
* * * | s638369412 | Accepted | p02567 | Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i | #!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10**9 + 1 # sys.maxsize # float("inf")
MOD = 10**9 + 7
def debug(*x):
print(*x, file=sys.stderr)
# Segment Tree
def set_depth(depth):
global DEPTH, SEGTREE_SIZE, NONLEAF_SIZE
DEPTH = depth
SEGTREE_SIZE = 1 << DEPTH
NONLEAF_SIZE = 1 << (DEPTH - 1)
def set_width(width):
global WIDTH
WIDTH = width
set_depth((width - 1).bit_length() + 1)
def point_set(table, pos, value, binop):
pos = pos + NONLEAF_SIZE
table[pos] = value
while pos > 1:
pos >>= 1
table[pos] = binop(
table[pos * 2],
table[pos * 2 + 1],
)
def range_reduce(table, left, right, binop, unity):
ret_left = unity
ret_right = unity
left += SEGTREE_SIZE // 2
right += SEGTREE_SIZE // 2
while left < right:
if left & 1:
ret_left = binop(ret_left, table[left])
left += 1
if right & 1:
right -= 1
ret_right = binop(table[right], ret_right)
left //= 2
right //= 2
return binop(ret_left, ret_right)
def bisect_left(table, left, right, value):
left += NONLEAF_SIZE
right += NONLEAF_SIZE
left_left = None
right_left = None
while left < right:
if left & 1:
if left_left is None and table[left] >= value:
left_left = left
left += 1
if right & 1:
if table[right - 1] >= value:
right_left = right - 1
left >>= 1
right >>= 1
if left_left is not None:
pos = left_left
while pos < NONLEAF_SIZE:
if table[2 * pos] >= value:
pos = 2 * pos
else:
pos = 2 * pos + 1
return pos - NONLEAF_SIZE
elif right_left is not None:
pos = right_left
while pos < NONLEAF_SIZE:
if table[2 * pos] >= value:
pos = 2 * pos
else:
pos = 2 * pos + 1
return pos - NONLEAF_SIZE
else:
return WIDTH
def full_up(table, binop):
for i in range(NONLEAF_SIZE - 1, 0, -1):
table[i] = binop(table[2 * i], table[2 * i + 1])
def main():
N, Q = map(int, input().split())
AS = list(map(int, input().split()))
set_width(N)
table = [0] * SEGTREE_SIZE
table[NONLEAF_SIZE : NONLEAF_SIZE + len(AS)] = AS
full_up(table, max)
for _q in range(Q):
q, x, y = map(int, input().split())
if q == 1:
# update
point_set(table, x - 1, y, max)
elif q == 2:
# find
print(range_reduce(table, x - 1, y, max, -INF))
else:
print(bisect_left(table, x - 1, N, y) + 1)
# tests
T1 = """
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
3
3
2
6
"""
def _test():
import doctest
doctest.testmod()
g = globals()
for k in sorted(g):
if k.startswith("TEST_"):
doctest.run_docstring_examples(g[k], g, name=k)
def as_input(s):
"use in test, use given string as input file"
import io
f = io.StringIO(s.strip())
g = globals()
g["input"] = lambda: bytes(f.readline(), "ascii")
g["read"] = lambda: bytes(f.read(), "ascii")
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
print("testing")
_test()
sys.exit()
main()
| Statement
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries
of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead. | [{"input": "5 5\n 1 2 3 2 1\n 2 1 5\n 3 2 3\n 1 3 1\n 2 2 4\n 3 1 3", "output": "3\n 3\n 2\n 6\n \n\n * First query: Print 3, which is the maximum of (A_1,A_2,A_3,A_4,A_5)=(1,2,3,2,1).\n * Second query: Since 3>A_2, j=2 does not satisfy the condition\uff0eSince 3 \\leq A_3, print j=3.\n * Third query: Replace the value of A_3 with 1. It becomes A=(1,2,1,2,1).\n * Fourth query: Print 2, which is the maximum of (A_2,A_3,A_4)=(2,1,2).\n * Fifth query: Since there is no j that satisfies the condition, print j=N+1=6."}] |
For each query with T_i=2, 3, print the answer.
* * * | s762249555 | Wrong Answer | p02567 | Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i | mycode = r"""
# distutils: language=c++
# cython: language_level=3, boundscheck=False, wraparound=False, cdivision=True
ctypedef long long LL
# cython: cdivision=True
from libc.stdio cimport scanf
from libcpp.vector cimport vector
ctypedef vector[LL] vec
cdef class SegmentTree():
cdef LL num,n
cdef vec tree
def __init__(self,vec A):
cdef LL n,i
n = A.size()
self.n = n
self.num = 1 << (n-1).bit_length()
self.tree = vec(2*self.num,0)
for i in range(n):
self.tree[self.num + i] = A[i]
for i in range(self.num-1,0,-1):
self.tree[i] = max(self.tree[2*i],self.tree[2*i+1])
cdef void update(self,LL k,LL x):
k += self.num
self.tree[k] = x
while k>1:
self.tree[k>>1] = max(self.tree[k],self.tree[k^1])
k >>= 1
cdef LL query(self,LL l,LL r):
cdef LL res
res = 0
l += self.num
r += self.num
while l<r:
if l&1:
res = max(res,self.tree[l])
l += 1
if r&1:
res = max(res,self.tree[r-1])
l >>= 1
r >>= 1
return res
cdef LL bisect_l(self,LL l,LL r,LL x):
cdef LL Lmin,Rmin,pos
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l&1:
if self.tree[l] >= x and Lmin == -1:
Lmin = l
l += 1
if r&1:
if self.tree[r] >= x:
Rmin = r
l >>= 1
r >>= 1
if Lmin!=-1:
pos = Lmin
while pos<self.num:
if self.tree[2*pos] >= x:
pos = 2*pos
else:
pos = 2*pos + 1
return pos-self.num
elif Rmin!=-1:
pos = Rmin
while pos<self.num:
if self.tree[2*pos] >= x:
pos = 2*pos
else:
pos = 2*pos + 1
return pos-self.num
else:
return self.n
cdef LL N,Q,i
cdef vec A
scanf("%lld %lld",&N,&Q)
A = vec(N,-1)
for i in range(N):
scanf("%lld",&A[i])
cdef SegmentTree S = SegmentTree(A)
cdef LL t,x,v
for i in range(Q):
scanf("%lld %lld %lld",&t,&x,&v)
if t==1:
S.update(x-1,v)
elif t==2:
print(S.query(x-1,v))
else:
print(S.bisect_l(x-1,N,v)+1)
"""
import sys
import os
if sys.argv[-1] == "ONLINE_JUDGE": # コンパイル時
with open("mycode.pyx", "w") as f:
f.write(mycode)
os.system("cythonize -i -3 -b mycode.pyx")
import mycode
| Statement
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries
of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead. | [{"input": "5 5\n 1 2 3 2 1\n 2 1 5\n 3 2 3\n 1 3 1\n 2 2 4\n 3 1 3", "output": "3\n 3\n 2\n 6\n \n\n * First query: Print 3, which is the maximum of (A_1,A_2,A_3,A_4,A_5)=(1,2,3,2,1).\n * Second query: Since 3>A_2, j=2 does not satisfy the condition\uff0eSince 3 \\leq A_3, print j=3.\n * Third query: Replace the value of A_3 with 1. It becomes A=(1,2,1,2,1).\n * Fourth query: Print 2, which is the maximum of (A_2,A_3,A_4)=(2,1,2).\n * Fifth query: Since there is no j that satisfies the condition, print j=N+1=6."}] |
For each query with T_i=2, 3, print the answer.
* * * | s039792833 | Accepted | p02567 | Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i | mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, A, initialize=True, segfunc=min, ident=2000000000):
self.N = len(A)
self.LV = (self.N - 1).bit_length()
self.N0 = 1 << self.LV
self.segfunc = segfunc
self.ident = ident
if initialize:
self.data = (
[self.ident] * self.N0 + A + [self.ident] * (self.N0 - self.N)
)
for i in range(self.N0 - 1, 0, -1):
self.data[i] = segfunc(self.data[i * 2], self.data[i * 2 + 1])
else:
self.data = [self.ident] * (self.N0 * 2)
def update(self, i, x):
i += self.N0 - 1
self.data[i] = x
for _ in range(self.LV):
i >>= 1
self.data[i] = self.segfunc(self.data[i * 2], self.data[i * 2 + 1])
# open interval [l, r)
def query(self, l, r):
l += self.N0 - 1
r += self.N0 - 1
ret_l = self.ident
ret_r = self.ident
while l < r:
if l & 1:
ret_l = self.segfunc(ret_l, self.data[l])
l += 1
if r & 1:
ret_r = self.segfunc(self.data[r - 1], ret_r)
r -= 1
l >>= 1
r >>= 1
return self.segfunc(ret_l, ret_r)
# return smallest i(l <= i < r) s.t. check(A[i]) == True
def binsearch(self, l, r, check):
if not check(self.query(l, r)):
return r
l += self.N0 - 1
val = self.ident
while True:
if check(self.segfunc(val, self.data[l])):
break
if l & 1:
val = self.segfunc(val, self.data[l])
l += 1
l >>= 1
while l < self.N0:
newval = self.segfunc(val, self.data[l * 2])
if not check(newval):
val = newval
l = (l << 1) + 1
else:
l <<= 1
return l - self.N0 + 1
def check(val):
return val >= v
N, Q = map(int, input().split())
A = list(map(int, input().split()))
ST = SegmentTree(A, segfunc=max, ident=-2000000000)
for _ in range(Q):
t, x, v = map(int, input().split())
if t == 1:
ST.update(x, v)
elif t == 2:
l = x
r = v + 1
print(ST.query(l, r))
else:
print(ST.binsearch(x, N + 1, check))
if __name__ == "__main__":
main()
| Statement
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries
of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead. | [{"input": "5 5\n 1 2 3 2 1\n 2 1 5\n 3 2 3\n 1 3 1\n 2 2 4\n 3 1 3", "output": "3\n 3\n 2\n 6\n \n\n * First query: Print 3, which is the maximum of (A_1,A_2,A_3,A_4,A_5)=(1,2,3,2,1).\n * Second query: Since 3>A_2, j=2 does not satisfy the condition\uff0eSince 3 \\leq A_3, print j=3.\n * Third query: Replace the value of A_3 with 1. It becomes A=(1,2,1,2,1).\n * Fourth query: Print 2, which is the maximum of (A_2,A_3,A_4)=(2,1,2).\n * Fifth query: Since there is no j that satisfies the condition, print j=N+1=6."}] |
Print `First` if Takahashi wins; print `Second` if Aoki wins.
* * * | s876929770 | Runtime Error | p03726 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1} | """
Writer: SPD_9X2
https://atcoder.jp/contests/agc014/tasks/agc014_d
白にしか隣接しない白を作れれば勝ちである
黒は、直前に置かれた白に対して対策するような動きをする羽目になる
距離2の葉の対があったら100%可能
ある時点での残りの森を考える(残りのどの点も黒が隣接していないとする)
葉に白を置く→葉において阻止
葉に隣接する点にしろを置く→葉において阻止
それ以外の点は、置いたら横に置くだけ(葉ではないので、隣接頂点が存在する)
なので、十分性もおk?
距離2の葉が存在するかだけを判定すればよさそう
"""
N = int(input())
lis = [[] for i in range(N)]
for i in range(N - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
lis[a].append(b)
lis[b].append(a)
import sys
sys.setrecursionlimit(500000)
if N == 2:
print("Second")
sys.exit
def dfs(v, p):
if len(lis[v]) == 1:
return 1
pl = 0
for nex in lis[v]:
if nex != p:
pl += dfs(nex, v)
if pl >= 2:
print("First")
sys.exit()
return 0
fi = None
for i in range(N):
if len(lis[i]) > 1:
fi = i
break
dfs(fi, fi)
print("Second")
| Statement
There is a tree with N vertices numbered 1 through N. The i-th of the N-1
edges connects vertices a_i and b_i.
Initially, each vertex is uncolored.
Takahashi and Aoki is playing a game by painting the vertices. In this game,
they alternately perform the following operation, starting from Takahashi:
* Select a vertex that is not painted yet.
* If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki.
Then, after all the vertices are colored, the following procedure takes place:
* Repaint every white vertex that is adjacent to a black vertex, in black.
Note that all such white vertices are repainted simultaneously, not one at a
time.
If there are still one or more white vertices remaining, Takahashi wins; if
all the vertices are now black, Aoki wins. Determine the winner of the game,
assuming that both persons play optimally. | [{"input": "3\n 1 2\n 2 3", "output": "First\n \n\nBelow is a possible progress of the game:\n\n * First, Takahashi paint vertex 2 white.\n * Then, Aoki paint vertex 1 black.\n * Lastly, Takahashi paint vertex 3 white.\n\nIn this case, the colors of vertices 1, 2 and 3 after the final procedure are\nblack, black and white, resulting in Takahashi's victory.\n\n* * *"}, {"input": "4\n 1 2\n 2 3\n 2 4", "output": "First\n \n\n* * *"}, {"input": "6\n 1 2\n 2 3\n 3 4\n 2 5\n 5 6", "output": "Second"}] |
Print `First` if Takahashi wins; print `Second` if Aoki wins.
* * * | s898151492 | Runtime Error | p03726 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1} | print('First) | Statement
There is a tree with N vertices numbered 1 through N. The i-th of the N-1
edges connects vertices a_i and b_i.
Initially, each vertex is uncolored.
Takahashi and Aoki is playing a game by painting the vertices. In this game,
they alternately perform the following operation, starting from Takahashi:
* Select a vertex that is not painted yet.
* If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki.
Then, after all the vertices are colored, the following procedure takes place:
* Repaint every white vertex that is adjacent to a black vertex, in black.
Note that all such white vertices are repainted simultaneously, not one at a
time.
If there are still one or more white vertices remaining, Takahashi wins; if
all the vertices are now black, Aoki wins. Determine the winner of the game,
assuming that both persons play optimally. | [{"input": "3\n 1 2\n 2 3", "output": "First\n \n\nBelow is a possible progress of the game:\n\n * First, Takahashi paint vertex 2 white.\n * Then, Aoki paint vertex 1 black.\n * Lastly, Takahashi paint vertex 3 white.\n\nIn this case, the colors of vertices 1, 2 and 3 after the final procedure are\nblack, black and white, resulting in Takahashi's victory.\n\n* * *"}, {"input": "4\n 1 2\n 2 3\n 2 4", "output": "First\n \n\n* * *"}, {"input": "6\n 1 2\n 2 3\n 3 4\n 2 5\n 5 6", "output": "Second"}] |
Print `First` if Takahashi wins; print `Second` if Aoki wins.
* * * | s253392653 | Wrong Answer | p03726 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1} | print("First")
| Statement
There is a tree with N vertices numbered 1 through N. The i-th of the N-1
edges connects vertices a_i and b_i.
Initially, each vertex is uncolored.
Takahashi and Aoki is playing a game by painting the vertices. In this game,
they alternately perform the following operation, starting from Takahashi:
* Select a vertex that is not painted yet.
* If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki.
Then, after all the vertices are colored, the following procedure takes place:
* Repaint every white vertex that is adjacent to a black vertex, in black.
Note that all such white vertices are repainted simultaneously, not one at a
time.
If there are still one or more white vertices remaining, Takahashi wins; if
all the vertices are now black, Aoki wins. Determine the winner of the game,
assuming that both persons play optimally. | [{"input": "3\n 1 2\n 2 3", "output": "First\n \n\nBelow is a possible progress of the game:\n\n * First, Takahashi paint vertex 2 white.\n * Then, Aoki paint vertex 1 black.\n * Lastly, Takahashi paint vertex 3 white.\n\nIn this case, the colors of vertices 1, 2 and 3 after the final procedure are\nblack, black and white, resulting in Takahashi's victory.\n\n* * *"}, {"input": "4\n 1 2\n 2 3\n 2 4", "output": "First\n \n\n* * *"}, {"input": "6\n 1 2\n 2 3\n 3 4\n 2 5\n 5 6", "output": "Second"}] |
Print `First` if Takahashi wins; print `Second` if Aoki wins.
* * * | s005923216 | Wrong Answer | p03726 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1} | import queue
import sys
n = int(input())
edges = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(lambda s: int(s) - 1, input().split())
edges[a].append(b)
edges[b].append(a)
q = queue.Queue()
leaf = -1
for index, ls in enumerate(edges):
if len(ls) == 1:
leaf = index
flag = [False for i in range(n)]
w = [False for i in range(n)]
q.put(leaf)
flag[leaf] = True
w[leaf] = True
while not q.empty():
g = q.get()
f = not w[g]
for to in edges[g]:
if flag[to]:
continue
q.put(to)
flag[to] = True
w[to] = f
if not f:
f = True
if not f:
print("First")
sys.exit()
print("Second" if w.count(True) == w.count(False) else "First")
| Statement
There is a tree with N vertices numbered 1 through N. The i-th of the N-1
edges connects vertices a_i and b_i.
Initially, each vertex is uncolored.
Takahashi and Aoki is playing a game by painting the vertices. In this game,
they alternately perform the following operation, starting from Takahashi:
* Select a vertex that is not painted yet.
* If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki.
Then, after all the vertices are colored, the following procedure takes place:
* Repaint every white vertex that is adjacent to a black vertex, in black.
Note that all such white vertices are repainted simultaneously, not one at a
time.
If there are still one or more white vertices remaining, Takahashi wins; if
all the vertices are now black, Aoki wins. Determine the winner of the game,
assuming that both persons play optimally. | [{"input": "3\n 1 2\n 2 3", "output": "First\n \n\nBelow is a possible progress of the game:\n\n * First, Takahashi paint vertex 2 white.\n * Then, Aoki paint vertex 1 black.\n * Lastly, Takahashi paint vertex 3 white.\n\nIn this case, the colors of vertices 1, 2 and 3 after the final procedure are\nblack, black and white, resulting in Takahashi's victory.\n\n* * *"}, {"input": "4\n 1 2\n 2 3\n 2 4", "output": "First\n \n\n* * *"}, {"input": "6\n 1 2\n 2 3\n 3 4\n 2 5\n 5 6", "output": "Second"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s076184562 | Runtime Error | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | def f_playing_tag_on_tree():
N, U, V = [int(i) for i in input().split()]
Edges = [[int(i) for i in input().split()] for j in range(N - 1)]
tree = [[] for _ in range(N)]
for u, v in Edges:
tree[u - 1].append(v - 1)
tree[v - 1].append(u - 1)
depth = [-1] * N
def dfs(current, parent, dep):
depth[current] = dep
for child in tree[current]:
if child == parent:
continue
dfs(child, current, dep + 1)
return None
dfs(V - 1, -1, 0)
return max(depth) - 1
print(f_playing_tag_on_tree())
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s027197344 | Wrong Answer | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | def f():
n, u, v = [int(s) for s in input().split()]
u -= 1
v -= 1
neibors = [[] for i in range(n)]
for i in range(n - 1):
a, b = [int(s) - 1 for s in input().split()]
neibors[a].append(b)
neibors[b].append(a)
if u == v:
return 0
visited = [0] * n
thisLayer = [u]
visited[u] = 1
children = [set() for i in range(n)]
father = [None] * n
while thisLayer:
nextLayer = []
for node in thisLayer:
for nb in neibors[node]:
if not visited[nb]:
children[node].add(nb)
father[nb] = node
nextLayer.append(nb)
visited[nb] = 1
thisLayer = nextLayer
# print(children)
# print(father)
def getHight(root):
thisLayer = [root]
h = 0
while thisLayer:
h += 1
nextLayer = []
for node in thisLayer:
for child in children[node]:
nextLayer.append(child)
thisLayer = nextLayer
return h
node = v
distance = 0
while node != u:
node = father[node]
distance += 1
if len(children[u]) <= 1 and distance <= 2:
return distance - 1
node = v
step = 0
half = distance // 2
while step < half:
node = father[node]
step += 1
ans = 0
while node != u:
children[father[node]].discard(node) # cutoff
node = father[node]
h = getHight(node)
ans = max(step + h, ans)
step += 1
return ans - distance % 2
print(f())
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s190092456 | Accepted | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | import os
import sys
import numpy as np
def solve(N, U, V, AB):
G = [[0] * 0 for _ in range(N + 1)]
for idx_ab in range(len(AB)):
a, b = AB[idx_ab]
G[a].append(b)
G[b].append(a)
P1 = np.zeros(N + 1, dtype=np.int64)
def dfs1(u):
st = [u]
while st:
v = st.pop()
p = P1[v]
for u in G[v]:
if p != u:
st.append(u)
P1[u] = v
dfs1(U)
path_u2v = [U]
v = V
while v != U:
v = P1[v]
path_u2v.append(v)
path_u2v.reverse()
l = len(path_u2v)
half = (l - 2) // 2
c = path_u2v[half]
ng = path_u2v[half + 1]
Depth = np.zeros(N + 1, dtype=np.int64)
def dfs2(c):
st = [c]
P = np.zeros(N + 1, dtype=np.int64)
while st:
v = st.pop()
p = P[v]
d = Depth[v]
for u in G[v]:
if p != u and u != ng:
st.append(u)
P[u] = v
Depth[u] = d + 1
dfs2(c)
c_ = path_u2v[l - 1 - half]
v = c_
while v != c:
Depth[v] = 0
v = P1[v]
d = l % 2
ans = max(Depth) + half + d
return ans
# >>> numba compile >>>
numba_config = [
[solve, "i8(i8,i8,i8,i8[:,:])"],
]
if sys.argv[-1] == "ONLINE_JUDGE":
from numba import njit
from numba.pycc import CC
cc = CC("my_module")
for func, signature in numba_config:
vars()[func.__name__] = njit(signature)(func)
cc.export(func.__name__, signature)(func)
cc.compile()
exit()
elif os.name == "posix":
exec(f"from my_module import {','.join(func.__name__ for func, _ in numba_config)}")
else:
from numba import njit
for func, signature in numba_config:
vars()[func.__name__] = njit(signature, cache=True)(func)
print("compiled!", file=sys.stderr)
# <<< numba compile <<<
def main():
N, u, v = map(int, input().split())
if N == 2:
print(0)
return
AB = np.array(sys.stdin.read().split(), dtype=np.int64).reshape(N - 1, 2)
ans = solve(N, u, v, AB)
print(ans)
main()
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s149845258 | Accepted | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | from collections import deque
import sys
si = sys.stdin.readline
def BFS(g, s):
d = 0
dt = dict()
visited = set()
visited.add(s)
Q = deque([s])
while len(Q):
d += 1
Qs = len(Q)
for _ in range(Qs):
Qpop = Q.popleft()
for node in g[Qpop]:
if node not in visited:
Q.append(node)
visited.add(node)
dt[node] = d
return dt
def main():
l = [int(e) for e in si().split()]
n, u, v = l[0], l[1], l[2]
graph = [[] for _ in range(n + 1)]
for _ in range(n - 1):
l = [int(e) for e in si().split()]
graph[l[0]].append(l[1])
graph[l[1]].append(l[0])
udt = BFS(graph, u)
vdt = BFS(graph, v)
udt[u], vdt[v] = 0, 0
vdmax = 0
for i in range(1, n + 1):
if (vdt[i] - udt[i]) > 0 and vdt[i] > vdmax:
vdmax = vdt[i]
print(vdmax - 1)
if __name__ == "__main__":
main()
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s656050798 | Wrong Answer | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | print("123".replace(input(), "").replace(input(), ""))
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s943119591 | Accepted | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | import sys
readline = sys.stdin.readline
# 青木君からの到達距離 - 高橋君からの到達距離が最も大きい場所に逃げるべき
# そこに到達したときに、
# 高橋君と青木君の距離が偶数のとき
# 青 - x - x - x - 高
# 青 - x - x - 高 - x
# x - 青 - x - 高 - x
# x - 青 - x - x - 高
# x - x - 青 - x - 高
# x - x - 青- 高 - x
# x - x - x - 終 - x
# 青木君からの距離 - 1が答え
# 高橋君と青木君の距離が奇数のとき
# 青 - x - x - 高
# 青 - x - 高 - x
# x - 青 - 高 - x
# x - 青 - x - 高
# x - x - 青 - 高
# x - x - 終 - x
# やっぱり青木君からの距離 - 1が答え
# つまり、
# ・[青木君からの距離が遠い場所について]
# ・[青木君からの距離 - 1]が答え
N, u, v = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(N - 1):
a, b = map(int, readline().split())
G[a - 1].append(b - 1)
G[b - 1].append(a - 1)
dist_from_u = [0 for i in range(N)] # 高橋君からの距離
dist_from_v = [0 for i in range(N)] # 青木君からの距離
stack = []
# 頂点, 高橋君からの距離, 親
stack.append([u - 1, 0, -1])
while stack:
e, dist, parent = stack.pop()
dist_from_u[e] = dist
for child in G[e]:
if child == parent:
continue
stack.append([child, dist + 1, e])
stack = []
# 頂点, 青木君からの距離, 親
stack.append([v - 1, 0, -1])
while stack:
e, dist, parent = stack.pop()
dist_from_v[e] = dist
for child in G[e]:
if child == parent:
continue
stack.append([child, dist + 1, e])
maxdiff_from_v = 0
for i in range(N):
if dist_from_u[i] < dist_from_v[i]:
if maxdiff_from_v < dist_from_v[i]:
maxdiff_from_v = dist_from_v[i]
print(maxdiff_from_v - 1)
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s810882650 | Wrong Answer | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | import sys
sys.setrecursionlimit(2 * 10**5)
n, u, v = map(int, input().split())
conn = {}
for _ in range(n - 1):
ai, bi = map(int, input().split())
if conn.get(ai):
conn.get(ai).add(bi)
else:
conn[ai] = {bi}
if conn.get(bi):
conn.get(bi).add(ai)
else:
conn[bi] = {ai}
def hoge(start, geta, dist_dict):
dist_dict[start] = geta
for i in conn[start]:
if dist_dict.get(i) == None:
hoge(i, geta + 1, dist_dict)
u_dist = {}
hoge(u, 0, u_dist)
v_dist = {}
hoge(v, 0, v_dist)
safety = [val for k, val in u_dist.items() if val < v_dist[k]]
danger = [val for k, val in u_dist.items() if val == v_dist[k]]
print(max([max(safety or [0]), min(danger or [0]), 1]))
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s955487732 | Accepted | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | n = input()
m = n.split()
p = [int(i) for i in m]
from collections import deque
list = []
for i in range(p[0] - 1): # 因数注意!
n = input()
m = n.split()
q = [int(i) for i in m] # 1列の数列をリスト化
list.append(q)
l = [[] for i in range(p[0] + 1)]
for pi in list: # 0-originedに注意
l[pi[0]].append(pi[1])
l[pi[1]].append(pi[0])
sousa = deque([[p[2], 0, 0]]) # [捜査対象ノード,親ノード,そのノードの距離]
node = [
[] for i in range(p[0])
] # n番目のリストにn+1について[親ノード,rootからの距離,子ノード]
while len(sousa) != 0:
a = sousa.popleft()
b = l[a[0]]
if a[1] != 0:
b.remove(a[1])
if len(b) == 0:
pass
else:
for i in b:
sousa.append([i, a[0], a[2] + 1])
node[a[0] - 1] = [a[1]] + [a[2]] + b
dis = node[p[1] - 1][1]
takahashi = p[1]
max = dis
hate = p[1]
for i in range((dis + 1) // 2):
tansaku = deque([[takahashi, dis]])
if i >= 1:
kitatoko = takahashi
takahashi = node[takahashi - 1][0]
a = tansaku.popleft()
b = node[takahashi - 1][2:]
b.remove(kitatoko)
if len(b) == 0:
continue
else:
for j in b:
tansaku.append([j, dis + 1 - i])
while len(tansaku) != 0:
a = tansaku.popleft()
b = node[a[0] - 1][2:]
print()
if len(b) == 0:
pass
else:
for j in b:
tansaku.append([j, a[1] + 1])
if max < a[1]:
max = a[1]
hate = a[0]
print(node[hate - 1][1] - 1)
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s645716995 | Wrong Answer | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | from collections import defaultdict
# def find_distances(edge_dict, node, distances):
# for end in edge_dict[node]:
# if distances[end] < 0:
# distances[end] = distances[node] + 1
# distances = find_distances(edge_dict, end, distances)
# return distances
def find_distances(edge_dict, node, V):
distances = [-1] * V
stack = [(0, node)]
while stack:
dist, node = stack.pop()
if distances[node] > 0:
continue
distances[node] = dist
for end in edge_dict[node]:
stack.append((dist + 1, end))
return distances
if __name__ == "__main__":
V, T, A = map(int, input().split())
T -= 1
A -= 1
edge_dict = defaultdict(list)
for _ in range(V - 1):
start, end = map(int, input().split())
edge_dict[start - 1].append(end - 1)
edge_dict[end - 1].append(start - 1)
dist_T = [-1] * V
dist_T[T] = 0
dist_T = find_distances(edge_dict, T, V)
dist_A = [-1] * V
dist_A[A] = 0
dist_A = find_distances(edge_dict, A, V)
max_dist = 0
for i in range(V):
if dist_T[i] <= dist_A[i]:
max_dist = max(max_dist, dist_A[i])
print(max_dist - 1)
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s251034739 | Accepted | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | N, u, v = list(map(int, input().split()))
u, w = u - 1, v - 1
w, u = u, w
e_list = [[] for i in range(N)]
for i in range(N - 1):
a, b = list(map(int, input().split()))
a, b = a - 1, b - 1
e_list[a].append(b)
e_list[b].append(a)
vi = u # 時と場合によってここを変える
from collections import deque
Q = deque([vi])
checked_list = [False for i in range(N)]
checked_list[vi] = True
min_path_list = [10**27 for i in range(N)] # 問題によりここを変える
min_path_list[vi] = 0
prev_list = [-1 for i in range(N)]
while len(Q) > 0:
v = Q.pop()
for v1 in e_list[v]:
if not checked_list[v1]:
checked_list[v1] = True
prev_list[v1] = v
Q.appendleft(v1)
min_path_list[v1] = min(
min_path_list[v1], min_path_list[v] + 1
) # 問題によりここを変える
dis = min_path_list[w] // 2
w_min = min_path_list[w]
current = w
for i in range(dis):
current = prev_list[current]
dist = min_path_list[current]
vi = current # 時と場合によってここを変える
Q = deque([vi])
checked_list = [False for i in range(N)]
checked_list[vi] = True
checked_list[prev_list[vi]] = True
min_path_list = [10**27 for i in range(N)] # 問題によりここを変える
min_path_list[vi] = 0
while len(Q) > 0:
v = Q.pop()
for v1 in e_list[v]:
if not checked_list[v1]:
checked_list[v1] = True
Q.appendleft(v1)
min_path_list[v1] = min(
min_path_list[v1], min_path_list[v] + 1
) # 問題によりここを変える
depth = 0
for i in range(N):
if min_path_list[i] < 10**27:
depth = max(min_path_list[i], depth)
depth = dist + depth
print(depth - 1)
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the number of moves Aoki will perform before the end of the game.
* * * | s052643963 | Accepted | p02834 | Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1} | import sys
sys.setrecursionlimit(10**9)
from collections import deque
class LCA1:
def __init__(self, l, start):
self.n = len(l)
self.dep = [0] * self.n
self.par = [[-1] * self.n for i in range(18)]
def bfs(start):
is_leaf = [0] * n
que = deque()
que.append((start, -1, 0))
while que:
c, p, d = que.pop()
self.dep[c] = d
self.par[0][c] = p
cnt = 0
for to in G[c]:
if to != p:
que.append((to, c, d + 1))
cnt += 1
if not cnt:
is_leaf[c] = 1
return is_leaf
self.is_leaf = bfs(start)
for i in range(17):
for j in range(self.n):
self.par[i + 1][j] = self.par[i][self.par[i][j]]
def lca(self, a, b):
if self.dep[a] > self.dep[b]:
a, b = b, a
for i in range(18):
if (self.dep[b] - self.dep[a]) & 1 << i:
b = self.par[i][b]
if a == b:
return a
for i in range(18)[::-1]:
if self.par[i][a] != self.par[i][b]:
a = self.par[i][a]
b = self.par[i][b]
return self.par[0][a]
def dist(self, a, b):
return abs(self.dep[a] - self.dep[b])
n, u, v = map(int, input().split())
u, v = u - 1, v - 1
G = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
a, b = a - 1, b - 1
G[a].append(b)
G[b].append(a)
LCA = LCA1(G, v)
ans = 0
for i in range(n):
if not LCA.is_leaf[i]:
continue
lca = LCA.lca(u, i)
if lca == v:
continue
if LCA.dist(lca, u) >= LCA.dist(lca, v):
continue
turn = 0
tmp = 0
d = LCA.dist(u, lca) + LCA.dist(lca, i)
if d != 0:
tmp = 2 * d
aoki = d
else:
aoki = 0
tak = LCA.dep[i]
m = tak - aoki
if m % 2 == 1:
tmp += 2 * m - 1
else:
tmp += 2 * (m - 1)
ans = max(ans, tmp)
print(ans // 2)
| Statement
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i
bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
* 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
* 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while
Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both
Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end. | [{"input": "5 4 1\n 1 2\n 2 3\n 3 4\n 3 5", "output": "2\n \n\nIf both players play optimally, the game will progress as follows:\n\n * Takahashi moves to Vertex 3.\n * Aoki moves to Vertex 2.\n * Takahashi moves to Vertex 5.\n * Aoki moves to Vertex 3.\n * Takahashi moves to Vertex 3.\n\nHere, Aoki performs two moves.\n\nNote that, in each move, it is prohibited to stay at the current vertex.\n\n* * *"}, {"input": "5 4 5\n 1 2\n 1 3\n 1 4\n 1 5", "output": "1\n \n\n* * *"}, {"input": "2 1 2\n 1 2", "output": "0\n \n\n* * *"}, {"input": "9 6 1\n 1 2\n 2 3\n 3 4\n 4 5\n 5 6\n 4 7\n 7 8\n 8 9", "output": "5"}] |
Print the maximum number of doughnuts that can be made under the condition.
* * * | s082366329 | Wrong Answer | p03376 | Input is given from Standard Input in the following format:
N X D
m_1
m_2 p_2
:
m_N p_N | #!/usr/bin/env python3
INF = 2 * 10**9
def solve(n, x, d, ma, pa):
v = [1] * n
w = [0] * n
for i in range(n - 1, -1, -1):
w[i] += ma[i]
if 0 <= pa[i]:
v[pa[i]] += v[i]
w[pa[i]] += w[i]
if d == 0:
return (x // w[0]) * n
c_0 = max(0, x - sum(w[1:]) * d + w[0] - 1) // w[0]
ans = n * c_0
y = w[0] * c_0
mean_w = [None] * n
for i in range(n):
mean_w[i] = (w[i] / v[i], i)
mean_w.sort()
t = [0] * n
llj = lj = -1
for i in range(n):
_, j = mean_w[i]
if j == 0:
t[0] = (x - y) // w[0]
y += w[0] * t[0]
lj = 0
break
if x <= y + w[j] * d:
t[j] = (x - y) // w[j]
y += w[j] * t[j]
lj = j
break
y += w[j] * d
t[j] = d
llj = j
c_max = min(n, d)
if c_max <= t[lj]:
y -= w[lj] * c_max
t[lj] -= c_max
else:
y -= w[lj] * t[lj]
t[lj] = 0
if llj != -1:
y -= w[llj] * c_max
t[llj] -= c_max
ans += sum([v[j] * t[j] for j in range(n)])
j_max = c_max * n * n
v_max = 0
rx = x - y
dp = [[0] + [INF] * j_max for _ in range(n)]
for j in range(1, j_max // n + 1):
dp[0][n * j] = ndp = w[0] * j
if ndp <= rx:
v_max = n * j
for i in range(1, n):
vi = v[i]
wi = w[i]
for j in range(1, j_max + 1):
ndp = dp[i - 1][j]
nj = j
w_sum = 0
for k in range(1, min(c_max, d - t[i])):
nj -= vi
w_sum += wi
if nj < 0:
break
ndp = min(ndp, dp[i - 1][nj] + w_sum)
dp[i][j] = ndp
if ndp <= rx:
if v_max < j:
v_max = j
ans += v_max
return ans
def main():
n, x, d = input().split()
n = int(n)
x = int(x)
d = int(d)
ma = []
pa = []
m = input()
m = int(m)
ma.append(m)
pa.append(-1)
for _ in range(n - 1):
m, p = input().split()
m = int(m)
ma.append(m)
p = int(p) - 1
pa.append(p)
print(solve(n, x, d, ma, pa))
if __name__ == "__main__":
main()
| Statement
Akaki, a patissier, can make N kinds of doughnut using only a certain powder
called "Okashi no Moto" (literally "material of pastry", simply called Moto
below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ...,
Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume
m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as
0.5 doughnuts.
The recipes of these doughnuts are developed by repeated modifications from
the recipe of Doughnut 1. Specifically, the recipe of Doughnut i (2 ≤ i ≤ N)
is a direct modification of the recipe of Doughnut p_i (1 ≤ p_i < i).
Now, she has X grams of Moto. She decides to make as many doughnuts as
possible for a party tonight. However, since the tastes of the guests differ,
she will obey the following condition:
* Let c_i be the number of Doughnut i (1 ≤ i ≤ N) that she makes. For each integer i such that 2 ≤ i ≤ N, c_{p_i} ≤ c_i ≤ c_{p_i} + D must hold. Here, D is a predetermined value.
At most how many doughnuts can be made here? She does not necessarily need to
consume all of her Moto. | [{"input": "3 100 1\n 15\n 10 1\n 20 1", "output": "7\n \n\nShe has 100 grams of Moto, can make three kinds of doughnuts, and the\nconditions that must hold are c_1 \u2264 c_2 \u2264 c_1 + 1 and c_1 \u2264 c_3 \u2264 c_1 + 1. It\nis optimal to make two Doughnuts 1, three Doughnuts 2 and two Doughnuts 3.\n\n* * *"}, {"input": "3 100 10\n 15\n 10 1\n 20 1", "output": "10\n \n\nThe amount of Moto and the recipes of the doughnuts are not changed from\nSample Input 1, but the last conditions are relaxed. In this case, it is\noptimal to make just ten Doughnuts 2. As seen here, she does not necessarily\nneed to make all kinds of doughnuts.\n\n* * *"}, {"input": "5 1000000000 1000000\n 123\n 159 1\n 111 1\n 135 3\n 147 3", "output": "7496296"}] |
Print the answer in M lines. The i-th line should contain the maximum number
of the kinds of souvenirs that can be purchased if one takes a train stopping
every i-th station.
* * * | s623306715 | Runtime Error | p03819 | The input is given from Standard Input in the following format:
N M
l_1 r_1
:
l_{N} r_{N} | import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9 + 7
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def LI_():
return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF():
return [float(x) for x in sys.stdin.readline().split()]
def LS():
return sys.stdin.readline().split()
def I():
return int(sys.stdin.readline())
def F():
return float(sys.stdin.readline())
def S():
return input()
def pf(s):
return print(s, flush=True)
class BIT:
def __init__(self, n):
i = 1
while 2**i <= n:
i += 1
self.H = i
self.N = 2**i
self.A = [0] * self.N
def find(self, i):
r = 0
while i:
r += self.A[i]
i -= i & (i - 1) ^ i
return r
def update(self, i, x):
while i < self.N:
self.A[i] += x
i += i & (i - 1) ^ i
def query(self, a, b):
return self.find(b - 1) - self.find(a - 1)
def main():
n, m = LI()
d = collections.defaultdict(list)
for _ in range(n):
l, r = LI()
d[r - l + 1].append((l, r))
r = [n]
bit = BIT(n + 3)
c = n
for i in range(2, m + 1):
for a, b in d[i - 1]:
c -= 1
bit.update(a, 1)
bit.update(b + 1, -1)
t = c
for j in range(i, m + 1, i):
t += bit.find(j)
r.append(t)
return "\n".join(map(str, r))
print(main())
| Statement
Snuke has decided to play a game, where the player runs a railway company.
There are M+1 stations on Snuke Line, numbered 0 through M. A train on Snuke
Line stops at station 0 and every d-th station thereafter, where d is a
predetermined constant for each train. For example, if d = 3, the train stops
at station 0, 3, 6, 9, and so forth.
There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind
of souvenirs can be purchased when the train stops at one of the following
stations: stations l_i, l_i+1, l_i+2, ..., r_i.
There are M values of d, the interval between two stops, for trains on Snuke
Line: 1, 2, 3, ..., M. For each of these M values, find the number of the
kinds of souvenirs that can be purchased if one takes a train with that value
of d at station 0. Here, assume that it is not allowed to change trains. | [{"input": "3 3\n 1 2\n 2 3\n 3 3", "output": "3\n 2\n 2\n \n\n * If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3.\n * If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2.\n * If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3.\n\n* * *"}, {"input": "7 9\n 1 7\n 5 9\n 5 7\n 5 9\n 1 1\n 6 8\n 3 4", "output": "7\n 6\n 6\n 5\n 4\n 5\n 5\n 3\n 2"}] |
Print the answer in M lines. The i-th line should contain the maximum number
of the kinds of souvenirs that can be purchased if one takes a train stopping
every i-th station.
* * * | s950257821 | Runtime Error | p03819 | The input is given from Standard Input in the following format:
N M
l_1 r_1
:
l_{N} r_{N} | def is_prime(N):
if N < 2:
return False
i = 2
while i * i <= N:
if N % i == 0:
return False
i += 1
return True
def main():
N = int(input())
if not is_prime(N):
dsum = 0
for c in str(N):
dsum += int(c)
if N == 1 or N % 10 in [2, 4, 5, 6, 8, 0] or dsum % 3 == 0:
print("Not Prime")
return
print("Prime")
if __name__ == "__main__":
main()
| Statement
Snuke has decided to play a game, where the player runs a railway company.
There are M+1 stations on Snuke Line, numbered 0 through M. A train on Snuke
Line stops at station 0 and every d-th station thereafter, where d is a
predetermined constant for each train. For example, if d = 3, the train stops
at station 0, 3, 6, 9, and so forth.
There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind
of souvenirs can be purchased when the train stops at one of the following
stations: stations l_i, l_i+1, l_i+2, ..., r_i.
There are M values of d, the interval between two stops, for trains on Snuke
Line: 1, 2, 3, ..., M. For each of these M values, find the number of the
kinds of souvenirs that can be purchased if one takes a train with that value
of d at station 0. Here, assume that it is not allowed to change trains. | [{"input": "3 3\n 1 2\n 2 3\n 3 3", "output": "3\n 2\n 2\n \n\n * If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3.\n * If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2.\n * If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3.\n\n* * *"}, {"input": "7 9\n 1 7\n 5 9\n 5 7\n 5 9\n 1 1\n 6 8\n 3 4", "output": "7\n 6\n 6\n 5\n 4\n 5\n 5\n 3\n 2"}] |
Print the answer in M lines. The i-th line should contain the maximum number
of the kinds of souvenirs that can be purchased if one takes a train stopping
every i-th station.
* * * | s787263475 | Runtime Error | p03819 | The input is given from Standard Input in the following format:
N M
l_1 r_1
:
l_{N} r_{N} | import sys
print("弁当の種類を指定してください:")
bentoType = int(sys.stdin.readline())
print("駅の合計数を指定してください:")
stationCnt = int(sys.stdin.readline())
startSta = 0
endSta = 0
array = []
for i in range(1, bentoType + 1):
bentoMap = {}
print("弁当" + str(i) + "の開始駅を指定してください:")
startSta = int(sys.stdin.readline())
print("弁当" + str(i) + "の終了駅を指定してください:")
endSta = int(sys.stdin.readline())
for start in range(startSta, endSta + 1, 1):
bentoMap.update({str(start): 1})
array.append(bentoMap)
bentoCnt = 0
for n in range(1, stationCnt + 1, 1):
bentoCnt = 0
for outMap in array:
for m in range(0, stationCnt + 1, n):
if str(m) in outMap:
bentoCnt += 1
break
print("弁当" + str(n) + ":")
print(bentoCnt)
| Statement
Snuke has decided to play a game, where the player runs a railway company.
There are M+1 stations on Snuke Line, numbered 0 through M. A train on Snuke
Line stops at station 0 and every d-th station thereafter, where d is a
predetermined constant for each train. For example, if d = 3, the train stops
at station 0, 3, 6, 9, and so forth.
There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind
of souvenirs can be purchased when the train stops at one of the following
stations: stations l_i, l_i+1, l_i+2, ..., r_i.
There are M values of d, the interval between two stops, for trains on Snuke
Line: 1, 2, 3, ..., M. For each of these M values, find the number of the
kinds of souvenirs that can be purchased if one takes a train with that value
of d at station 0. Here, assume that it is not allowed to change trains. | [{"input": "3 3\n 1 2\n 2 3\n 3 3", "output": "3\n 2\n 2\n \n\n * If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3.\n * If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2.\n * If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3.\n\n* * *"}, {"input": "7 9\n 1 7\n 5 9\n 5 7\n 5 9\n 1 1\n 6 8\n 3 4", "output": "7\n 6\n 6\n 5\n 4\n 5\n 5\n 3\n 2"}] |
Print the answer in M lines. The i-th line should contain the maximum number
of the kinds of souvenirs that can be purchased if one takes a train stopping
every i-th station.
* * * | s774555263 | Wrong Answer | p03819 | The input is given from Standard Input in the following format:
N M
l_1 r_1
:
l_{N} r_{N} | # coding: UTF-8
N, M = map(int, input().split())
d_list = [[0]] * M
sd_list = [0] * M
for i in range(0, N):
l, r = map(int, input().split())
d = r - l
if d_list[d] == [0]:
d_list[d] = [[l, r]]
else:
d_list[d].append([l, r])
for i in range(0, M):
if d_list[i] != [0]:
sd_list[i] = len(d_list[i])
plist = [[0 for i in range(0, M)] for i in range(0, M)]
for i in range(0, M):
if 0 not in d_list[i]:
for L in d_list[i]:
for j in range(L[0], L[1] + 1):
plist[i][j - 1] += 1
out = [0] * M
out[0] = sd_list[0]
for i in range(1, M):
out[i] = sd_list[i]
for k in range(0, i):
for j in range(i, M, i + 1):
out[i] += plist[k][j]
for i in range(0, M):
print(out[i])
| Statement
Snuke has decided to play a game, where the player runs a railway company.
There are M+1 stations on Snuke Line, numbered 0 through M. A train on Snuke
Line stops at station 0 and every d-th station thereafter, where d is a
predetermined constant for each train. For example, if d = 3, the train stops
at station 0, 3, 6, 9, and so forth.
There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind
of souvenirs can be purchased when the train stops at one of the following
stations: stations l_i, l_i+1, l_i+2, ..., r_i.
There are M values of d, the interval between two stops, for trains on Snuke
Line: 1, 2, 3, ..., M. For each of these M values, find the number of the
kinds of souvenirs that can be purchased if one takes a train with that value
of d at station 0. Here, assume that it is not allowed to change trains. | [{"input": "3 3\n 1 2\n 2 3\n 3 3", "output": "3\n 2\n 2\n \n\n * If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3.\n * If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2.\n * If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3.\n\n* * *"}, {"input": "7 9\n 1 7\n 5 9\n 5 7\n 5 9\n 1 1\n 6 8\n 3 4", "output": "7\n 6\n 6\n 5\n 4\n 5\n 5\n 3\n 2"}] |
Print the answer in M lines. The i-th line should contain the maximum number
of the kinds of souvenirs that can be purchased if one takes a train stopping
every i-th station.
* * * | s336493654 | Accepted | p03819 | The input is given from Standard Input in the following format:
N M
l_1 r_1
:
l_{N} r_{N} | import sys
input = sys.stdin.readline
def main():
n, m = map(int, input().split())
LR = [list(map(int, input().split())) for _ in range(n)]
BIT = [0] * (m + 2)
def add(i, a):
while i <= m + 1:
BIT[i] += a
i += i & (-i)
def bit_sum(i):
res = 0
while i > 0:
res += BIT[i]
i -= i & (-i)
return res
for l, r in LR:
add(l, 1)
add(r + 1, -1)
S = sorted([(r - l + 1, l, r) for l, r in LR])
cnt = 0
L = []
for i in range(m, 0, -1):
while S and S[-1][0] == i:
c, l, r = S.pop()
cnt += 1
add(l, -1)
add(r + 1, 1)
res = cnt
for j in range(0, m + 1, i):
res += bit_sum(j)
L.append(res)
print(*L[::-1], sep="\n")
if __name__ == "__main__":
main()
| Statement
Snuke has decided to play a game, where the player runs a railway company.
There are M+1 stations on Snuke Line, numbered 0 through M. A train on Snuke
Line stops at station 0 and every d-th station thereafter, where d is a
predetermined constant for each train. For example, if d = 3, the train stops
at station 0, 3, 6, 9, and so forth.
There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind
of souvenirs can be purchased when the train stops at one of the following
stations: stations l_i, l_i+1, l_i+2, ..., r_i.
There are M values of d, the interval between two stops, for trains on Snuke
Line: 1, 2, 3, ..., M. For each of these M values, find the number of the
kinds of souvenirs that can be purchased if one takes a train with that value
of d at station 0. Here, assume that it is not allowed to change trains. | [{"input": "3 3\n 1 2\n 2 3\n 3 3", "output": "3\n 2\n 2\n \n\n * If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3.\n * If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2.\n * If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3.\n\n* * *"}, {"input": "7 9\n 1 7\n 5 9\n 5 7\n 5 9\n 1 1\n 6 8\n 3 4", "output": "7\n 6\n 6\n 5\n 4\n 5\n 5\n 3\n 2"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s171835076 | Accepted | p03618 | Input is given from Standard Input in the following format:
A | print(
(
len(a := input()) ** 2
- sum(map(lambda x: x * x, map(a.count, [chr(i) for i in range(97, 123)])))
)
// 2
+ 1
)
| Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s567078175 | Accepted | p03618 | Input is given from Standard Input in the following format:
A | print(2 + len(a := input()) ** 2 - sum(a.count(x) ** 2 for x in set(a)) >> 1)
| Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s775590794 | Accepted | p03618 | Input is given from Standard Input in the following format:
A | def main():
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left, bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil, pi, factorial
from operator import itemgetter
def I():
return int(input())
def MI():
return map(int, input().split())
def LI():
return list(map(int, input().split()))
def LI2():
return [int(input()) for i in range(n)]
def MXI():
return [[LI()] for i in range(n)]
def SI():
return input().rstrip()
def printns(x):
print("\n".join(x))
def printni(x):
print("\n".join(list(map(str, x))))
inf = 10**17
mod = 10**9 + 7
# main code here!
s = SI()
n = len(s)
dict_ = defaultdict(lambda: 0)
for i in range(n):
dict_[s[i]] += 1
ans = 1 + (n * (n - 1)) // 2
for x in dict_.keys():
ans -= (dict_[x] * (dict_[x] - 1)) // 2
print(ans)
if __name__ == "__main__":
main()
| Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s511119103 | Runtime Error | p03618 | Input is given from Standard Input in the following format:
A | import sys
sys.setrecursionlimit(10**7)
def I():
return int(sys.stdin.readline().rstrip())
def MI():
return map(int, sys.stdin.readline().rstrip().split())
def LI():
return list(map(int, sys.stdin.readline().rstrip().split())) # 空白あり
def LI2():
return list(map(int, sys.stdin.readline().rstrip())) # 空白なし
def S():
return sys.stdin.readline().rstrip()
def LS():
return list(sys.stdin.readline().rstrip().split()) # 空白あり
def LS2():
return list(sys.stdin.readline().rstrip()) # 空白なし
N, K = MI()
S = LI2()
A = []
a = 1
for i in range(1, N):
if S[i - 1] == S[i]:
a += 1
else:
A.append(a)
a = 1
A.append(a)
l = len(A)
if l <= 2 * K - 1:
print(N)
exit()
if S[0] == 1:
A = [1] + A
if S[-1] == 1:
A = A + [1]
A = [0] + A
l = len(A)
from itertools import accumulate
A = list(accumulate(A))
ans = 0
for i in range(l // 2 - K + 1):
if i == 0:
ans = max(ans, A[2 * (K + i)] - A[2 * i])
elif i == l // 2 - K:
ans = max(ans, A[2 * (K + i) - 1] - A[2 * i - 1])
else:
ans = max(ans, A[2 * (K + i)] - A[2 * i - 1])
print(ans)
| Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s419945035 | Accepted | p03618 | Input is given from Standard Input in the following format:
A | import sys, collections as cl, bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9 + 7
Max = sys.maxsize
def l(): # intのlist
return list(map(int, input().split()))
def m(): # 複数文字
return map(int, input().split())
def onem(): # Nとかの取得
return int(input())
def s(x): # 圧縮
a = []
if len(x) == 0:
return []
aa = x[0]
su = 1
for i in range(len(x) - 1):
if aa != x[i + 1]:
a.append([aa, su])
aa = x[i + 1]
su = 1
else:
su += 1
a.append([aa, su])
return a
def jo(x): # listをスペースごとに分ける
return " ".join(map(str, x))
def max2(x): # 他のときもどうように作成可能
return max(map(max, x))
def In(x, a): # aがリスト(sorted)
k = bs.bisect_left(a, x)
if k != len(a) and a[k] == x:
return True
else:
return False
def pow_k(x, n):
ans = 1
while n:
if n % 2:
ans *= x
x *= x
n >>= 1
return ans
"""
def nibu(x,n,r):
ll = 0
rr = r
while True:
mid = (ll+rr)//2
if rr == mid:
return ll
if (ここに評価入れる):
rr = mid
else:
ll = mid+1
"""
a = input()[:-1]
su = (len(a) * (len(a) - 1)) // 2
po = [0 for i in range(26)]
for i in range(len(a)):
on = ord(a[i]) - 97
su -= po[on]
po[on] += 1
print(su + 1)
| Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s126489893 | Accepted | p03618 | Input is given from Standard Input in the following format:
A | a, alpha = list(input()), list("abcdefghijklmnopqrstuvwxyz")
cnt, n = [sum(map(lambda x: x == i, a)) for i in alpha], len(a)
print(n * (n - 1) // 2 - sum(map(lambda x: x * (x - 1) // 2, cnt)) + 1)
| Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s116094760 | Accepted | p03618 | Input is given from Standard Input in the following format:
A | from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, groupby
import sys
import bisect
import string
import math
import time
import random
def S_():
return input()
def IS():
return input().split()
def LS():
return [i for i in input().split()]
def I():
return int(input())
def MI():
return map(int, input().split())
def LI():
return [int(i) for i in input().split()]
def LI_():
return [int(i) - 1 for i in input().split()]
def NI(n):
return [int(input()) for i in range(n)]
def NI_(n):
return [int(input()) - 1 for i in range(n)]
def StoI():
return [ord(i) - 97 for i in input()]
def ItoS(nn):
return chr(nn + 97)
def LtoS(ls):
return "".join([chr(i + 97) for i in ls])
def GI(V, E, Directed=False, index=0):
org_inp = []
g = [[] for i in range(n)]
for i in range(E):
inp = LI()
org_inp.append(inp)
if index == 0:
inp[0] -= 1
inp[1] -= 1
if len(inp) == 2:
a, b = inp
g[a].append(b)
if not Directed:
g[b].append(a)
elif len(inp) == 3:
a, b, c = inp
aa = (inp[0], inp[2])
bb = (inp[1], inp[2])
g[a].append(bb)
if not Directed:
g[b].append(aa)
return g, org_inp
def GGI(h, w, search=None, replacement_of_found=".", mp_def={"#": 1, ".": 0}):
# h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
mp = [1] * (w + 2)
found = {}
for i in range(h):
s = input()
for char in search:
if char in s:
found[char] = (i + 1) * (w + 2) + s.index(char) + 1
mp_def[char] = mp_def[replacement_of_found]
mp += [1] + [mp_def[j] for j in s] + [1]
mp += [1] * (w + 2)
return h + 2, w + 2, mp, found
def bit_combination(k, n=2):
rt = []
for tb in range(n**k):
s = [tb // (n**bt) % n for bt in range(k)]
rt += [s]
return rt
def show(*inp, end="\n"):
if show_flg:
print(*inp, end=end)
YN = ["Yes", "No"]
mo = 10**9 + 7
inf = float("inf")
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
# sys.setrecursionlimit(10**7)
input = lambda: sys.stdin.readline().rstrip()
def ran_input():
import random
n = random.randint(4, 16)
rmin, rmax = 1, 10
a = [random.randint(rmin, rmax) for _ in range(n)]
return n, a
show_flg = False
show_flg = True
ans = 0
s = input()
n = len(s)
ans += 1 + n * (n - 1) // 2
p = ""
c = 1
s = sorted(s)
for i in [1] + s + [0]:
if p == i:
c += 1
else:
ans -= c * (c - 1) // 2
c = 1
p = i
print(ans)
| Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s423023337 | Wrong Answer | p03618 | Input is given from Standard Input in the following format:
A | A = input()
ans = 0
a = A.count("a")
b = A.count("b")
c = A.count("c")
d = A.count("d")
e = A.count("e")
f = A.count("f")
g = A.count("g")
h = A.count("h")
i = A.count("i")
j = A.count("j")
k = A.count("k")
l = A.count("l")
m = A.count("m")
n = A.count("n")
o = A.count("o")
p = A.count("p")
q = A.count("q")
r = A.count("r")
s = A.count("s")
t = A.count("t")
u = A.count("u")
v = A.count("v")
w = A.count("w")
x = A.count("x")
y = A.count("y")
z = A.count("z")
B = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
for aa in range(26):
ans = ans + B[aa] * (len(A) - B[aa])
print(ans)
| Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s517821712 | Runtime Error | p03618 | Input is given from Standard Input in the following format:
A | strs = [x for x in input()]
ans = 1
for i in range(len(strs)):
for j in range(i+1,len(strs)+1):
if strs[i] == strs[j]:
pass
else:
ans ++
print(ans) | Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s362041349 | Runtime Error | p03618 | Input is given from Standard Input in the following format:
A | s=input()
def cal(n):
if len(s)==1:
return 0
else:
new=s[0]
ans=0
cnt=0
for i in range(1,n):
if s[i]!=new:
new=s[i]
cnt=0
ans+=(i+1)
else: s[i]==new:
cnt+=1
ans+=cnt
return ans
| Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
Print the number of different strings you can obtain by reversing any
substring in A at most once.
* * * | s142485676 | Runtime Error | p03618 | Input is given from Standard Input in the following format:
A | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define PI 3.1415926535897932384626433832795
#define INF (int)1e9
typedef long long int int64;
void print() {
cout << endl;
}
void print(const char* s, bool endline = true) {
cout << s;
if (endline) print();
}
void print(char s, bool endline = true) {
cout << s;
if (endline) print();
}
void print(string s, bool endline = true) {
cout << s;
if (endline) print();
}
void print(int64 s, bool endline = true) {
cout << s;
if (endline) print();
}
void print(int s, bool endline = true) {
cout << s;
if (endline) print();
}
template <typename T, typename T2>
void print(pair<T, T2>& p, bool endline = true) {
cout << "(";
print(p.first, false);
cout << ", ";
print(p.second, false);
cout << ")";
if (endline) print();
}
template <typename T>
void print(T& t, bool endline = true) {
cout << "[";
for (auto it = t.begin(); it != t.end(); ++it) {
if (it != t.begin()) cout << ", ";
print(*it, false);
}
cout << "]";
if(endline) print();
}
template <typename T>
vector<T> operator+(const vector<T> &a, const vector<T> &b)
{
vector<T> ret;
ret.reserve( a.size() + b.size() ); // preallocate memory
ret.insert( ret.end(), a.begin(), a.end() ); // add A;
ret.insert( ret.end(), b.begin(), b.end() ); // add B;
return ret;
}
template <typename T>
vector<T> &operator+=(vector<T> &a, const vector<T> &b)
{
a.reserve( a.size() + b.size() ); // preallocate memory without erase original data
a.insert( a.end(), b.begin(), b.end() ); // add B;
return a;
}
bool c(const pair<int,int> &a, const pair<int,int> &b)
{
return (a.first + a.second > b.first + b.second);
}
int main() {
// g++ -Wall -Wextra -O2 -std=c++17 helloworld.cpp
string s;
cin >> s;
map<char, int> m;
for(auto& c : s) {
m[c]++;
}
int64 count = 1;
for(char c = 'a'; c <= 'z'; c++) {
for(char c2 = c + 1; c2 <= 'z'; c2++) {
count += m[c] * m[c2];
}
}
cout << count << endl;
return 0;
} | Statement
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and
reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain? | [{"input": "aatt", "output": "5\n \n\nYou can obtain `aatt` (don't do anything), `atat` (reverse A[2..3]), `atta`\n(reverse A[2..4]), `ttaa` (reverse A[1..4]) and `taat` (reverse A[1..3]).\n\n* * *"}, {"input": "xxxxxxxxxx", "output": "1\n \n\nWhatever substring you reverse, you'll always get `xxxxxxxxxx`.\n\n* * *"}, {"input": "abracadabra", "output": "44"}] |
If a tree with n vertices that satisfies the conditions does not exist, print
`-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1
lines. The i-th line should contain u_i and v_i with a space in between. If
there are multiple trees that satisfy the conditions, any such tree will be
accepted.
* * * | s515074028 | Runtime Error | p03248 | Input is given from Standard Input in the following format:
s | input()
print(input().split().index("1") + 1)
| Statement
You are given a string s of length n. Does a tree with n vertices that
satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree. | [{"input": "1111", "output": "-1\n \n\nIt is impossible to have a connected component of size n after removing one\nedge from a tree with n vertices.\n\n* * *"}, {"input": "1110", "output": "1 2\n 2 3\n 3 4\n \n\nIf Edge 1 or Edge 3 is removed, we will have a connected component of size 1\nand another of size 3. If Edge 2 is removed, we will have two connected\ncomponents, each of size 2.\n\n* * *"}, {"input": "1010", "output": "1 2\n 1 3\n 1 4\n \n\nRemoving any edge will result in a connected component of size 1 and another\nof size 3."}] |
If a tree with n vertices that satisfies the conditions does not exist, print
`-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1
lines. The i-th line should contain u_i and v_i with a space in between. If
there are multiple trees that satisfy the conditions, any such tree will be
accepted.
* * * | s146495272 | Wrong Answer | p03248 | Input is given from Standard Input in the following format:
s | S = input()
print(-1)
| Statement
You are given a string s of length n. Does a tree with n vertices that
satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree. | [{"input": "1111", "output": "-1\n \n\nIt is impossible to have a connected component of size n after removing one\nedge from a tree with n vertices.\n\n* * *"}, {"input": "1110", "output": "1 2\n 2 3\n 3 4\n \n\nIf Edge 1 or Edge 3 is removed, we will have a connected component of size 1\nand another of size 3. If Edge 2 is removed, we will have two connected\ncomponents, each of size 2.\n\n* * *"}, {"input": "1010", "output": "1 2\n 1 3\n 1 4\n \n\nRemoving any edge will result in a connected component of size 1 and another\nof size 3."}] |
If a tree with n vertices that satisfies the conditions does not exist, print
`-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1
lines. The i-th line should contain u_i and v_i with a space in between. If
there are multiple trees that satisfy the conditions, any such tree will be
accepted.
* * * | s689677605 | Wrong Answer | p03248 | Input is given from Standard Input in the following format:
s | #!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI():
return list(map(int, sys.stdin.readline().split()))
def I():
return int(sys.stdin.readline())
def LS():
return list(map(list, sys.stdin.readline().split()))
def S():
return list(sys.stdin.readline())[:-1]
def IR(n):
l = [None for i in range(n)]
for i in range(n):
l[i] = I()
return l
def LIR(n):
l = [None for i in range(n)]
for i in range(n):
l[i] = LI()
return l
def SR(n):
l = [None for i in range(n)]
for i in range(n):
l[i] = S()
return l
def LSR(n):
l = [None for i in range(n)]
for i in range(n):
l[i] = SR()
return l
mod = 1000000007
# A
def A():
return
# B
def B():
return
# C
def C():
n = I()
v = LI()
d = [defaultdict(int) for i in range(2)]
for i in range(n):
d[i % 2][v[i]] += 1
if len(d[0].keys()) == len(d[1].keys()) == 1:
if d[0].keys() == d[1].keys():
ans = n // 2
else:
d = [list(d[i].values()) for i in range(2)]
ans = sum(d[0]) - max(d[0]) + sum(d[1]) - max(d[1])
else:
d = [sorted(list(d[i].items()), key=lambda x: -x[1]) for i in range(2)]
if d[0][0][0] != d[1][0][0]:
ans = -d[0][0][1] - d[1][0][1]
for i in range(len(d[0])):
ans += d[0][i][1]
for i in range(len(d[1])):
ans += d[1][i][1]
else:
ans = -d[0][0][1] - d[1][1][1]
for i in range(len(d[0])):
ans += d[0][i][1]
for i in range(len(d[1])):
ans += d[1][i][1]
ans2 = -d[0][1][1] - d[1][0][1]
for i in range(len(d[0])):
ans2 += d[0][i][1]
for i in range(len(d[1])):
ans2 += d[1][i][1]
ans = min(ans, ans2)
print(ans)
# D
def D():
return
# E
def E():
s = list(map(int, S()))
if s[-1] == 1:
print(-1)
quit()
s.pop(-1)
if s != s[::-1]:
print(-1)
quit()
n = len(s)
ans = [[1, i + 2] for i in range(n)]
s = s[: n // 2 + n % 2]
m = (n + 1) // 2
k = 0
for i in range(len(s)):
k += s[i]
if k == 0:
print(-1)
quit()
if sorted(s, reverse=True) != s:
print(-1)
quit()
for i in range(k - 1):
ans[i + 1] = [i + 2, ans[i + 1][1]]
for i, j in ans:
print(i, j)
# F
def F():
return
# G
def G():
return
# H
def H():
return
# Solve
if __name__ == "__main__":
E()
| Statement
You are given a string s of length n. Does a tree with n vertices that
satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree. | [{"input": "1111", "output": "-1\n \n\nIt is impossible to have a connected component of size n after removing one\nedge from a tree with n vertices.\n\n* * *"}, {"input": "1110", "output": "1 2\n 2 3\n 3 4\n \n\nIf Edge 1 or Edge 3 is removed, we will have a connected component of size 1\nand another of size 3. If Edge 2 is removed, we will have two connected\ncomponents, each of size 2.\n\n* * *"}, {"input": "1010", "output": "1 2\n 1 3\n 1 4\n \n\nRemoving any edge will result in a connected component of size 1 and another\nof size 3."}] |
Print the minimum possible total cost incurred.
* * * | s312312775 | Wrong Answer | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | #!/usr/bin/env python
# coding: utf-8
import sys
# N, K = 5, 3
# h = list(map(int, "10 30 40 50 20".split()))
N, K = list(map(int, sys.stdin.readline().split()))
h = list(map(int, sys.stdin.readline().split()))
def test1():
dp = {0: 0.0}
def sget(i) -> float:
if i in dp:
return dp[i]
return float("inf")
def hs(i, j) -> float:
return abs(h[i] - h[j])
for i in range(1, N):
value = float("inf")
for k in range(1, K + 1):
if i - k < 0:
continue
# value = min(value, hs(i, i - k) + sget(i - k))
if i - k not in dp:
continue
value = min(value, abs(h[i] - h[i - k]) + dp[i - k])
dp[i] = value
print(int(dp[N - 1]))
def test2():
MAXN = 100002
dp = [-1] * MAXN
dp[1] = 0
def hs(i, j):
return abs(h[i - 1] - h[j - 1])
for i in range(2, K + 1):
for j in range(1, i):
if dp[i] == -1 or dp[j] + hs(i, j) < dp[i]:
dp[i] = dp[j] + hs(i, j)
for i in range(K + 1, N + 1):
for j in range(i - K, i):
if dp[i] == -1 or dp[j] + hs(i, j) < dp[i]:
dp[i] = dp[j] + hs(i, j)
print(dp[N])
def test3():
INF = 10**5
dp = [0] * (N + 1)
for i in range(2, N + 1):
dp[i] = INF
for j in range(i - 1, 0, -1):
if j < i - K:
break
dp[i] = min(dp[i], dp[j] + abs(h[i - 1] - h[j - 1]))
print(dp[N])
test3()
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s886793621 | Accepted | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | INF = float("inf")
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
input_int = lambda: int(input())
input_ints = lambda: map(int, input().split())
input_ints_list = lambda: list(input_ints())
input_str = lambda: input()
input_strs = lambda: input().split()
input_lines = lambda n, input_func: [input_func() for _ in range(n)]
import importlib
import_module = lambda module_name: importlib.import_module(module_name)
init_array_1dim = lambda value, n: [value] * n # 1次元配列を生成
init_array_2dim = lambda value, n, m: [
init_array_1dim(value, n) for _ in range(m)
] # 2次元配列を生成
gcd_base = lambda value1, value2: import_module("fractions").gcd(
value1, value2
) # 最大公約数(2値)
gcd = lambda lst: import_module("functools").reduce(
gcd_base, lst
) # 最大公約数(リスト)
lcm_base = lambda value1, value2: (value1 * value2) // gcd_base(
value1, value2
) # 最小公倍数(2値)
lcm = lambda lst: import_module("functools").reduce(
lcm_base, lst, 1
) # 最小公倍数(リスト)
permutations = lambda lst, n: import_module("itertools").permutations(lst, n) # 順列
combinations = lambda lst, n: import_module("itertools").combinations(
lst, n
) # 組み合わせ
product = lambda lst1, lst2: import_module("itertools").product(
lst1, lst2
) # 二つのリストの直積
round = lambda value: round(value) # 四捨五入
ceil = lambda value: import_module("math").ceil(value) # 切り上げ
floor = lambda value: import_module("math").floor(value) # 切り捨て
# キュー
init_q = lambda lst: import_module("collections").deque(lst)
q_pop = lambda q: q.popleft() # 先頭から取り出し
q_push = lambda q, value: q.appendleft(value) # 先頭に追加(値)
q_pushlist = lambda q, lst: q.extendleft(lst) # 先頭に追加(リスト)
q_append = lambda q, value: q.append(value) # 末尾に追加(値)
q_appendlist = lambda q, lst: q.extend(lst) # 末尾に追加(リスト)
# プライオリティキュー
init_heap = lambda a: import_module("heapq").heapify(a)
heap_push = lambda a, v: import_module("heapq").heappush(a, v)
heap_pop = lambda a: import_module("heapq").heappop(a) # 最小値を取り出す
def solution():
# ここに実装
N, K = input_ints()
h = input_ints_list()
dp = init_array_1dim(0, N)
for i in range(N):
if i == 0:
continue
temp = []
for j in range(K):
if i - j - 1 < 0:
continue
temp.append(dp[i - j - 1] + abs(h[i] - h[i - j - 1]))
dp[i] = min(temp)
print(dp[N - 1])
if __name__ == "__main__":
solution()
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s298501911 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | n, k = map(int, input().split())
h = list(map(int, input().split()))
dp = [abs(h[i] - h[0]) for i in range(k)]
for i in range(2, k):
tmp = []
for j in range(i + 1):
# tmp =[]
# print(*dp)
# print(dp[j])
# print(*h)
# print(h[i],h[j],i,j)
tmp.append(dp[j] + abs(h[i] - h[j])) # こっちはdp[j],h[j]
dp[i] = min(tmp)
for i in range(k, n):
tmp = []
for j in range(1, k + 1): # +1
tmp.append(dp[i - j] + abs(h[i] - h[i - j])) # こっちはdp[i-j],h[i-j]
dp.append(min(tmp))
print(*dp)
print(dp[n - 1])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s185320463 | Wrong Answer | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | # AtCoder Educational DP Contest - B
(n, k) = map(int, input().split())
h = [0] + list(int(x) for x in input().split())
cost = [0, 0]
# for i in range(2, n+1):
# temp = []
# for j in range(1, min(k, i)+1):
# temp.append(cost[i-j]+abs(h[i-j]-h[i]))
# cost.append(min(temp))
for i in range(2, n + 1):
temp = 10**4
for j in range(1, min(k, i) + 1):
temp = min(temp, cost[i - j] + abs(h[i - j] - h[i]))
cost.append(temp)
print(cost[n])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s994950162 | Wrong Answer | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | a, b = map(int, input().split())
x = list(map(int, input().split()))
dp = [0] + [10**10] * (a - 1)
dp = [0] + [float("inf")] * (a - 1)
dp[1] = abs(x[1] - x[0])
for i, h in enumerate(x):
for j in range(max(0, i - b), i):
dp[i] = min(dp[i], dp[j] + abs(h - x[j]))
print(dp)
print(dp)
print(dp[a - 1])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s193488060 | Wrong Answer | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | # python3
import sys
input = sys.stdin.readline
def main():
# 2 <= N <= pow(10,5), 1 <= K <= 100
N, K = [int(ele) for ele in input().split()]
h = [Node(int(ele)) for ele in input().split()]
for idx, n in enumerate(h):
if idx != 0:
s = max(0, idx - K)
n.parents = h[s:idx]
n.cal_dp()
print(h[-1].dp_val)
class Node:
def __init__(self, val):
self.val = val
self.dp_val = 1000000000000
self.parents = []
def cal_dp(self):
if self.parents == []:
self.dp_val = 0
return
for n in self.parents:
self.dp_val = min(self.dp_val, abs(n.val - self.val) + n.dp_val)
if __name__ == "__main__":
main()
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s876581984 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | imort sys
input = sys.stdin.readline
n,k = map(int,input().split())
h = list(map(int,input().split()))
dp = [10**10]*n
dp[0] = 0
for i in range(n):
for j in range(1,k+1):
if i-j >= 0:
dp[i] = min(dp[i],dp[i-j]+abs(h[i]-h[i-j]))
print(dp[n-1])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s989386661 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | import math
class Graph(object):
def __init__(self, v):
self.v = v
self.visited = [False for i in range(v)]
self.adj = [[] for i in range(v)]
self.parent = [-1 for i in range(v)]
self.distance = [0 for i in range(v)]
def AddEdge(self, a, b):
self.adj[a].append(b)
self.adj[b].append(a)
def BFS(self, start):
Q = [start]
self.visited[start] = True
while len(Q) > 0:
cur = Q.pop(0)
for child in self.adj[cur]:
if self.visited[child] == False:
self.visited[child] = True
self.distance[child] = self.distance[cur] + 1
self.parent[child] = cur
Q.append(child)
def CycleDetection_Using_BFS(self, start):
Q = [start]
self.visited[start] = True
while len(Q) > 0:
cur = Q.pop(0)
for child in self.adj[cur]:
if self.visited[child] == False:
self.visited[child] = True
self.distance[child] = self.distance[cur] + 1
self.parent[child] = cur
Q.append(child)
else:
if self.parent[cur] != child:
return True
return False
NK = list(map(int, input().split(" ")))
n, k = NK[0], NK[1]
h = list(map(int, input().split(" ")))
dp = [math.inf] * n
for i in reversed(range(n)):
m = math.inf
for j in range(1, k + 1):
Move = i + j
if Move <= n - 1:
m = min(m, dp[Move] + abs(h[i] - h[Move]))
dp[i] = m if m != math.inf else 0
print(dp[0])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s278195029 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | from sys import stdin, gettrace
import sys
if not gettrace():
def input():
return next(stdin)[:-1]
# def input():
# return stdin.buffer.readline()
def main():
def mincost(n,h):
dp=[-1 for i in range(n)]
dp[n-1]=0
dp[n-2]=abs(h[n-2]-h[n-1])
for i in range(n-3,-1,-1):
mn=min(i+k+1,n)
mnm=sys.maxsize
for j in range(i+1,mn):
mnm=min(dp[j]+abs(h[j]-h[i]),mnm)
dp[i]=mnm
return dp[0]
n,k=map(int,input().split())
h=[int(x) for x in input().split()]
print(mincost(n,h))
if __name__ == "__main__":
main() | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s455047709 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | ef knapsack(nums, KLeap):
n = len(nums)
if n == 0 or n == 1:
return 0
if n < KLeap:
return abs(nums[0] - nums[-1])
# dp[i] is min cost when reaching stone i
dp = [0] * n
for i in range(1, KLeap):
dp[i] = abs(nums[0] - nums[i])
for i in range(K+1, n):
dp[i] = min([dp[i - k] + abs(nums[i - k] - nums[i]) for k in range(1, KLeap)])
return dp[-1]
if __name__ == "__main__":
_, K = [int(x) for x in input().split()]
nums = [int(x) for x in input().split()]
print(knapsack(nums, K)) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s361569644 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | N, K = [int(i) for i in input().split()]
H = [int(i) for i in input().split()]
dp = [0] * N
for i in range(1, N):
L = []
for j in range(max(0, i-K), i):
L.append(dp[j] + abs(H[i] - H[j]))
dp[i] = min(L)
print(dp[-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s687856063 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | N, K = map(int, (input().split()))
h = list(map(int, input().split()))
dp = [float("inf")] * len(h)
dp[0] = 0
for i in range(len(h)):
for j in range(1, min(i + 1, K + 1)):
dp[i] = min(dp[i - j] + abs(h[i] - h[i - j]), dp[i])
print(dp[N - 1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s743161675 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | in, k = map(int, input().split())
h = [int(i) for i in input().split()]
# dpの最小値を変更する関数
def chmin(a, b):
if a > b:
return b
else:
return a
# 無限大の値
f_inf = float('inf')
# DP テーブルを初期化 (最小化問題なので INF に初期化)
dp = [f_inf] * (10**5+10)
# 初期条件
dp[0] = 0
for i in range(1, n):
for j in range(1, k+1):
if i - j >= 0:
dp[i] = chmin(dp[i], dp[i-j]+ abs(h[i] - h[i - j]))
print(dp[n-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s467738001 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | N, K = map(int, input().split())
h = [None] + list(map(int, input().split(' ')))
dp = [None for _ in range(N+1)]
for k in range(2,N+1):
candidate = []
for i in range(1,K+1):
if k - 1 <= 0:
break
candidate.append(dp[k-1] + abs(h[k] - h[k-1])
dp[k] = min(candidate)
print(dp[n]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s614109561 | Accepted | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def main():
nk = list(map(int, input().split()))
h = list(map(int, input().split()))
n = nk[0]
k = nk[1]
dp = [10**9] * n
dp[0] = 0
dp[1] = abs(h[1] - h[0])
for i in range(2, n):
# dp[i]=min(dp[j]+abs(h[i]-h[j]) for j in range(max(0,i-k),i))
for j in range(max(0, i - k), i):
dp[i] = min(dp[j] + abs(h[i] - h[j]), dp[i])
print(dp[-1])
if __name__ == "__main__":
main()
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s682440229 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | import sys
def main():
INF=sys.maxsize
N,K=tuple(map(int,sys.stdin.readline().split()))
h=tuple(map(int,sys.stdin.readline().split()))
dp=[INF for _ in range(N)]
dp[0]=0
for i in range(N-1):h
for j in range(1,K+1):
if i+j<N:dp[i+j]=min([dp[i+j],dp[i]+abs(h[i+j]-h[i])])
print(dp[N-1])
if __name__=='__main__':main() | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s200381618 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | #B
n,k = list(map(int,input().split()))
h = list(map(int,input().split()))
cost = [1000000]*n
for i in range(n):
if i == 0:
cost[i] = 0
continue
for j in range(1:k+1):
if i-j>=0:
cost[i] = min(cost[i],cost[i-j]+abs(h[i]-h[i-j]))
print(cost[n-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s368998716 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | n,k=map(int,input().split())
h=list(map(int,input().split()))+[0]*(k+10)
dp=[(float("inf")) for i in range(n+k+10)]
dp[0]=0
def main():
for i in range(n-1):
for j in range(k):
dp[i+j+1]=min(dp[i]+abs(h[i]-h[i+j+1]),dp[i+j+1])
print(dp[n-1])
main()
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s022511389 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | def main():
n,k= map(int,input().split())
h = [int(i) for i in input().split()]
inf = 10**7
dp = [inf]*100005
dp[0] = 0
for i in range(1,n):
for j in range(1,min(k,i)+1)
dp[i] = min(dp[i-j] + abs(h[i-j] - h[i]) )
print(dp[n-1])
main() | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s076183536 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | import numpy as np
N, K=map(int,input().split(' '))
H=np.array(list(map(int,input().split(' '))))
dp=np.zeros(N)
for i in range(N):
if i==0:
continue
elif i==1:
#0->1に移動するコストは1通り
dp[i]=(np.abs(H[1]-H[0]))
else:
#i>=2のときはiに移動するコストは
#dp[i-j]+abs(H[i-j]-H[i]) (j=1,...,min(K,i)) の最小値]
dp[i] = np.min(dp[min(0,i-K):i] + np.abs(H[min(0,i-K):i] - H[i]))
print(dp[N-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s297395102 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | n, k = map(int, input().split()) |n = int(input())
h = list(map(int, input().split())) |h = list(map(int, input().split()))
dp = [0] * n |dp = [0]*n
|
for i in range(n): |for i in range(n):
if i == 0: | if i == 0:
dp[0] = 0 | dp[0] = 0
elif i == 1: | elif i == 1:
dp[1] = abs(h[0]-h[1]) | dp[1] = abs(h[0]-h[1])
else: | else:
costs = [] | cost1 = dp[i-1] + abs(h[i-1]-h[i])
for j in range(1, k+1): | cost2 = dp[i-2] + abs(h[i-2]-h[i])
if j > i: | dp[i] = min(cost1, cost2)
break |
if abs(h[i-j]-h[i]) == 0: |print(dp[n-1])
costs.append(dp[i-j]) |
break |
costs.append(dp[i-j] + abs(h[i-j]-h[i])) |
|
# if i == 3: |
# print(costs) |
dp[i] = min(costs) |
|
#print(dp) |
print(dp[n-1]) |
|
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s453324264 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | import sys
sys.setrecursionlimit(2000000001)
def solve(n,k,ar,dp,x):
ab = abs; mn = min
if x>=n-2: return dp[x]
if dp[x] != -1: return dp[x]
m = 1e9
for i in range(x+1,mn(n,x+k+1)):
t = ab(ar[x]-ar[i])+solve(n,k,ar,dp,i)
m = t if t<m else m
dp[x] = m
# pr(f'{x} => {dp[x]}')
return dp[x]
def main():
I = lambda:map(int,sys.stdin.readline().split())
pr = lambda x:sys.stdout.write(f'{x}\n')
n,k, ar = *I(), [*I()]
dp = [-1]*(n-2) + [abs(ar[-2]-ar[-1]),0]
# pr((n,k,ar,dp))
pr(solve(n,k,ar,dp,0))
main()
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s343524600 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | n, k, *hs = [int(x) for x in open(0).read().split()]
l = len(hs)
delta = lambda a, b: abs(hs[a] - hs[b])
dp = [0]
for i in range(1, l):
cs = [dp[j] + delta(i, j) for j in range(max(0, i - k), i)]
v = min(cs)
dp.append(v)
print(dp[-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s257451842 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | N,K = map(int,(input().split()))
h = list(map(int,input().split()))
H = [0]*N
from functools import lru_cache
@lru_cache(maxsize=None)
for i in range(1,N):
if i == 1:
H[i] = abs(h[1]-h[0])
else:
Min = 1000000000
start = max((i-K),0)
for j in range(start,i):
if Min > H[j]+abs(h[i]-h[j]):
Min = H[j]+abs(h[i]-h[j])
H[i] = Min
print(H[N-1])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s904822825 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | N, K = map(int, input().split())
h = list(map(int, input().split()))
dp = [float('inf')]*N
dp[0] = 0
for i in range(1,N):
dp[i] = min(dp[j] + abs(H[i] - H[j]) for j in range(max(i-K, 0), i)
print(dp[N-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s617441347 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | n = int(input())
h = list(map(int,input().split()))
dp=[0]*n
dp[1]=abs(h[1]-h[0])
for i in range(2,n):
for j in range(max(0,i-k+1),i):
dp[i]=(min(dp[j] + abs(h[i]-h[j]),dp[i])
print(dp[n-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s705477964 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | N, K = map(int, input().split())
[*h] = map(int, input().split())
dp = [float("inf") for _ in range(N)]
dp[0] = 0
for i in range(N):
dp[i] = min(
dp[i], dp[i - j] + abs(h[i] - h[i - j]) for j in range(1, min(i, K) + 1)
)
print(dp[N - 1])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s660405887 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | import numpy as np
N, K = map(int, input().split())
H = np.array(list(map(int, input().split())))
dp = np.zero(N, dtype=int)
for i in range(1, N):
start = max(0, i-K)
dp[i] = min(dp[start:i]+np.abs(H[i]-H[start:i]))
print(dp[N-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s284113483 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | dp = [1000000000] * N
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s053640019 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | N,K=int(input())
h=[]
dp=[]
dp.append(0)
for i in range(N-K,N):
dp_N-1=min[abs(h[N-1]-h[i]) + dp[i] for j in range(N-2)]
dp.append(dp_N-1)
print(dp[N-1])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s216961389 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | import numpy as np
N, K = map(int, input().split())
H = np.array(map(int, input().split()))
dp = np.zero(N, dtype=int)
for i in range(1, N):
start = max(0, i-K)
dp[i] = min(dp[start:i]+np.abs(H[i]-H[start:i]))
print(dp[N-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s294971587 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | N, K = map(int, input().split())
h = list(map(int, input().split()))
dp = [float("inf")] * N
dp[0] = 0
for i in range(1, N):
l = min(K, i)
data = []
dp[i] = min(data, dp[i - j] + abs(h[i] - h[i - j]) for j in range(1, l + 1))
print(dp[N - 1])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s053740713 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | n,k=map(int,input().split())
step=list(map(int,input().split()))
dp=[0]*n
for i in range(1,k+1):
min=10**7
for j in range(1,i+1):
if abs(step[i]-step[i-j])<min:
min=abs(step[i]-step[i-j])
dp[i]=min
for i in range(k+1,n):
min=10**7
for j in range(1,k+1):
if abs(step[i]-step[i-j])<min:
min=abs(step[i]-step[i-j]
dp[i]=min
print(dp[n-1])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s703153414 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | import sys
input=sys.stdin.readline
import math
n,k=map(int,input().split())
z=list(map(int,input().split()))
cost=[(10**10 for i in range(len(z))]
cost[0]=0
for i in range(1,len(z)):
for t in range(1,min(i+1,k+1)):
cost[i]=min(cost[i-t]+abs(z[i]-z[i-t]),cost[i])
sys.stdout.write(str(cost[-1])+'\n')
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s248735722 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
if k>n:
k=n-1
dp=np.array([int(0) for _ in range(n)])
dp[1]=abs(a[0]-a[1])
for i in range(2,n):
ind = max(0,i-k)
dp[i]=np.minimum(np.sum(dp[ind:i],abs(a[i]-a[ind:i])))
#dp[i]=min(dp[i-1]+abs(a[i]-a[i-1]),dp[i-2]+abs(a[i]-a[i-2]))
#print(dp[n-1])
print(dp[-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s334263777 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | n,k = map(int, input().split())
nums = list(map(int, input().split()))
if n==2:
print(abs(nums[1]-nums[0]))
dp=[0]*len(nums)
dp[0]=nums[0]
dp[1]=abs(nums[1]-nums[0])
for i in range(len(nums)):
minn=-1
j=i-1
while j!=-1 and j>=i-k:
p=abs(a[j]-a[i])+dp[j]
if minn=-1 or minn>p:
minn=p
j-=1
dp[i]=minn
print(dp[-1]) | Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s140458436 | Runtime Error | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | N,K = map(int,input().split())
cost = list(map(int,input().split()))
dp = [0 for _ in range(N+10)]
for cnt in range(2,N+1):
dp[cnt] = dp[cnt-1] + abs(cost[cnt-1]-cost[cnt])
for i in range(2,K+1):
if cnt - i>=1:
dp[cnt] = min(dp[cnt],dp[cnt - i] + abs(cost[cnt] - cost[cnt - i]))
print(dp[N])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum possible total cost incurred.
* * * | s652746676 | Accepted | p03161 | Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N | ## necessary imports
# import sys
# input = sys.stdin.readline
# from math import log2, log, ceil
# swap_array function
def swaparr(arr, a, b):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
## gcd function
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if k > n - k:
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return res
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
hi = len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < x:
lo = mid + 1
else:
hi = mid
return lo
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while n % 2 == 0:
primes[2] = primes.get(2, 0) + 1
n = n // 2
for i in range(3, int(n**0.5) + 2, 2):
while n % i == 0:
primes[i] = primes.get(i, 0) + 1
n = n // i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if x == 0:
return 0
while y > 0:
if (y & 1) == 1:
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a, b):
temp = a
a = b
b = temp
return a, b
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x
while p != link[p]:
p = link[p]
while x != p:
nex = link[x]
link[x] = p
x = nex
return p
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x, y = swap(x, y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n + 1)]
p = 2
while p * p <= n:
if prime[p] == True:
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
spf[1] = 1
for i in range(2, MAXN):
spf[i] = i
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, ceil(MAXN**0.5), 2):
if spf[i] == i:
for j in range(i * i, MAXN, i):
if spf[j] == j:
spf[j] = i
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
ret = {}
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1
x = x // spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()))
## taking string array input
def str_array():
return input().strip().split()
# defining a couple constants
MOD = int(1e9) + 7
CMOD = 998244353
INF = float("inf")
NINF = -float("inf")
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
n, k = int_array()
a = int_array()
dp = [INF] * n
dp[0] = 0
for i in range(n):
for j in range(i + 1, min(n, i + k + 1)):
x = dp[i] + abs(a[j] - a[i])
dp[j] = min(dp[j], x)
print(dp[-1])
| Statement
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following
action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N. | [{"input": "5 3\n 10 30 40 50 20", "output": "30\n \n\nIf we follow the path 1 \u2192 2 \u2192 5, the total cost incurred would be |10 - 30| +\n|30 - 20| = 30.\n\n* * *"}, {"input": "3 1\n 10 20 10", "output": "20\n \n\nIf we follow the path 1 \u2192 2 \u2192 3, the total cost incurred would be |10 - 20| +\n|20 - 10| = 20.\n\n* * *"}, {"input": "2 100\n 10 10", "output": "0\n \n\nIf we follow the path 1 \u2192 2, the total cost incurred would be |10 - 10| = 0.\n\n* * *"}, {"input": "10 4\n 40 10 20 70 80 10 20 70 80 60", "output": "40\n \n\nIf we follow the path 1 \u2192 4 \u2192 8 \u2192 10, the total cost incurred would be |40 -\n70| + |70 - 70| + |70 - 60| = 40."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s442116520 | Accepted | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | from fractions import gcd
# from datetime import date, timedelta
# from heapq import *
import heapq
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
import sys
sys.setrecursionlimit(10**7)
MOD = 10**9 + 7
# input = sys.stdin.readline
def lcm(a, b):
return a * b / fractions.gcd(a, b)
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n // i)
# divisors.sort()
return divisors
def factorize(n):
fct = [] # prime factor
b, e = 2, 0 # base, exponent
while b * b <= n:
while n % b == 0:
n = n // b
e = e + 1
if e > 0:
fct.append((b, e))
b, e = b + 1, 0
if n > 1:
fct.append((n, 1))
return fct
def is_prime(n):
if n == 1:
return False
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
def primes(n):
is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False
for i in range(2, int(n**0.5) + 1):
if not is_prime[i]:
continue
for j in range(i * 2, n + 1, i):
is_prime[j] = False
return [i for i in range(n + 1) if is_prime[i]]
def modpow(a, n, mod):
res = 1
while n > 0:
if n & 1:
res = res * a % mod
a = a * a % mod
n >>= 1
return res
def modinv(a, mod):
return modpow(a, mod - 2, mod)
def cnk(a, b):
MOD = 10**9 + 7
ret = 1
for i in range(b):
ret *= a - i
ret %= MOD
ret = ret * modinv(i + 1, MOD) % MOD
return ret
def main():
n, x = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
for i in range(n - 1):
if a[i] + a[i + 1] <= x:
continue
v = a[i + 1] + a[i] - x
if a[i + 1] >= v:
a[i + 1] -= v
ans += v
else:
ans += a[i + 1]
v -= a[i + 1]
a[i + 1] = 0
a[i] -= v
ans += v
print(ans)
if __name__ == "__main__":
main()
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s774273680 | Wrong Answer | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | import sys
import math
import collections
import itertools
import array
import inspect
# Set max recursion limit
sys.setrecursionlimit(1000000)
# Debug output
def chkprint(*args):
names = {id(v): k for k, v in inspect.currentframe().f_back.f_locals.items()}
print(", ".join(names.get(id(arg), "???") + " = " + repr(arg) for arg in args))
# Binary converter
def to_bin(x):
return bin(x)[2:]
def li_input():
return [int(_) for _ in input().split()]
def gcd(n, m):
if n % m == 0:
return m
else:
return gcd(m, n % m)
def gcd_list(L):
v = L[0]
for i in range(1, len(L)):
v = gcd(v, L[i])
return v
def lcm(n, m):
return (n * m) // gcd(n, m)
def lcm_list(L):
v = L[0]
for i in range(1, len(L)):
v = lcm(v, L[i])
return v
# Width First Search (+ Distance)
def wfs_d(D, N, K):
"""
D: 隣接行列(距離付き)
N: ノード数
K: 始点ノード
"""
dfk = [-1] * (N + 1)
dfk[K] = 0
cps = [(K, 0)]
r = [False] * (N + 1)
r[K] = True
while len(cps) != 0:
n_cps = []
for cp, cd in cps:
for i, dfcp in enumerate(D[cp]):
if dfcp != -1 and not r[i]:
dfk[i] = cd + dfcp
n_cps.append((i, cd + dfcp))
r[i] = True
cps = n_cps[:]
return dfk
# Depth First Search (+Distance)
def dfs_d(v, pre, dist):
"""
v: 現在のノード
pre: 1つ前のノード
dist: 現在の距離
以下は別途用意する
D: 隣接リスト(行列ではない)
D_dfs_d: dfs_d関数で用いる,始点ノードから見た距離リスト
"""
global D
global D_dfs_d
D_dfs_d[v] = dist
for next_v, d in D[v]:
if next_v != pre:
dfs_d(next_v, v, dist + d)
return
def sigma(N):
ans = 0
for i in range(1, N + 1):
ans += i
return ans
class Combination:
def __init__(self, n, mod):
g1 = [1, 1]
g2 = [1, 1]
inverse = [0, 1]
for i in range(2, n + 1):
g1.append((g1[-1] * i) % mod)
inverse.append((-inverse[mod % i] * (mod // i)) % mod)
g2.append((g2[-1] * inverse[-1]) % mod)
self.MOD = mod
self.N = n
self.g1 = g1
self.g2 = g2
self.inverse = inverse
def __call__(self, n, r):
if r < 0 or r > n:
return 0
r = min(r, n - r)
return self.g1[n] * self.g2[r] * self.g2[n - r] % self.MOD
# --------------------------------------------
dp = None
def main():
N, X = li_input()
A = li_input()
ans = 0
for i in range(len(A)):
if A[i] > X:
ans += A[i] - X
A[i] = X
for i in range(1, len(A) - 1, 2):
s1 = A[i] + A[i - 1]
s2 = A[i] + A[i + 1]
if s1 > X or s2 > X:
s = max(s1, s2)
d = s - X
ans += d
A[i] -= d
print(ans)
main()
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s654682463 | Wrong Answer | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | def solve():
N, x = list(map(int, input().split(" ")))
candies = list(map(int, input().split(" ")))
cnt = 0
if N % 2:
for i in range(1, N, 2):
if (candies[i - 1] + candies[i] > x) and (candies[i] + candies[i + 1] > x):
cnt += max(candies[i - 1] + candies[i], candies[i] + candies[i + 1]) - x
candies[i] -= (
max(candies[i - 1] + candies[i], candies[i] + candies[i + 1]) - x
)
elif (candies[i - 1] + candies[i] > x) and (
candies[i] + candies[i + 1] <= x
):
cnt += candies[i - 1] + candies[i] - x
candies[i] -= candies[i - 1] + candies[i] - x
elif (candies[i - 1] + candies[i] <= x) and (
candies[i] + candies[i + 1] > x
):
cnt += candies[i] + candies[i + 1] - x
candies[i + 1] -= candies[i] + candies[i + 1] - x
else:
pass
else:
print("III")
if N == 2:
if sum(candies) > x:
cnt += sum(candies) - x
else:
for i in range(1, N + 1, 2):
if i == N - 1:
if candies[i - 1] + candies[i] > x:
cnt += candies[i - 1] + candies[i] - x
else:
pass
else:
if (candies[i - 1] + candies[i] > x) and (
candies[i] + candies[i + 1] > x
):
cnt += (
max(
candies[i - 1] + candies[i], candies[i] + candies[i + 1]
)
- x
)
candies[i] -= (
max(
candies[i - 1] + candies[i], candies[i] + candies[i + 1]
)
- x
)
elif (candies[i - 1] + candies[i] > x) and (
candies[i] + candies[i + 1] <= x
):
cnt += candies[i - 1] + candies[i] - x
candies[i + 1] -= candies[i - 1] + candies[i] - x
elif (candies[i - 1] + candies[i] <= x) and (
candies[i] + candies[i + 1] > x
):
cnt += candies[i] + candies[i + 1] - x
candies[i + 1] -= candies[i] + candies[i + 1] - x
else:
pass
print(cnt)
solve()
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s852539257 | Accepted | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | # @oj: atcoder
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-08-14 17:33
# @url:https://atcoder.jp/contests/abc048/tasks/arc064_a
import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
# region fastio
BUFSIZE = 8192
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def main():
n, x = map(int, input().split())
a = list(map(int, input().split()))
s = a[0]
ans = 0
for i in range(1, len(a)):
if s + a[i] > x:
temp = s + a[i] - x
ans += temp
if temp >= a[i]:
# ans+=(temp-a[i])
a[i] = 0
else:
a[i] = a[i] - temp
s = a[i]
print(ans)
if __name__ == "__main__":
main()
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s429244335 | Accepted | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | #
# Written by NoKnowledgeGG @YlePhan
# ('ω')
#
# import math
# mod = 10**9+7
# import itertools
# import fractions
# import numpy as np
# mod = 10**4 + 7
"""def kiri(n,m):
r_ = n / m
if (r_ - (n // m)) > 0:
return (n//m) + 1
else:
return (n//m)"""
""" n! mod m 階乗
mod = 1e9 + 7
N = 10000000
fac = [0] * N
def ini():
fac[0] = 1 % mod
for i in range(1,N):
fac[i] = fac[i-1] * i % mod"""
"""mod = 1e9+7
N = 10000000
pw = [0] * N
def ini(c):
pw[0] = 1 % mod
for i in range(1,N):
pw[i] = pw[i-1] * c % mod"""
"""
def YEILD():
yield 'one'
yield 'two'
yield 'three'
generator = YEILD()
print(next(generator))
print(next(generator))
print(next(generator))
"""
"""def gcd_(a,b):
if b == 0:#結局はc,0の最大公約数はcなのに
return a
return gcd_(a,a % b) # a = p * b + q"""
"""def extgcd(a,b,x,y):
d = a
if b!=0:
d = extgcd(b,a%b,y,x)
y -= (a//b) * x
print(x,y)
else:
x = 1
y = 0
return d"""
def readInts():
return list(map(int, input().split()))
def main():
n, x = readInts()
A = readInts()
ans = 0
i = 0
if sum(A[i : i + 2]) > x:
sum_ = sum(A[i : i + 2])
# preprocessing
if A[i + 1] - (sum_ - x) < 0:
A[i + 1] = 0
ans += A[i + 1]
nya = sum_ - x
A[i] -= nya
ans += nya
else:
nya = sum_ - x
A[i + 1] -= nya
ans += nya
for i in range(1, n - 1):
if sum(A[i : i + 2]) > x:
sum_ = sum(A[i : i + 2])
nya = sum_ - x
A[i + 1] -= nya
ans += nya
print(ans)
if __name__ == "__main__":
main()
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s978010511 | Accepted | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | import sys
import math
import copy
import heapq
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)
# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]
INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD - 2, MOD)
def nck(n, k, kaijyo):
return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD
def npk(n, k, kaijyo):
if k == 0 or k == n:
return n % MOD
return (kaijyo[n] * divide(kaijyo[n - k])) % MOD
def fact_and_inv(SIZE):
inv = [0] * SIZE # inv[j] = j^{-1} mod MOD
fac = [0] * SIZE # fac[j] = j! mod MOD
finv = [0] * SIZE # finv[j] = (j!)^{-1} mod MOD
inv[1] = 1
fac[0] = fac[1] = 1
finv[0] = finv[1] = 1
for i in range(2, SIZE):
inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
fac[i] = fac[i - 1] * i % MOD
finv[i] = finv[i - 1] * inv[i] % MOD
return fac, finv
def renritsu(A, Y):
# example 2x + y = 3, x + 3y = 4
# A = [[2,1], [1,3]])
# Y = [[3],[4]] または [3,4]
A = np.matrix(A)
Y = np.matrix(Y)
Y = np.reshape(Y, (-1, 1))
X = np.linalg.solve(A, Y)
# [1.0, 1.0]
return X.flatten().tolist()[0]
class TwoDimGrid:
# 2次元座標 -> 1次元
def __init__(self, h, w, wall="#"):
self.h = h
self.w = w
self.size = (h + 2) * (w + 2)
self.wall = wall
self.get_grid()
# self.init_cost()
def get_grid(self):
grid = [self.wall * (self.w + 2)]
for i in range(self.h):
grid.append(self.wall + getS() + self.wall)
grid.append(self.wall * (self.w + 2))
self.grid = grid
def init_cost(self):
self.cost = [INF] * self.size
def pos(self, x, y):
# 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
return y * (self.w + 2) + x
def getgrid(self, x, y):
return self.grid[y][x]
def get(self, x, y):
return self.cost[self.pos(x, y)]
def set(self, x, y, v):
self.cost[self.pos(x, y)] = v
return
def show(self):
for i in range(self.h + 2):
print(self.cost[(self.w + 2) * i : (self.w + 2) * (i + 1)])
def showsome(self, tgt):
for t in tgt:
print(t)
return
def showsomejoin(self, tgt):
for t in tgt:
print("".join(t))
return
def search(self):
grid = self.grid
move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
move_eight = [
(0, 1),
(0, -1),
(1, 0),
(-1, 0),
(1, 1),
(1, -1),
(-1, 1),
(-1, -1),
]
# for i in range(1, self.h+1):
# for j in range(1, self.w+1):
# cx, cy = j, i
# for dx, dy in move_eight:
# nx, ny = dx + cx, dy + cy
def solve():
n, x = getList()
nums = getList()
ans = 0
if nums[0] > x:
ans += nums[0] - x
nums[0] = x
for i in range(1, n):
t = nums[i] + nums[i - 1] - x
if t > 0:
ans += t
nums[i] -= t
print(ans)
def main():
n = getN()
for _ in range(n):
solve()
return
if __name__ == "__main__":
# main()
solve()
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s553916337 | Runtime Error | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | f,g = list(map(int,input().split()))
a = list(map(int,input().split()))
c = 0
p = 0
if a[0] > g:
c += a[0] - g
a[0] = g
while p <= f-1:
if a[p-1] + a[p] > x:
eat = a[p-1] + a[p] - x:
c += eat
a[p] -= e
p += 1
print(c) | Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s357857788 | Runtime Error | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | N,x = map(int,input().split())
a = list(map(int,input().split()))
i = 0
answer = 0
if a[0] > x:
answer = a[0] - x
a[0] = x
for i in range(N-1)
if a[i] + a[i+1] > x:
answer += a[i] + a[i+1] - x
a[i+1] = x - a[i]
print(answer)
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s772831070 | Runtime Error | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | N, x = map(int, input().split())
a = list(map(int, input().split()))
count = 0
for i in range(N-1):
while a[i]+a[i+1] > x:
if a[i]>a[i+1]:
a[i] -= 1
count += 1
else:
a[i+1] -= 1
count += 1
print(count) | Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s829281419 | Runtime Error | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | n,x=map(int,input().split())
a=list(map(int,input().split()))
ans=0
for i in range(n-1):
if a[i]+a[i+1]>x: #xを上回る時のみ操作を行う
temp=a[i]+a[i+1]-x #減らさなきゃいけない個数
ans+=temp
if a[i+1]>=temp: #減らすのは出来るだけ右側
a[i+1]-=temp
else:
a[i+1]=0
print(ans) | Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s495948161 | Runtime Error | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | import copy
[n,x]=list(map(int,input().split()))
a=list(map(int,input().split()))
a0=copy.copy(a)
ans=0
if a[0]+a[1]>x and a[0]>x:
a[0]-=a[0]-x
ans+=a0[0]-x
if a[0]+a[1]>x:
a[1]=0
ans+=a[1]
for i in range(1,n-1):
if a[i]+a[i+1]>x:
a[i+1]-=a[i]+a[i+1]-x
ans+=a[i]+a[i+1]-x
print(ans) | Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s394841880 | Runtime Error | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | import copy
[n,x]=list(map(int,input().split()))
a=list(map(int,input().split()))
a0=copy.copy(a)
ans=0
if a[0]+a[1]>x and a[0]>x:
a[0]-=a[0]-x
ans+=a[0]-x
if a[0]+a[1]>x:
a[1]=0
ans+=a[1]
for i in range(1,n-1):
if a[i]+a[i+1]>x:
a[i+1]-=a[i]+a[i+1]-x
ans+=a[i]+a[i+1]-x
print(ans) | Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s079140158 | Runtime Error | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | s = input()
n = len(s)
if s[0] == s[-1] ^ n % 2 == 0:
print("Second")
else:
print("First")
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Print the minimum number of operations required to achieve the objective.
* * * | s688852572 | Runtime Error | p03862 | The input is given from Standard Input in the following format:
N x
a_1 a_2 ... a_N | N, A = map(int, input().split())
n = 0
def pick(list, num):
4yu
for i in range(N):
x = int(input().split())
if x != A:
L.append(int(input().split())-A)
else:
n += 1
L.sort()
| Statement
There are N boxes arranged in a row. Initially, the i-th box from the left
contains a_i candies.
Snuke can perform the following operation any number of times:
* Choose a box containing at least one candy, and eat one of the candies in the chosen box.
His objective is as follows:
* Any two neighboring boxes contain at most x candies in total.
Find the minimum number of operations required to achieve the objective. | [{"input": "3 3\n 2 2 2", "output": "1\n \n\nEat one candy in the second box. Then, the number of candies in each box\nbecomes (2, 1, 2).\n\n* * *"}, {"input": "6 1\n 1 6 1 2 0 4", "output": "11\n \n\nFor example, eat six candies in the second box, two in the fourth box, and\nthree in the sixth box. Then, the number of candies in each box becomes (1, 0,\n1, 0, 0, 1).\n\n* * *"}, {"input": "5 9\n 3 1 4 1 5", "output": "0\n \n\nThe objective is already achieved without performing operations.\n\n* * *"}, {"input": "2 0\n 5 5", "output": "10\n \n\nAll the candies need to be eaten."}] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.