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 |
|---|---|---|---|---|---|---|---|
Print the minimum possible total increase of your fatigue level when you visit
all the towns.
* * * | s717316147 | Runtime Error | p03829 | The input is given from Standard Input in the following format:
N A B
X_1 X_2 ... X_N | N, A, B = map(int, input().split())
X = list(map(int, input().split()))
ans = 0
for i in range(1, N):
d = X[i] - X[i - 1]
if d * A > B:
ans += B
else:
ans += d * A
print(ans | Statement
There are N towns on a line running east-west. The towns are numbered 1
through N, in order from west to east. Each point on the line has a one-
dimensional coordinate, and a point that is farther east has a greater
coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the other towns. You have two
ways to travel:
* Walk on the line. Your _fatigue level_ increases by A each time you travel a distance of 1, regardless of direction.
* Teleport to any location of your choice. Your fatigue level increases by B, regardless of the distance covered.
Find the minimum possible total increase of your fatigue level when you visit
all the towns in these two ways. | [{"input": "4 2 5\n 1 2 5 7", "output": "11\n \n\nFrom town 1, walk a distance of 1 to town 2, then teleport to town 3, then\nwalk a distance of 2 to town 4. The total increase of your fatigue level in\nthis case is 2\u00d71+5+2\u00d72=11, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 100\n 40 43 45 105 108 115 124", "output": "84\n \n\nFrom town 1, walk all the way to town 7. The total increase of your fatigue\nlevel in this case is 84, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 2\n 24 35 40 68 72 99 103", "output": "12\n \n\nVisit all the towns in any order by teleporting six times. The total increase\nof your fatigue level in this case is 12, which is the minimum possible value."}] |
Print the minimum possible total increase of your fatigue level when you visit
all the towns.
* * * | s131734209 | Runtime Error | p03829 | The input is given from Standard Input in the following format:
N A B
X_1 X_2 ... X_N | n, a, b = map(int, input().split())
townpos = map(int, input().split())
step = townpos[0]
tsukare = 0
for x in townpos[1:]:
tsukare += min((x - step) * a, b)
step = x
print(tsukare)
| Statement
There are N towns on a line running east-west. The towns are numbered 1
through N, in order from west to east. Each point on the line has a one-
dimensional coordinate, and a point that is farther east has a greater
coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the other towns. You have two
ways to travel:
* Walk on the line. Your _fatigue level_ increases by A each time you travel a distance of 1, regardless of direction.
* Teleport to any location of your choice. Your fatigue level increases by B, regardless of the distance covered.
Find the minimum possible total increase of your fatigue level when you visit
all the towns in these two ways. | [{"input": "4 2 5\n 1 2 5 7", "output": "11\n \n\nFrom town 1, walk a distance of 1 to town 2, then teleport to town 3, then\nwalk a distance of 2 to town 4. The total increase of your fatigue level in\nthis case is 2\u00d71+5+2\u00d72=11, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 100\n 40 43 45 105 108 115 124", "output": "84\n \n\nFrom town 1, walk all the way to town 7. The total increase of your fatigue\nlevel in this case is 84, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 2\n 24 35 40 68 72 99 103", "output": "12\n \n\nVisit all the towns in any order by teleporting six times. The total increase\nof your fatigue level in this case is 12, which is the minimum possible value."}] |
Print the minimum possible total increase of your fatigue level when you visit
all the towns.
* * * | s009669589 | Accepted | p03829 | The input is given from Standard Input in the following format:
N A B
X_1 X_2 ... X_N | n, a, b, *x = map(int, open(0).read().split())
print(sum(min(b, a * (j - i)) for i, j in zip(x, x[1:])))
| Statement
There are N towns on a line running east-west. The towns are numbered 1
through N, in order from west to east. Each point on the line has a one-
dimensional coordinate, and a point that is farther east has a greater
coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the other towns. You have two
ways to travel:
* Walk on the line. Your _fatigue level_ increases by A each time you travel a distance of 1, regardless of direction.
* Teleport to any location of your choice. Your fatigue level increases by B, regardless of the distance covered.
Find the minimum possible total increase of your fatigue level when you visit
all the towns in these two ways. | [{"input": "4 2 5\n 1 2 5 7", "output": "11\n \n\nFrom town 1, walk a distance of 1 to town 2, then teleport to town 3, then\nwalk a distance of 2 to town 4. The total increase of your fatigue level in\nthis case is 2\u00d71+5+2\u00d72=11, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 100\n 40 43 45 105 108 115 124", "output": "84\n \n\nFrom town 1, walk all the way to town 7. The total increase of your fatigue\nlevel in this case is 84, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 2\n 24 35 40 68 72 99 103", "output": "12\n \n\nVisit all the towns in any order by teleporting six times. The total increase\nof your fatigue level in this case is 12, which is the minimum possible value."}] |
Print the minimum possible total increase of your fatigue level when you visit
all the towns.
* * * | s835889495 | Runtime Error | p03829 | The input is given from Standard Input in the following format:
N A B
X_1 X_2 ... X_N | n,a,b=map(int,input().split())
s=list(map(int,input().split())
t=0
for i in range(n-1):
t+=min(b,a*(s[i+1]-s[i]))
print(t) | Statement
There are N towns on a line running east-west. The towns are numbered 1
through N, in order from west to east. Each point on the line has a one-
dimensional coordinate, and a point that is farther east has a greater
coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the other towns. You have two
ways to travel:
* Walk on the line. Your _fatigue level_ increases by A each time you travel a distance of 1, regardless of direction.
* Teleport to any location of your choice. Your fatigue level increases by B, regardless of the distance covered.
Find the minimum possible total increase of your fatigue level when you visit
all the towns in these two ways. | [{"input": "4 2 5\n 1 2 5 7", "output": "11\n \n\nFrom town 1, walk a distance of 1 to town 2, then teleport to town 3, then\nwalk a distance of 2 to town 4. The total increase of your fatigue level in\nthis case is 2\u00d71+5+2\u00d72=11, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 100\n 40 43 45 105 108 115 124", "output": "84\n \n\nFrom town 1, walk all the way to town 7. The total increase of your fatigue\nlevel in this case is 84, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 2\n 24 35 40 68 72 99 103", "output": "12\n \n\nVisit all the towns in any order by teleporting six times. The total increase\nof your fatigue level in this case is 12, which is the minimum possible value."}] |
Print the minimum possible total increase of your fatigue level when you visit
all the towns.
* * * | s769084051 | Runtime Error | p03829 | The input is given from Standard Input in the following format:
N A B
X_1 X_2 ... X_N | N, A, B = map(int, input().split())
X = list(map(int, input().split()))
res = 0
for i in range(N - 1):
if X[i + 1] - X[i] > B:
res += B
else:
res += X[i + 1] = X[i]
print(res) | Statement
There are N towns on a line running east-west. The towns are numbered 1
through N, in order from west to east. Each point on the line has a one-
dimensional coordinate, and a point that is farther east has a greater
coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the other towns. You have two
ways to travel:
* Walk on the line. Your _fatigue level_ increases by A each time you travel a distance of 1, regardless of direction.
* Teleport to any location of your choice. Your fatigue level increases by B, regardless of the distance covered.
Find the minimum possible total increase of your fatigue level when you visit
all the towns in these two ways. | [{"input": "4 2 5\n 1 2 5 7", "output": "11\n \n\nFrom town 1, walk a distance of 1 to town 2, then teleport to town 3, then\nwalk a distance of 2 to town 4. The total increase of your fatigue level in\nthis case is 2\u00d71+5+2\u00d72=11, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 100\n 40 43 45 105 108 115 124", "output": "84\n \n\nFrom town 1, walk all the way to town 7. The total increase of your fatigue\nlevel in this case is 84, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 2\n 24 35 40 68 72 99 103", "output": "12\n \n\nVisit all the towns in any order by teleporting six times. The total increase\nof your fatigue level in this case is 12, which is the minimum possible value."}] |
Print the minimum possible total increase of your fatigue level when you visit
all the towns.
* * * | s930188697 | Accepted | p03829 | The input is given from Standard Input in the following format:
N A B
X_1 X_2 ... X_N | #!/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
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI():
return list(map(int, stdin.readline().split()))
def LF():
return list(map(float, stdin.readline().split()))
def LI_():
return list(map(lambda x: int(x) - 1, stdin.readline().split()))
def II():
return int(stdin.readline())
def IF():
return float(stdin.readline())
def LS():
return list(map(list, stdin.readline().split()))
def S():
return list(stdin.readline().rstrip())
def IR(n):
return [II() for _ in range(n)]
def LIR(n):
return [LI() for _ in range(n)]
def FR(n):
return [IF() for _ in range(n)]
def LFR(n):
return [LI() for _ in range(n)]
def LIR_(n):
return [LI_() for _ in range(n)]
def SR(n):
return [S() for _ in range(n)]
def LSR(n):
return [LS() for _ in range(n)]
mod = 1000000007
inf = float("INF")
# A
def A():
a, b, c, d = LI()
print(max(a * b, c * d))
return
# B
def B():
_ = II()
s = S()
d = {}
d["I"] = 1
d["D"] = -1
ans = 0
now = 0
for i in s:
now += d[i]
ans = max(ans, now)
print(ans)
return
# C
def C():
def primes2(n):
"""https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188"""
""" Returns a list of primes < n """
sieve = [True] * (n // 2)
for i in range(3, int(n**0.5) + 1, 2):
if sieve[i // 2]:
sieve[i * i // 2 :: i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]]
n = II()
prime = primes2(n + 1)
d = []
for i in prime:
b = n
f = 0
while b:
b = b // i
f += b
d.append(f % mod)
ans = 1
for i in d:
ans *= i + 1
ans %= mod
print(ans)
return
# D
def D():
n, a, b = LI()
x = LI()
ans = 0
for i in range(n - 1):
ans += min((x[i + 1] - x[i]) * a, b)
print(ans)
return
# Solve
if __name__ == "__main__":
D()
| Statement
There are N towns on a line running east-west. The towns are numbered 1
through N, in order from west to east. Each point on the line has a one-
dimensional coordinate, and a point that is farther east has a greater
coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the other towns. You have two
ways to travel:
* Walk on the line. Your _fatigue level_ increases by A each time you travel a distance of 1, regardless of direction.
* Teleport to any location of your choice. Your fatigue level increases by B, regardless of the distance covered.
Find the minimum possible total increase of your fatigue level when you visit
all the towns in these two ways. | [{"input": "4 2 5\n 1 2 5 7", "output": "11\n \n\nFrom town 1, walk a distance of 1 to town 2, then teleport to town 3, then\nwalk a distance of 2 to town 4. The total increase of your fatigue level in\nthis case is 2\u00d71+5+2\u00d72=11, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 100\n 40 43 45 105 108 115 124", "output": "84\n \n\nFrom town 1, walk all the way to town 7. The total increase of your fatigue\nlevel in this case is 84, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 2\n 24 35 40 68 72 99 103", "output": "12\n \n\nVisit all the towns in any order by teleporting six times. The total increase\nof your fatigue level in this case is 12, which is the minimum possible value."}] |
Print the minimum possible total increase of your fatigue level when you visit
all the towns.
* * * | s269906384 | Accepted | p03829 | The input is given from Standard Input in the following format:
N A B
X_1 X_2 ... X_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
def comb(n, r):
if n - r < r:
r = n - r
if r == 0:
return 1
if r == 1:
return n
numerator = [n - r + k + 1 for k in range(r)]
denominator = [k + 1 for k in range(r)]
for p in range(2, r + 1):
pivot = denominator[p - 1]
if pivot > 1:
offset = (n - r) % p
for k in range(p - 1, r, p):
numerator[k - offset] /= pivot
denominator[k] /= pivot
result = 1
for k in range(r):
if numerator[k] > 1:
result *= int(numerator[k])
return result
def bisearch(L, target):
low = 0
high = len(L) - 1
while low <= high:
mid = (low + high) // 2
guess = L[mid]
if guess == target:
return True
elif guess < target:
low = mid + 1
elif guess > target:
high = mid - 1
if guess != target:
return False
# --------------------------------------------
dp = None
def main():
N, A, B = li_input()
X = li_input()
ans = 0
for i in range(len(X) - 1):
if (X[i + 1] - X[i]) * A < B:
ans += (X[i + 1] - X[i]) * A
else:
ans += B
print(ans)
main()
| Statement
There are N towns on a line running east-west. The towns are numbered 1
through N, in order from west to east. Each point on the line has a one-
dimensional coordinate, and a point that is farther east has a greater
coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the other towns. You have two
ways to travel:
* Walk on the line. Your _fatigue level_ increases by A each time you travel a distance of 1, regardless of direction.
* Teleport to any location of your choice. Your fatigue level increases by B, regardless of the distance covered.
Find the minimum possible total increase of your fatigue level when you visit
all the towns in these two ways. | [{"input": "4 2 5\n 1 2 5 7", "output": "11\n \n\nFrom town 1, walk a distance of 1 to town 2, then teleport to town 3, then\nwalk a distance of 2 to town 4. The total increase of your fatigue level in\nthis case is 2\u00d71+5+2\u00d72=11, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 100\n 40 43 45 105 108 115 124", "output": "84\n \n\nFrom town 1, walk all the way to town 7. The total increase of your fatigue\nlevel in this case is 84, which is the minimum possible value.\n\n* * *"}, {"input": "7 1 2\n 24 35 40 68 72 99 103", "output": "12\n \n\nVisit all the towns in any order by teleporting six times. The total increase\nof your fatigue level in this case is 12, which is the minimum possible value."}] |
For each dataset, output the least penalty. | s917083600 | Runtime Error | p00643 | The first line of each data set has two numbers _h_ and _w_ , which stands for
the number of rows and columns of the grid.
Next _h_ line has _w_ integers, which stands for the number printed on the
grid. Top-left corner corresponds to northwest corner.
Row number and column number of the starting cell are given in the following
line, and those of the destination cell are given in the next line. Rows and
columns are numbered 0 to _h_ -1, 0 to _w_ -1, respectively.
Input terminates when _h_ = _w_ = 0. | T, S, E, W, N, B = range(6)
class Dice:
def __init__(self):
self.state = list(range(1, 7))
def copy(self):
dice = Dice()
dice.state = [x for x in self.state]
return dice
def _turn(self, turn):
k = self.state[turn[-1]]
for i in range(4):
self.state[turn[i]], k = k, self.state[turn[i]]
def go_south(self):
turn = [T, S, B, N]
self._turn(turn)
def go_north(self):
turn = [N, B, S, T]
self._turn(turn)
def go_east(self):
turn = [T, E, B, W]
self._turn(turn)
def go_west(self):
turn = [T, W, B, E]
self._turn(turn)
def north(self):
return self.state[N]
def south(self):
return self.state[S]
def east(self):
return self.state[E]
def west(self):
return self.state[W]
def bottom(self):
return self.state[B]
def top(self):
return self.state[T]
def goto(self, n):
func = [self.go_west, self.go_north, self.go_east, self.go_south]
func[n]()
def show(self):
d = list("TSEWNB")
for x, s in zip(d, self.state):
print(x + " : {}".format(s))
import heapq
INF = 10**9
if __name__ == "__main__":
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
while True:
dp = [
[[[INF for _ in range(7)] for i in range(7)] for j in range(10)]
for k in range(10)
]
h, w = map(int, input().split())
if h == 0:
break
cost = [list(map(int, input().split())) for _ in range(h)]
sy, sx = map(int, input().split())
gy, gx = map(int, input().split())
q = []
dice = Dice()
heapq.heappush(q, [0, sx, sy, dice])
dp[sy][sx][dice.bottom()][dice.east()]
ans = INF + 1
while q:
c, x, y, dice = heapq.heappop(q)
if x == gx and y == gy:
ans = min(ans, c)
continue
if c >= ans:
continue
else:
for i in range(4):
ddx, ddy = dx[i], dy[i]
if x + ddx >= w or x + ddx < 0 or y + ddy >= h or y + ddy < 0:
continue
else:
d = dice.copy()
d.goto(i)
new_cost = c + d.bottom() * cost[y + ddy][x + ddx]
if dp[y + ddy][x + ddx][d.bottom()][d.east()] > new_cost:
dp[y + ddy][x + ddx][d.bottom()][d.east()] = new_cost
heapq.heappush(q, [new_cost, x + ddx, y + ddy, d])
print(ans)
| G: Rolling Dice
The north country is conquered by the great shogun-sama (which means king).
Recently many beautiful dice which were made by order of the great shogun-sama
were given to all citizens of the country. All citizens received the beautiful
dice with a tear of delight. Now they are enthusiastically playing a game with
the dice.
The game is played on grid of _h_ * _w_ cells that each of which has a number,
which is designed by the great shogun-sama's noble philosophy. A player put
his die on a starting cell and move it to a destination cell with rolling the
die. After rolling the die once, he takes a penalty which is multiple of the
number written on current cell and the number printed on a bottom face of the
die, because of malicious conspiracy of an enemy country. Since the great
shogun-sama strongly wishes, it is decided that the beautiful dice are
initially put so that 1 faces top, 2 faces south, and 3 faces east. You will
find that the number initially faces north is 5, as sum of numbers on opposite
faces of a die is always 7. Needless to say, idiots those who move his die
outside the grid are punished immediately.
The great shogun-sama is pleased if some citizens can move the beautiful dice
with the least penalty when a grid and a starting cell and a destination cell
is given. Other citizens should be sent to coal mine (which may imply labor as
slaves). Write a program so that citizens can deal with the great shogun-
sama's expectations. | [{"input": "2\n 8 8\n 0 0\n 0 1\n 3 3\n 1 2 5\n 2 8 3\n 0 1 2\n 0 0\n 2 2\n 3 3\n 1 2 5\n 2 8 3\n 0 1 2\n 0 0\n 1 2\n 2 2\n 1 2\n 3 4\n 0 0\n 0 1\n 2 3\n 1 2 3\n 4 5 6\n 0 0\n 1 2\n 0 0", "output": "19\n 17\n 6\n 21"}] |
For each question, print the integer on the right side face. | s534961634 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | def move(lon, lat, com):
target, other, pop_index, insert_index = lon, lat, 0, 3
if com == "E" or com == "W":
target, other = lat, lon
if com == "S" or com == "W":
pop_index, insert_index = 3, 0
target.insert(insert_index, target.pop(pop_index))
other[0], other[2] = target[0], target[2]
def set_upper(lon, lat, upper):
com = "N" if upper in lon else "E"
for _i in range(4):
move(lon, lat, com)
if lon[0] == upper:
break
def rotate(lon, lat, com):
if com == "R":
lon[1], lat[1], lon[3], lat[3] = lat[3], lon[1], lat[1], lon[3]
elif com == "L":
lon[1], lat[1], lon[3], lat[3] = lat[1], lon[3], lat[3], lon[1]
longitude = [1, 2, 6, 5]
latitude = [1, 4, 6, 3]
values = list(input().split())
n = int(input())
for i in range(n):
U, F = input().split()
set_upper(longitude, latitude, values.index(U) + 1)
for j in range(3):
if longitude[1] == values.index(F) + 1:
break
rotate(longitude, latitude, "R")
print(values[latitude[3] - 1])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s705961135 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | # Problem - サイコロ
# input
t, s, e, w, n, b = map(int, input().split())
p_num = int(input())
# initialization
dice_dic = {}
dice_dic[t] = {s: e, e: n, n: w, w: s}
dice_dic[b] = {n: e, w: n, s: w, e: s}
dice_dic[s] = {e: t, t: w, w: b, b: e}
dice_dic[n] = {t: e, e: b, b: w, w: t}
dice_dic[e] = {s: b, b: n, n: t, t: s}
dice_dic[w] = {s: t, t: n, n: b, b: s}
# process
for i in range(p_num):
in_1, in_2 = map(int, input().split())
print(dice_dic[in_1][in_2])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s071331706 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | a = list(map(int, input().split()))
s = ["402351", "152304", "310542", "215043"]
for _ in range(int(input())):
b, c = map(int, input().split())
t = []
t.append(a)
i = 0
j = 0
while True:
if t[i][0] == b and t[i][1] == c:
print(t[i][2])
break
if i == len(t) - 1: # add if it finishes searching all path
for h in range(len(s)):
t.append([t[j][int(k)] for k in list(s[h])])
j += 1
i += 1
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s252397452 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | # coding: utf-8
tfr = (
(1, 2, 4, 3),
(0, 3, 5, 2),
(0, 1, 5, 4),
(0, 4, 5, 1),
(0, 2, 5, 3),
(1, 3, 4, 2),
)
label = list(map(int, input().split()))
q = int(input())
for i in range(q):
t, f = map(int, input().split())
idxt = label.index(t)
idxf = label.index(f)
idxr = tfr[idxt].index(idxf) + 1
if idxr == 4:
idxr = 0
print(label[tfr[idxt][idxr]])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s126398735 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | n = list(map(int, input().split()))
p = ["2354", "3146", "2651", "1562", "1364", "2453"]
for _ in range(int(input())):
t, m = map(int, input().split())
t = n.index(t)
m = str(n.index(m) + 1)
print(n[int(p[t][(p[t].index(m) + 1) % 4]) - 1])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s869075558 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | n = list(map(int, input().split()))
q = int(input())
l = [[3, 5, 2, 4], [4, 1, 6, 3], [2, 6, 1, 5], [5, 1, 6, 2], [3, 6, 1, 4], [4, 2, 5, 3]]
for i in range(q):
a, b = map(int, input().split())
for j in range(6):
if a == n[j]:
c = j
if b == n[j]:
d = j
e = d
if c < d:
e -= 1
if c + d > 5:
e -= 1
print(n[l[c][e] - 1])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s847066327 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | sokumen = {
1: [2, 3, 5, 4, 2],
2: [6, 3, 1, 4, 6],
3: [2, 6, 5, 1, 2],
4: [2, 1, 5, 6, 2],
5: [1, 3, 6, 4, 1],
6: [5, 3, 2, 4, 5],
}
number = list(map(int, input().split()))
q = int(input())
for _ in range(q):
u, f = map(int, input().split())
u = number.index(u) + 1
f = number.index(f) + 1
ans = sokumen[u][sokumen[u].index(f) + 1]
print(number[ans - 1])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s846383401 | Runtime Error | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | from Dice import Dice
dice = Dice(input().split())
count = int(input())
result = []
for i in range(count):
(top, front) = [i for i in input().split()]
dice.moveTopTo(top)
dice.moveFrontTo(front)
result.append(dice.getRight())
for s in result:
print(s)
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s858228083 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | class dice:
def __init__(self):
self.number = [i for i in range(6)]
self.work = [i for i in range(6)]
def setnum(self, s):
self.number = s
def kai(self, h):
tmp = self.number
if h == "E":
self.number = [tmp[3], tmp[1], tmp[0], tmp[5], tmp[4], tmp[2]]
elif h == "S":
self.number = [tmp[4], tmp[0], tmp[2], tmp[3], tmp[5], tmp[1]]
elif h == "W":
self.number = [tmp[2], tmp[1], tmp[5], tmp[0], tmp[4], tmp[3]]
elif h == "N":
self.number = [tmp[1], tmp[5], tmp[2], tmp[3], tmp[0], tmp[4]]
def Qright(self, up, flont, num):
uf = (up, flont)
if (
uf == (num[1], num[2])
or uf == (num[2], num[4])
or uf == (num[4], num[3])
or uf == (num[3], num[1])
):
ans = num[0]
elif (
uf == (num[0], num[3])
or uf == (num[3], num[5])
or uf == (num[5], num[2])
or uf == (num[2], num[0])
):
ans = num[1]
elif (
uf == (num[0], num[1])
or uf == (num[1], num[5])
or uf == (num[5], num[4])
or uf == (num[4], num[0])
):
ans = num[2]
elif (
uf == (num[0], num[4])
or uf == (num[4], num[5])
or uf == (num[5], num[1])
or uf == (num[1], num[0])
):
ans = num[3]
elif (
uf == (num[0], num[2])
or uf == (num[2], num[5])
or uf == (num[5], num[3])
or uf == (num[3], num[0])
):
ans = num[4]
elif (
uf == (num[1], num[3])
or uf == (num[3], num[4])
or uf == (num[4], num[2])
or uf == (num[2], num[1])
):
ans = num[5]
print(ans)
num = list(map(int, input().split()))
# kaitenn = input()
q = int(input())
dice = dice()
dice.setnum(num)
for i in range(q):
up, flont = map(int, input().split())
dice.Qright(up, flont, num)
# print(dice.number[0])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s471294532 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | dice = [int(i) for i in input().split()]
n = int(input())
for _ in range(n):
face = list(map(int, input().split()))
if face in [
[dice[0], dice[1]],
[dice[1], dice[5]],
[dice[5], dice[4]],
[dice[4], dice[0]],
]:
print(dice[2])
elif face in [
[dice[0], dice[2]],
[dice[2], dice[5]],
[dice[5], dice[3]],
[dice[3], dice[0]],
]:
print(dice[4])
elif face in [
[dice[0], dice[4]],
[dice[4], dice[5]],
[dice[5], dice[1]],
[dice[1], dice[0]],
]:
print(dice[3])
elif face in [
[dice[0], dice[3]],
[dice[3], dice[5]],
[dice[5], dice[2]],
[dice[2], dice[0]],
]:
print(dice[1])
elif face in [
[dice[1], dice[2]],
[dice[2], dice[4]],
[dice[4], dice[3]],
[dice[3], dice[1]],
]:
print(dice[0])
elif face in [
[dice[1], dice[3]],
[dice[3], dice[4]],
[dice[4], dice[2]],
[dice[2], dice[1]],
]:
print(dice[5])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s973134206 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | c = [int(i) for i in input().split()]
Q = int(input())
inp = [map(int, input().split()) for i in range(Q)]
d = [(0, 0, 1), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (1, 0, 0), (0, 0, -1)]
def north(r):
res = []
for p in r:
res.append((p[2], p[1], -p[0]))
return res
def south(r):
res = []
for p in r:
res.append((-p[2], p[1], p[0]))
return res
def east(r):
res = []
for p in r:
res.append((p[0], p[2], -p[1]))
return res
def west(r):
res = []
for p in r:
res.append((p[0], -p[2], p[1]))
return res
for k in range(Q):
x = (0, 0, 0)
y = (0, 0, 0)
a, b = inp[k]
for i in range(6):
if a == c[i]:
x = d[i]
if b == c[i]:
y = d[i]
z = (
y[1] * x[2] - y[2] * x[1],
y[2] * x[0] - y[0] * x[2],
y[0] * x[1] - y[1] * x[0],
)
for i in range(6):
if d[i] == z:
print(c[i])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s890652659 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | def N(d1):
t1 = [0 for i in range(6)]
t1[0] = d1[1]
t1[1] = d1[5]
t1[2] = d1[2]
t1[3] = d1[3]
t1[4] = d1[0]
t1[5] = d1[4]
return t1
def S(d1):
t1 = [0 for i in range(6)]
t1[0] = d1[4]
t1[1] = d1[0]
t1[2] = d1[2]
t1[3] = d1[3]
t1[4] = d1[5]
t1[5] = d1[1]
return t1
def E(d1):
t1 = [0 for i in range(6)]
t1[0] = d1[3]
t1[1] = d1[1]
t1[2] = d1[0]
t1[3] = d1[5]
t1[4] = d1[4]
t1[5] = d1[2]
return t1
def W(d1):
t1 = [0 for i in range(6)]
t1[0] = d1[2]
t1[1] = d1[1]
t1[2] = d1[5]
t1[3] = d1[0]
t1[4] = d1[4]
t1[5] = d1[3]
return t1
d1 = [0 for i in range(6)]
d1[:] = (int(x) for x in input().split())
q = int(input())
for i in range(q):
t, f = (int(x) for x in input().split())
if d1[1] == t:
d1 = N(d1)
elif d1[2] == t:
d1 = W(d1)
elif d1[3] == t:
d1 = E(d1)
elif d1[4] == t:
d1 = S(d1)
elif d1[5] == t:
d1 = N(d1)
d1 = N(d1)
if d1[2] == f:
d1 = W(d1)
d1 = S(d1)
d1 = E(d1)
elif d1[3] == f:
d1 = E(d1)
d1 = S(d1)
d1 = W(d1)
elif d1[4] == f:
d1 = E(d1)
d1 = S(d1)
d1 = S(d1)
d1 = W(d1)
print(d1[2])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s593868544 | Wrong Answer | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | def north(list):
List = []
List.append(list[1])
List.append(list[5])
List.append(list[2])
List.append(list[3])
List.append(list[0])
List.append(list[4])
return List
def west(list):
List = []
List.append(list[2])
List.append(list[1])
List.append(list[5])
List.append(list[0])
List.append(list[4])
List.append(list[3])
return List
def south(list):
List = []
List.append(list[4])
List.append(list[0])
List.append(list[2])
List.append(list[3])
List.append(list[5])
List.append(list[1])
return List
def east(list):
List = []
List.append(list[3])
List.append(list[1])
List.append(list[0])
List.append(list[5])
List.append(list[4])
List.append(list[2])
return List
dice = list(map(int, input().split()))
D = [dice]
for i in range(0, 3):
D.append(north(D[i]))
D.append(south(west(D[0])))
D.append(south(east(D[0])))
for i in range(6):
for j in range(3):
if j == 0:
D.append(east(D[i + j]))
else:
D.append(east(D[5 + j]))
x = int(input())
for i in range(x):
a, b = map(int, input().split())
for i in range(len(D)):
if a == D[i][0] and b == D[i][1]:
print(D[i][2])
break
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s423176420 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | class dice:
def __init__(self, a, b, c, d, e, f):
self.A = [a, b, c, d, e, f]
self.temp = []
def q_method(self, x, y):
for i in self.A:
self.temp.append(i)
# xとyが何番目の配列かを確認する
n = self.A.index(x)
m = self.A.index(y)
if n == 0:
if m == 1:
print(self.A[2])
elif m == 2:
print(self.A[4])
elif m == 3:
print(self.A[1])
elif m == 4:
print(self.A[3])
elif n == 1:
if m == 0:
print(self.A[3])
elif m == 2:
print(self.A[0])
elif m == 3:
print(self.A[5])
elif m == 5:
print(self.A[2])
elif n == 2:
if m == 0:
print(self.A[1])
elif m == 1:
print(self.A[5])
elif m == 4:
print(self.A[0])
elif m == 5:
print(self.A[4])
elif n == 3:
if m == 0:
print(self.A[4])
elif m == 1:
print(self.A[0])
elif m == 4:
print(self.A[5])
elif m == 5:
print(self.A[1])
elif n == 4:
if m == 0:
print(self.A[2])
elif m == 2:
print(self.A[5])
elif m == 3:
print(self.A[0])
elif m == 5:
print(self.A[3])
elif n == 5:
if m == 1:
print(self.A[3])
elif m == 2:
print(self.A[1])
elif m == 3:
print(self.A[4])
elif m == 4:
print(self.A[2])
if __name__ == "__main__":
input_text = ""
input_text = input()
array = []
array = input_text.split()
ob1 = dice(array[0], array[1], array[2], array[3], array[4], array[5])
question = input()
question = int(question)
for i in range(question):
input_order = input()
order_array = []
order_array = input_order.split()
ob1.q_method(order_array[0], order_array[1])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s723424832 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | class Dice:
def __init__(self, num):
self.top = num[0]
self.front = num[1]
self.right = num[2]
self.left = num[3]
self.back = num[4]
self.bottom = num[5]
def south_direction(self):
front = self.top
bottom = self.front
back = self.bottom
top = self.back
right = self.right
left = self.left
self.top = top
self.front = front
self.bottom = bottom
self.back = back
self.right = right
self.left = left
def north_direction(self):
back = self.top
top = self.front
front = self.bottom
bottom = self.back
right = self.right
left = self.left
self.top = top
self.front = front
self.bottom = bottom
self.back = back
self.right = right
self.left = left
def east_direction(self):
right = self.top
front = self.front
left = self.bottom
back = self.back
bottom = self.right
top = self.left
self.top = top
self.front = front
self.bottom = bottom
self.back = back
self.right = right
self.left = left
def west_direction(self):
left = self.top
front = self.front
right = self.bottom
back = self.back
top = self.right
bottom = self.left
self.top = top
self.front = front
self.bottom = bottom
self.back = back
self.right = right
self.left = left
def clockwise_rotate(self):
top = self.top
left = self.front
bottom = self.bottom
right = self.back
front = self.right
back = self.left
self.top = top
self.front = front
self.bottom = bottom
self.back = back
self.right = right
self.left = left
def print_top(self):
print(self.top)
def judge_right(self, top, front):
while True:
if self.top == top and self.front == front:
print(self.right)
break
elif top == self.front:
self.north_direction()
elif top == self.left:
self.east_direction()
elif top == self.back:
self.south_direction()
elif top == self.right:
self.west_direction()
elif top == self.bottom:
self.north_direction()
self.north_direction()
elif front == self.front:
pass
elif front == self.left:
self.clockwise_rotate()
self.clockwise_rotate()
self.clockwise_rotate()
elif front == self.back:
self.clockwise_rotate()
self.clockwise_rotate()
elif front == self.right:
self.clockwise_rotate()
num = list(map(int, input().split()))
rep = int(input())
d = Dice(num)
for i in range(rep):
top, front = map(int, input().split())
d.judge_right(top, front)
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s679190384 | Wrong Answer | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | inp = [i for i in input().split()]
n = int(input())
array = [[i for i in input().split()] for i in range(n)]
fuck = []
love = []
for i2 in range(n):
for i in range(1, 33):
if (i <= 20 and i % 5 == 0) or i == 22 or i == 27 or i == 28:
s = "N"
else:
s = "E"
if s == "E":
a = []
a.append(inp[3])
a.append(inp[1])
a.append(inp[0])
a.append(inp[5])
a.append(inp[4])
a.append(inp[2])
inp = a
if inp[0] == array[i2][0] and inp[1] == array[i2][1]:
fuck.append(inp[2])
elif s == "N":
a = []
a.append(inp[1])
a.append(inp[5])
a.append(inp[2])
a.append(inp[3])
a.append(inp[0])
a.append(inp[4])
inp = a
if inp[0] == array[i2][0] and inp[1] == array[i2][1]:
fuck.append(inp[2])
for i in fuck:
if i not in love:
love.append(i)
for i in range(len(love)):
print(love[i])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s054420636 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | n = [int(i) for i in input().split()]
count = int(input())
num = []
class Dice(object):
def __init__(self, num):
self.one = num[0]
self.two = num[1]
self.three = num[2]
self.four = num[3]
self.five = num[4]
self.six = num[5]
def right(self, top, forward):
if top == self.one:
if forward == self.two:
return self.three
elif forward == self.three:
return self.five
elif forward == self.five:
return self.four
elif forward == self.four:
return self.two
elif top == self.two:
if forward == self.six:
return self.three
elif forward == self.three:
return self.one
elif forward == self.one:
return self.four
elif forward == self.four:
return self.six
elif top == self.three:
if forward == self.two:
return self.six
elif forward == self.six:
return self.five
elif forward == self.five:
return self.one
elif forward == self.one:
return self.two
elif top == self.four:
if forward == self.two:
return self.one
elif forward == self.one:
return self.five
elif forward == self.five:
return self.six
elif forward == self.six:
return self.two
elif top == self.five:
if forward == self.one:
return self.three
elif forward == self.three:
return self.six
elif forward == self.six:
return self.four
elif forward == self.four:
return self.one
elif top == self.six:
if forward == self.two:
return self.four
elif forward == self.four:
return self.five
elif forward == self.five:
return self.three
elif forward == self.three:
return self.two
dice = Dice(n)
for i in range(count):
num.append([int(i) for i in input().split()])
for i in range(count):
print(dice.right(num[i][0], num[i][1]))
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s915375887 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | n = list(map(int, input().split()))
# print(n)
qn = int(input())
question = []
for i in range(qn):
q = list(map(int, input().split()))
question.append(q)
right = []
for i in range(qn):
x = n
if question[i][0] == x[1]: # N(北)に回転
temp = x[0]
x[0] = x[1]
x[1] = x[5]
x[5] = x[4]
x[4] = temp
elif question[i][0] == x[2]: # W(西)に回転
temp = x[0]
x[0] = x[2]
x[2] = x[5]
x[5] = x[3]
x[3] = temp
elif question[i][0] == x[3]: # E(東)に回転
temp = x[0]
x[0] = x[3]
x[3] = x[5]
x[5] = x[2]
x[2] = temp
elif question[i][0] == x[4]: # S(南)に回転
temp = x[0]
x[0] = x[4]
x[4] = x[5]
x[5] = x[1]
x[1] = temp
elif question[i][0] == x[5]: # S(南)に2回転
for k in range(2):
temp = x[0]
x[0] = x[4]
x[4] = x[5]
x[5] = x[1]
x[1] = temp
if question[i][1] != x[1]:
if question[i][1] == x[2]: # 地面から垂直に左回転
temp = x[2]
x[2] = x[4]
x[4] = x[3]
x[3] = x[1]
x[1] = temp
elif question[i][1] == x[3]: # 地面から垂直の右回転
temp = x[3]
x[3] = x[4]
x[4] = x[2]
x[2] = x[1]
x[1] = temp
elif question[i][1] == x[4]: # 地面から垂直に2回右回転
for k in range(2):
temp = x[3]
x[3] = x[4]
x[4] = x[2]
x[2] = x[1]
x[1] = temp
right.append(x[2])
for i in right:
print(i)
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s916813990 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | class Dice:
def __init__(self, l):
self.value = l
def roll(self, s):
new_list = [0] * 6
if s == "W":
new_list[0] = self.value[2]
new_list[1] = self.value[1]
new_list[2] = self.value[5]
new_list[3] = self.value[0]
new_list[4] = self.value[4]
new_list[5] = self.value[3]
if s == "E":
new_list[0] = self.value[3]
new_list[1] = self.value[1]
new_list[2] = self.value[0]
new_list[3] = self.value[5]
new_list[4] = self.value[4]
new_list[5] = self.value[2]
if s == "N":
new_list[0] = self.value[1]
new_list[1] = self.value[5]
new_list[2] = self.value[2]
new_list[3] = self.value[3]
new_list[4] = self.value[0]
new_list[5] = self.value[4]
if s == "S":
new_list[0] = self.value[4]
new_list[1] = self.value[0]
new_list[2] = self.value[2]
new_list[3] = self.value[3]
new_list[4] = self.value[5]
new_list[5] = self.value[1]
self.value = new_list
l = list(map(int, input().split()))
Dice1 = Dice(l)
n = int(input())
for i in range(n):
one, two = map(int, input().split())
one_index = Dice1.value.index(one)
two_index = Dice1.value.index(two)
if (
(one_index == 0 and two_index == 1)
or (one_index == 1 and two_index == 5)
or (one_index == 5 and two_index == 4)
or (one_index == 4 and two_index == 0)
):
print(Dice1.value[2])
if (
(one_index == 1 and two_index == 0)
or (one_index == 5 and two_index == 1)
or (one_index == 4 and two_index == 5)
or (one_index == 0 and two_index == 4)
):
print(Dice1.value[3])
if (
(one_index == 0 and two_index == 2)
or (one_index == 2 and two_index == 5)
or (one_index == 5 and two_index == 3)
or (one_index == 3 and two_index == 0)
):
print(Dice1.value[4])
if (
(one_index == 2 and two_index == 0)
or (one_index == 5 and two_index == 2)
or (one_index == 3 and two_index == 5)
or (one_index == 0 and two_index == 3)
):
print(Dice1.value[1])
if (
(one_index == 1 and two_index == 2)
or (one_index == 2 and two_index == 4)
or (one_index == 4 and two_index == 3)
or (one_index == 3 and two_index == 1)
):
print(Dice1.value[0])
if (
(one_index == 2 and two_index == 1)
or (one_index == 4 and two_index == 2)
or (one_index == 3 and two_index == 4)
or (one_index == 1 and two_index == 3)
):
print(Dice1.value[5])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s650026017 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | class Dice:
def __init__(self, a, b, c, d, e, f):
# サイコロの現在一番上にある面
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
self.f = f
self.n_list = [0, self.a, self.b, self.c, self.d, self.e, self.f]
def is_right_surface(self, top, front):
swapped = False
"""
print(f"{top=}")
print(f"{front=}")
print(f"{self.n_list.index(top)=}")
print(f"{self.n_list.index(front)=}")
"""
if self.n_list.index(top) > self.n_list.index(front):
tmp = front
front = top
top = tmp
swapped = True
if self.n_list.index(top) == 1 and self.n_list.index(front) == 2:
return self.c, self.d, swapped
if self.n_list.index(top) == 1 and self.n_list.index(front) == 3:
return self.e, self.b, swapped
if self.n_list.index(top) == 1 and self.n_list.index(front) == 4:
return self.b, self.e, swapped
if self.n_list.index(top) == 1 and self.n_list.index(front) == 5:
return self.d, self.c, swapped
if self.n_list.index(top) == 2 and self.n_list.index(front) == 3:
return self.a, self.f, swapped
if self.n_list.index(top) == 2 and self.n_list.index(front) == 4:
return self.f, self.a, swapped
if self.n_list.index(top) == 2 and self.n_list.index(front) == 6:
return self.c, self.d, swapped
if self.n_list.index(top) == 3 and self.n_list.index(front) == 5:
return self.a, self.f, swapped
if self.n_list.index(top) == 3 and self.n_list.index(front) == 6:
return self.e, self.b, swapped
if self.n_list.index(top) == 4 and self.n_list.index(front) == 5:
return self.f, self.a, swapped
if self.n_list.index(top) == 4 and self.n_list.index(front) == 6:
return self.b, self.e, swapped
if self.n_list.index(top) == 5 and self.n_list.index(front) == 6:
return self.d, self.c, swapped
def move(self, move_str):
for i in move_str:
if i == "N":
self.move_N()
elif i == "E":
self.move_E()
elif i == "W":
self.move_W()
elif i == "S":
self.move_S()
def move_N(self):
tmp1 = self.a
tmp2 = self.e
self.a = self.b
self.b = self.f
self.e = tmp1
self.f = tmp2
def move_E(self):
tmp1 = self.a
tmp2 = self.c
self.a = self.d
self.c = tmp1
self.d = self.f
self.f = tmp2
def move_W(self):
tmp1 = self.a
tmp2 = self.d
self.a = self.c
self.c = self.f
self.d = tmp1
self.f = tmp2
def move_S(self):
tmp1 = self.a
tmp2 = self.b
self.a = self.e
self.b = tmp1
self.e = self.f
self.f = tmp2
a, b, c, d, e, f = map(int, input().split())
dice = Dice(a, b, c, d, e, f)
n = int(input())
for i in range(n):
x, y = map(int, input().split())
right, left, is_swap = dice.is_right_surface(x, y)
if is_swap:
print(left)
else:
print(right)
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s341332456 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | from copy import deepcopy
from copy import copy
class Dice:
def __init__(self, labels):
self.surface = {x: labels[x - 1] for x in range(1, 6 + 1)}
def move_towards(self, direction):
if direction == "N":
self._move(1, 2, 6, 5)
elif direction == "S":
self._move(1, 5, 6, 2)
elif direction == "E":
self._move(1, 4, 6, 3)
elif direction == "W":
self._move(1, 3, 6, 4)
def get_upper(self):
return self.surface[1]
def _move(self, i, j, k, l):
temp_label = self.surface[i]
self.surface[i] = self.surface[j]
self.surface[j] = self.surface[k]
self.surface[k] = self.surface[l]
self.surface[l] = temp_label
def find_pattern(self, pattern):
dice = deepcopy(self)
if dice.surface[1] == pattern[0] and dice.surface[2] == pattern[1]:
return dice.surface[3]
pattern_tested = {"original": dice.surface}
moves = ["N", "S", "E", "W"]
def find(dice, moves):
next_moves = []
for move in moves:
if len(move) == 1:
start = "original"
else:
start = move[:-1]
dice.surface = pattern_tested[start]
dice.move_towards(move[-1])
if dice.surface[1] == pattern[0] and dice.surface[2] == pattern[1]:
right_label = dice.surface[3]
return right_label
else:
move_tested = move
pattern_tested[move_tested] = copy(dice.surface)
next_moves.extend([move + "N", move + "S", move + "E", move + "W"])
return find(dice, next_moves)
return find(dice, moves)
labels = list(map(int, input().split()))
num_questions = int(input())
questions = [list(map(int, input().split())) for _ in range(num_questions)]
dice = Dice(labels)
results = []
for question in questions:
right_label = dice.find_pattern(question)
results.append(right_label)
for result in results:
print(result)
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s472354311 | Runtime Error | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | class Converter:
d = {
"1 2": 2,
"1 3": 4,
"1 4": 1,
"1 5": 3,
"2 1": 3,
"2 3": 0,
"2 4": 5,
"2 6": 2,
"3 1": 1,
"3 2": 5,
"3 5": 0,
"3 6": 4,
"4 1": 4,
"4 2": 0,
"4 5": 5,
"4 6": 1,
"5 1": 2,
"5 3": 5,
"5 4": 0,
"5 6": 3,
"6 2": 3,
"6 3": 1,
"6 4": 4,
"6 5": 2,
}
def __init__(self, s):
self.pip = s.split()
def __call__(self, s):
print(self.pip[self.d[s]])
cv = Converter(input())
n = int(input())
for _ in range(n):
cv(input())
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s780727302 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | _rule = {
"N": (1, 5, 2, 3, 0, 4),
"S": (4, 0, 2, 3, 5, 1),
"E": (0, 3, 1, 4, 2, 5),
"W": (0, 2, 4, 1, 3, 5),
}
_idx = {"top": 0, "front": 1, "right": 2, "left": 3, "back": 4, "bottom": 5}
_idxmap = ((1, 2), (1, 1), (2, 1), (0, 1), (3, 1), (1, 0))
def motion(dlist, direction):
templist = dlist
for i in range(len(direction)):
templist = [templist[r] for r in _rule[direction[i]]]
return templist
def stopmotion(dlist, num, distination):
return dlist.index(num) == _idxmap[distination]
def search(dlist, top, front):
ret = ""
prepos = _idxmap[dlist.index(top)]
topxpos, topypos = _idxmap[0]
xpos = topxpos - prepos[0]
ypos = topypos - prepos[1]
if xpos <= 0:
ret = "W" * abs(xpos)
else:
ret = "E" * abs(xpos)
ret += "N" * abs(ypos)
templist = motion(x, ret)
ret = ""
prepos = _idxmap[templist.index(front)]
frontxpos, frontypos = _idxmap[1]
xpos = frontxpos - prepos[0]
if xpos <= 0:
ret = "W" * abs(xpos)
else:
ret = "E" * abs(xpos)
return motion(templist, ret)
x = input().split()
for _ in range(int(input())):
top, front = input().split()
templist = search(x, top, front)
print(templist[_idx["right"]])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s685521347 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | class Dice:
def __init__(self, nums):
self.face = nums
def rolltoTop(self, dicenum):
num = 0
for i, val in enumerate(self.face):
if dicenum == val:
num = i
break
if num == 1:
self.roll("N")
elif num == 2:
self.roll("W")
elif num == 3:
self.roll("E")
elif num == 4:
self.roll("S")
elif num == 5:
self.roll("NN")
def roll(self, actions):
for act in actions:
t = 0
if act == "E":
t = self.face[0]
self.face[0] = self.face[3]
self.face[3] = self.face[5]
self.face[5] = self.face[2]
self.face[2] = t
elif act == "N":
t = self.face[0]
self.face[0] = self.face[1]
self.face[1] = self.face[5]
self.face[5] = self.face[4]
self.face[4] = t
elif act == "S":
t = self.face[0]
self.face[0] = self.face[4]
self.face[4] = self.face[5]
self.face[5] = self.face[1]
self.face[1] = t
elif act == "W":
t = self.face[0]
self.face[0] = self.face[2]
self.face[2] = self.face[5]
self.face[5] = self.face[3]
self.face[3] = t
elif act == "M":
t = self.face[1]
self.face[1] = self.face[2]
self.face[2] = self.face[4]
self.face[4] = self.face[3]
self.face[3] = t
diceface = [int(val) for val in input().split(" ")]
dice = Dice(diceface)
q = int(input())
for i in range(q):
topnum, frontnum = [int(val) for val in input().split(" ")]
dice.rolltoTop(topnum)
while dice.face[1] != frontnum:
dice.roll("M")
print(dice.face[2])
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
For each question, print the integer on the right side face. | s477779243 | Accepted | p02384 | In the first line, six integers assigned to faces are given in ascending order
of their corresponding labels. In the second line, the number of questions $q$
is given.
In the following $q$ lines, $q$ questions are given. Each question consists of
two integers on the top face and the front face respectively. | class Dice(object):
def __init__(self, nums):
from collections import deque
self.ns = deque([nums[4], nums[0], nums[1]])
self.we = deque([nums[3], nums[0], nums[2]])
self.bk = deque([nums[5]])
def __str__(self):
return str({"ns": self.ns, "we": self.we, "bk": self.bk})
def operation(self, o):
if o == "N":
self.n()
elif o == "S":
self.s()
elif o == "W":
self.w()
elif o == "E":
self.e()
else:
raise BaseException("invalid", o)
def n(self):
self.ns.append(self.bk.popleft())
self.bk.append(self.ns.popleft())
self.we[1] = self.ns[1]
def s(self):
self.ns.appendleft(self.bk.pop())
self.bk.appendleft(self.ns.pop())
self.we[1] = self.ns[1]
def w(self):
self.we.append(self.bk.popleft())
self.bk.append(self.we.popleft())
self.ns[1] = self.we[1]
def e(self):
self.we.appendleft(self.bk.pop())
self.bk.appendleft(self.we.pop())
self.ns[1] = self.we[1]
def rotate_right(self):
tmp = self.ns
tmp.reverse()
self.ns = self.we
self.we = tmp
def fit_top_s(self, top, s):
while self.get_top() != top:
if top in self.ns:
self.n()
elif top in self.we:
self.w()
else:
self.n()
self.n()
while self.get_s() != s:
self.rotate_right()
def get_top(self):
return self.ns[1]
def get_s(self):
return self.ns[2]
def get_e(self):
return self.we[2]
def resolve():
nums = [int(i) for i in input().split()]
dc = Dice(nums)
q = int(input())
for _ in range(q):
top, s = [int(i) for i in input().split()]
dc.fit_top_s(top, s)
print(dc.get_e())
resolve()
| Dice II
Construct a dice from a given sequence of integers in the same way as Dice I.
You are given integers on the top face and the front face after the dice was
rolled in the same way as Dice I. Write a program to print an integer on the
right side face.
 | [{"input": "2 3 4 5 6\n 3\n 6 5\n 1 3\n 3 2", "output": "5\n 6"}] |
If there exist no reorderings that satisfy the condition, print `No`.
If there exists a reordering that satisfies the condition, print `Yes` on the
first line. After that, print a reordering of B on the second line, separating
terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print
any of them.
* * * | s054708435 | Wrong Answer | p02557 | Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N | #!/usr/bin/env python3
from heapq import heappush, heappop
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)
def solve(N, AS, BS):
acount = [0] * (N + 10)
bcount = [0] * (N + 10)
for i in range(N):
acount[AS[i]] += 1
bcount[BS[i]] += 1
overlap = []
queue = []
for i in range(N + 10):
if acount[i] + bcount[i] > N:
print("No")
return
if acount[i] and bcount[i]:
overlap.append(i)
if bcount[i]:
heappush(queue, (-acount[i] - bcount[i], i))
ret = []
for i in range(N):
cx, x = heappop(queue)
if x == AS[i]:
# use another number
try:
cy, y = heappop(queue)
except:
print("No")
return
ret.append(y)
bcount[y] -= 1
if bcount[y]:
heappush(queue, (cy + 1, y))
heappush(queue, (cx, x))
else:
ret.append(x)
bcount[x] -= 1
if bcount[x]:
heappush(queue, (cx + 1, x))
print("Yes")
print(*ret, sep=" ")
def main():
# parse input
N = int(input())
AS = list(map(int, input().split()))
BS = list(map(int, input().split()))
solve(N, AS, BS)
# tests
T01 = """
2
1 1
1 1
"""
TEST_T01 = """
>>> as_input(T01)
>>> main()
No
"""
T02 = """
2
1 1
1 2
"""
TEST_T02 = """
>>> as_input(T02)
>>> main()
No
"""
T03 = """
2
1 3
2 3
"""
TEST_T03 = """
>>> as_input(T03)
>>> main()
Yes
3 2
"""
T04 = """
2
1 2
1 3
"""
TEST_T04 = """
>>> as_input(T04)
>>> main()
Yes
3 1
"""
T05 = """
2
1 2
1 2
"""
TEST_T05 = """
>>> as_input(T05)
>>> main()
Yes
2 1
"""
T1 = """
6
1 1 1 2 2 3
1 1 1 2 2 3
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
Yes
2 2 3 1 1 1
"""
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
Given are two sequences A and B, both of length N. A and B are each sorted in
the ascending order. Check if it is possible to reorder the terms of B so that
for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output
any of the reorderings that achieve it. | [{"input": "6\n 1 1 1 2 2 3\n 1 1 1 2 2 3", "output": "Yes\n 2 2 3 1 1 1\n \n\n* * *"}, {"input": "3\n 1 1 2\n 1 1 3", "output": "No\n \n\n* * *"}, {"input": "4\n 1 1 2 3\n 1 2 3 3", "output": "Yes\n 3 3 1 2"}] |
If there exist no reorderings that satisfy the condition, print `No`.
If there exists a reordering that satisfies the condition, print `Yes` on the
first line. After that, print a reordering of B on the second line, separating
terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print
any of them.
* * * | s595088674 | Accepted | p02557 | Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N | from collections import Counter, deque
from random import randint
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
CA = Counter(A)
CB = Counter(B)
keys = set(A + B)
M = 0
for k in keys:
M = max(M, CA[k] + CB[k])
if M > N:
print("No")
exit()
CB = CB.most_common()
L, R = [], []
for i, x in enumerate(CB):
if i % 2 == 0:
L.append(list(x))
else:
R.append(list(x))
X = deque(L + R[::-1])
y = L + R
ans = [None] * N
for i in range(N):
if (X[0][0] != A[i]) and (X[-1][0] != A[i]):
if X[0][1] > X[-1][1]:
ans[i] = X[0][0]
X[0][1] -= 1
if X[0][1] == 0:
X.popleft()
else:
ans[i] = X[-1][0]
X[-1][1] -= 1
if X[-1][1] == 0:
X.pop()
elif X[0][0] != A[i]:
ans[i] = X[0][0]
X[0][1] -= 1
if X[0][1] == 0:
X.popleft()
else:
ans[i] = X[-1][0]
X[-1][1] -= 1
if X[-1][1] == 0:
X.pop()
for i in range(10):
m = randint(0, N - 1)
for i in range(N):
if ans[i] != A[i]:
continue
ans[i], ans[m] = ans[m], ans[i]
m += 1
m %= N
print("Yes")
print(*ans, sep=" ")
| Statement
Given are two sequences A and B, both of length N. A and B are each sorted in
the ascending order. Check if it is possible to reorder the terms of B so that
for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output
any of the reorderings that achieve it. | [{"input": "6\n 1 1 1 2 2 3\n 1 1 1 2 2 3", "output": "Yes\n 2 2 3 1 1 1\n \n\n* * *"}, {"input": "3\n 1 1 2\n 1 1 3", "output": "No\n \n\n* * *"}, {"input": "4\n 1 1 2 3\n 1 2 3 3", "output": "Yes\n 3 3 1 2"}] |
If there exist no reorderings that satisfy the condition, print `No`.
If there exists a reordering that satisfies the condition, print `Yes` on the
first line. After that, print a reordering of B on the second line, separating
terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print
any of them.
* * * | s635519133 | Runtime Error | p02557 | Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N | import os
from io import BytesIO, IOBase
import sys
from collections import Counter
def main():
n = int(input())
ans = "Yes"
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = Counter(a)
d = Counter(b)
for i in c:
if (n - c[i]) < d[i]:
ans = "No"
break
if ans == "Yes":
for i in d:
if (n - d[i]) < c[i]:
ans = "No"
break
if ans == "Yes":
b.reverse()
e = []
for i in range(n):
if a[i] == b[i]:
e.append(i)
if e != []:
e.reverse()
for i in range(n):
if a[i] != b[i] and a[i] != b[e[-1]]:
b[e[-1]], b[i] = b[i], b[e[-1]]
e.pop()
if e == []:
break
for i in range(n):
if a[i] != b[i] and a[i] != b[e[-1]]:
b[e[-1]], b[i] = b[i], b[e[-1]]
e.pop()
if e == []:
break
if e == []:
ans = "Yes"
else:
ans = "No"
print(ans)
if ans == "Yes":
print(*b)
# 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")
if __name__ == "__main__":
main()
| Statement
Given are two sequences A and B, both of length N. A and B are each sorted in
the ascending order. Check if it is possible to reorder the terms of B so that
for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output
any of the reorderings that achieve it. | [{"input": "6\n 1 1 1 2 2 3\n 1 1 1 2 2 3", "output": "Yes\n 2 2 3 1 1 1\n \n\n* * *"}, {"input": "3\n 1 1 2\n 1 1 3", "output": "No\n \n\n* * *"}, {"input": "4\n 1 1 2 3\n 1 2 3 3", "output": "Yes\n 3 3 1 2"}] |
If there exist no reorderings that satisfy the condition, print `No`.
If there exists a reordering that satisfies the condition, print `Yes` on the
first line. After that, print a reordering of B on the second line, separating
terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print
any of them.
* * * | s372208664 | Wrong Answer | p02557 | Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
# cntb = [0]*n
# for i in b:
# cntb[i] += 1
print("No")
# ans = [0]*n
# l = 0
# cnt = [0]*n
# for i in range(600):
# for j in range(n):
# if cnt[j] != 0:
# continue
# if a[l] != b[j]:
# ans[l] = b[j]
# cnt[j] = 1
# l+=1
# if l<n:
# print("No")
# else:
# print("Yes")
# print(*ans)
| Statement
Given are two sequences A and B, both of length N. A and B are each sorted in
the ascending order. Check if it is possible to reorder the terms of B so that
for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output
any of the reorderings that achieve it. | [{"input": "6\n 1 1 1 2 2 3\n 1 1 1 2 2 3", "output": "Yes\n 2 2 3 1 1 1\n \n\n* * *"}, {"input": "3\n 1 1 2\n 1 1 3", "output": "No\n \n\n* * *"}, {"input": "4\n 1 1 2 3\n 1 2 3 3", "output": "Yes\n 3 3 1 2"}] |
If there exist no reorderings that satisfy the condition, print `No`.
If there exists a reordering that satisfies the condition, print `Yes` on the
first line. After that, print a reordering of B on the second line, separating
terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print
any of them.
* * * | s137079058 | Wrong Answer | p02557 | Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N | print('No') | Statement
Given are two sequences A and B, both of length N. A and B are each sorted in
the ascending order. Check if it is possible to reorder the terms of B so that
for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output
any of the reorderings that achieve it. | [{"input": "6\n 1 1 1 2 2 3\n 1 1 1 2 2 3", "output": "Yes\n 2 2 3 1 1 1\n \n\n* * *"}, {"input": "3\n 1 1 2\n 1 1 3", "output": "No\n \n\n* * *"}, {"input": "4\n 1 1 2 3\n 1 2 3 3", "output": "Yes\n 3 3 1 2"}] |
If there exist no reorderings that satisfy the condition, print `No`.
If there exists a reordering that satisfies the condition, print `Yes` on the
first line. After that, print a reordering of B on the second line, separating
terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print
any of them.
* * * | s251490743 | Accepted | p02557 | Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N | import sys
readline = sys.stdin.readline
N = int(readline())
A = list(map(int, readline().split()))
B = list(map(int, readline().split()))
from collections import Counter
cA = Counter(A)
cB = Counter(B)
# 両チームに入っている文字の合計数が多い順に処理していく
# heapqで、(両方に入っている個数, Bにいる個数, その数)
# 使うごとに、1つ目、2つ目の要素を-1してもう一度heappush
import heapq as hq
q = []
hq.heapify(q)
for key, value in cB.items():
if key in cA:
hq.heappush(q, (-(value + cA[key]), value, key))
if value + cA[key] > N:
print("No")
exit(0)
else:
hq.heappush(q, (-value, value, key))
print("Yes")
a_ind = 0
ans = []
while a_ind < N:
keep = []
while True:
allcnt, bcnt, key = hq.heappop(q)
allcnt *= -1
if A[a_ind] == key:
keep.append((allcnt, bcnt, key))
else:
ans.append(key)
if bcnt - 1 > 0:
hq.heappush(q, (-(allcnt - 1), bcnt - 1, key))
break
for k in keep:
hq.heappush(q, k)
a_ind += 1
print(*ans)
| Statement
Given are two sequences A and B, both of length N. A and B are each sorted in
the ascending order. Check if it is possible to reorder the terms of B so that
for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output
any of the reorderings that achieve it. | [{"input": "6\n 1 1 1 2 2 3\n 1 1 1 2 2 3", "output": "Yes\n 2 2 3 1 1 1\n \n\n* * *"}, {"input": "3\n 1 1 2\n 1 1 3", "output": "No\n \n\n* * *"}, {"input": "4\n 1 1 2 3\n 1 2 3 3", "output": "Yes\n 3 3 1 2"}] |
If there exist no reorderings that satisfy the condition, print `No`.
If there exists a reordering that satisfies the condition, print `Yes` on the
first line. After that, print a reordering of B on the second line, separating
terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print
any of them.
* * * | s926600531 | Accepted | p02557 | Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N | """
和がN以下なら恐れくYES
過半数にならないようにとっていけばいい
和がちょうどNなのが2つあったら、それを取る
和がNになるやつが現れるまでは自由にとり
N個になったら、それ+1個を取る
"""
import sys
from sys import stdin
# 0-indexed , 半開区間[a,b)
# calc変更で演算変更
class SegTree:
def __init__(self, N, first):
self.NO = 2 ** (N - 1).bit_length()
self.First = first
self.data = [first] * (2 * self.NO)
def calc(self, l, r):
return max(l, r)
def update(self, ind, x):
ind += self.NO - 1
self.data[ind] = x
while ind >= 0:
ind = (ind - 1) // 2
self.data[ind] = self.calc(self.data[2 * ind + 1], self.data[2 * ind + 2])
def query(self, l, r):
L = l + self.NO
R = r + self.NO
s = self.First
while L < R:
if R & 1:
R -= 1
s = self.calc(s, self.data[R - 1])
if L & 1:
s = self.calc(s, self.data[L - 1])
L += 1
L >>= 1
R >>= 1
return s
def get(self, ind):
ind += self.NO - 1
return self.data[ind]
N = int(stdin.readline())
A = list(map(int, stdin.readline().split()))
B = list(map(int, stdin.readline().split()))
nA = [0] * (N + 1)
nB = [0] * (N + 1)
nS = [0] * (N + 1)
for i in A:
nA[i] += 1
nS[i] += 1
for i in B:
nB[i] += 1
nS[i] += 1
if max(nS) > N:
print("No")
sys.exit()
print("Yes")
ST = SegTree(N + 1, (float("-inf"), 0))
for i in range(N):
ST.update(i, (nS[i], i))
B.sort()
B.reverse()
out = None
ans = []
for i in range(N):
num, inds = ST.query(0, N + 1)
if num == N - i:
out = inds
break
if A[-1] == B[-1]:
B.reverse()
nas, tmp = ST.get(A[-1])
ST.update(A[-1], (nas - 1, A[-1]))
nab, tmp = ST.get(B[-1])
ST.update(B[-1], (nab - 1, B[-1]))
ans.append((A[-1], B[-1]))
del A[-1]
del B[-1]
if out != None:
for i in A:
if i != out:
ans.append((i, out))
for i in B:
if i != out:
ans.append((out, i))
ans.sort()
pla = []
for aa, bb in ans:
pla.append(bb)
print(*pla)
| Statement
Given are two sequences A and B, both of length N. A and B are each sorted in
the ascending order. Check if it is possible to reorder the terms of B so that
for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output
any of the reorderings that achieve it. | [{"input": "6\n 1 1 1 2 2 3\n 1 1 1 2 2 3", "output": "Yes\n 2 2 3 1 1 1\n \n\n* * *"}, {"input": "3\n 1 1 2\n 1 1 3", "output": "No\n \n\n* * *"}, {"input": "4\n 1 1 2 3\n 1 2 3 3", "output": "Yes\n 3 3 1 2"}] |
If there exist no reorderings that satisfy the condition, print `No`.
If there exists a reordering that satisfies the condition, print `Yes` on the
first line. After that, print a reordering of B on the second line, separating
terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print
any of them.
* * * | s244726320 | Accepted | p02557 | Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N | N = int(input())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
C = [0] * N
D = [0] * N
c = d = 0
for i in range(N):
a = A[i]
b = B[i]
if C[a - 1] == 0:
for j in range(c, a):
C[j] = C[c]
c = a - 1
C[c] = C[c - 1] + 1
else:
C[a - 1] += 1
if D[b - 1] == 0:
for j in range(d, b):
D[j] = D[d]
d = b - 1
D[d] = D[d - 1] + 1
else:
D[b - 1] += 1
for j in range(c, N):
C[j] = C[c]
for j in range(d, N):
D[j] = D[d]
E = [0] * N
for i in range(N):
if i == 0:
E[i] = C[i] + D[i]
else:
E[i] = C[i] - C[i - 1] + D[i] - D[i - 1]
# print(C,D,E)
if max(E) > N:
print("No")
else:
for i in range(N):
if i == 0:
x = C[i]
if x < C[i] - D[i - 1]:
x = C[i] - D[i - 1]
B_ = [0] * N
# print(x)
for i in range(N):
B_[(i + x) % N] = B[i]
print("Yes")
print(*B_, sep=" ")
| Statement
Given are two sequences A and B, both of length N. A and B are each sorted in
the ascending order. Check if it is possible to reorder the terms of B so that
for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output
any of the reorderings that achieve it. | [{"input": "6\n 1 1 1 2 2 3\n 1 1 1 2 2 3", "output": "Yes\n 2 2 3 1 1 1\n \n\n* * *"}, {"input": "3\n 1 1 2\n 1 1 3", "output": "No\n \n\n* * *"}, {"input": "4\n 1 1 2 3\n 1 2 3 3", "output": "Yes\n 3 3 1 2"}] |
Print the minimum number of operations required.
* * * | s451357467 | Accepted | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | n = int(input())
b = [0] * (n + 1)
for p in (int(input()) for _ in range(n)):
b[p] = b[p - 1] + 1
print(n - max(b))
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s447886846 | Accepted | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | # -*- coding: utf-8 -*-
#############
# Libraries #
#############
import sys
input = sys.stdin.readline
import math
# from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache
#############
# Constants #
#############
MOD = 10**9 + 7
INF = float("inf")
AZ = "abcdefghijklmnopqrstuvwxyz"
#############
# Functions #
#############
######INPUT######
def I():
return int(input().strip())
def S():
return input().strip()
def IL():
return list(map(int, input().split()))
def SL():
return list(map(str, input().split()))
def ILs(n):
return list(int(input()) for _ in range(n))
def SLs(n):
return list(input().strip() for _ in range(n))
def ILL(n):
return [list(map(int, input().split())) for _ in range(n)]
def SLL(n):
return [list(map(str, input().split())) for _ in range(n)]
######OUTPUT######
def P(arg):
print(arg)
return
def Y():
print("Yes")
return
def N():
print("No")
return
def E():
exit()
def PE(arg):
print(arg)
exit()
def YE():
print("Yes")
exit()
def NE():
print("No")
exit()
#####Shorten#####
def DD(arg):
return defaultdict(arg)
#####Inverse#####
def inv(n):
return pow(n, MOD - 2, MOD)
######Combination######
kaijo_memo = []
def kaijo(n):
if len(kaijo_memo) > n:
return kaijo_memo[n]
if len(kaijo_memo) == 0:
kaijo_memo.append(1)
while len(kaijo_memo) <= n:
kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
return kaijo_memo[n]
gyaku_kaijo_memo = []
def gyaku_kaijo(n):
if len(gyaku_kaijo_memo) > n:
return gyaku_kaijo_memo[n]
if len(gyaku_kaijo_memo) == 0:
gyaku_kaijo_memo.append(1)
while len(gyaku_kaijo_memo) <= n:
gyaku_kaijo_memo.append(
gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo), MOD - 2, MOD) % MOD
)
return gyaku_kaijo_memo[n]
def nCr(n, r):
if n == r:
return 1
if n < r or r < 0:
return 0
ret = 1
ret = ret * kaijo(n) % MOD
ret = ret * gyaku_kaijo(r) % MOD
ret = ret * gyaku_kaijo(n - r) % MOD
return ret
######Factorization######
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-(n**0.5) // 1)) + 1):
if temp % i == 0:
cnt = 0
while temp % i == 0:
cnt += 1
temp //= i
arr.append([i, cnt])
if temp != 1:
arr.append([temp, 1])
if arr == []:
arr.append([n, 1])
return arr
#####MakeDivisors######
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)
return divisors
#####MakePrimes######
def make_primes(N):
max = int(math.sqrt(N))
seachList = [i for i in range(2, N + 1)]
primeNum = []
while seachList[0] <= max:
primeNum.append(seachList[0])
tmp = seachList[0]
seachList = [i for i in seachList if i % tmp != 0]
primeNum.extend(seachList)
return primeNum
#####GCD#####
def gcd(a, b):
while b:
a, b = b, a % b
return a
#####LCM#####
def lcm(a, b):
return a * b // gcd(a, b)
#####BitCount#####
def count_bit(n):
count = 0
while n:
n &= n - 1
count += 1
return count
#####ChangeBase#####
def base_10_to_n(X, n):
if X // n:
return base_10_to_n(X // n, n) + [X % n]
return [X % n]
def base_n_to_10(X, n):
return sum(int(str(X)[-i - 1]) * n**i for i in range(len(str(X))))
def base_10_to_n_without_0(X, n):
X -= 1
if X // n:
return base_10_to_n_without_0(X // n, n) + [X % n]
return [X % n]
#####IntLog#####
def int_log(n, a):
count = 0
while n >= a:
n //= a
count += 1
return count
#############
# Main Code #
#############
N = I()
A = ILs(N)
START = []
f = [0 for i in range(N + 1)]
for a in A:
if f[a - 1] == 0:
START.append(a)
f[a] = 1
else:
f[a] = 1
START.sort()
dic = {k: [] for k in START}
for a in A:
p = bisect.bisect(START, a)
dic[START[p - 1]].append(a)
print(N - max(len(dic[k]) for k in START))
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s951711517 | Accepted | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | import sys
import math
import copy
import random
from heapq import heappush, heappop, heapify
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 BIT:
# A1 ... AnのBIT(1-indexed)
def __init__(self, n):
self.n = n
self.BIT = [0] * (n + 2)
# A1 ~ Aiまでの和 O(logN)
def query(self, idx):
res_sum = 0
while idx > 0:
res_sum += self.BIT[idx]
idx -= idx & (-idx)
return res_sum
# Ai += x O(logN)
def update(self, idx, x):
# print(idx)
while idx <= self.n:
# print(idx)
self.BIT[idx] += x
idx += idx & (-idx)
return
def show(self):
print(self.BIT)
def solve():
n = getN()
li = []
for i in range(n):
li.append(getN())
slis = [0 for i in range(n + 10)]
for num in li:
slis[num] = slis[num - 1] + 1
print(n - max(slis))
def main():
n = getN()
for _ in range(n):
s = "".join([random.choice(["F", "T"]) for i in range(20)])
print(s)
solve(s, 1, 0)
return
if __name__ == "__main__":
# main()
solve()
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s776508238 | Runtime Error | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | a, b, c, k = map(int, input().split())
if k % 2 == 0:
print(a - b)
else:
print(b - a)
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s238512815 | Runtime Error | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | n = int(input())
f, s = n // 2, n // 2 + 1
p = [int(input()) for _ in range(n)]
fi = p.index(f)
si = p.index(s)
ans = 0
if fi > si:
ans += 1
for i in range(fi - 1, -1, -1):
if p[i] == f - 1:
f -= 1
for i in range(si + 1, n):
if p[i] == s + 1:
s += 1
ans += f - 1 + n - s
print(f - 1 + n - s)
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s130457560 | Runtime Error | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | def main():
N=int(input())
P=[0]*N
p=[False]*(N+1)
P[0]=int(input())
for i in range(N-1):
P[i+1=int(input())
if P[-1]-1 in P[:-1]:
p[P[-1]-1] = True
ans=0
j=0
for i in range(N):
if p[i]==True:
j+=1
else:
ans=max(ans,j)
j=0
print(N-ans-1)
if __name__ == "__main__":
main()
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s513643000 | Runtime Error | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | n=int(input())
a=[int(input()) for i in range(n)]
al= {}
ds=[]
ans=0
for ai in a:
ds=
if ai - 1 in al.keys():
al[ai]=al[ai-1]+1
ans=max(ans,al[ai-1]+1)
del al[ai-1]
else:
al[ai]=0
if ai + 1 in al.keys():
del al[ai]
print(n-ans-1) | Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s739352141 | Runtime Error | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | N = int(input())
a = [input() for _ in range(N)]
c = 0
maxc = 0
for i in range(1:N):
if a.index(i) < a.index(i+1):
c += 1
else:
if c > maxc:
macxc = c
c = 0
print(N-maxc) | Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s621294164 | Runtime Error | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | n=int(input())
p=[]
for i in range (n):
p.append(int(input()))
pos=0
num=0
n_th = 0
for i in range(n)
if i+1 in p[pos:]:
num += 1
pos = p[pos:].index(i+1)+pos
else:
if num>n_th:
n_th = num
if i+1 in p:
num = 1
pos = p.index(i+1)
if num >n_th:
print (n-num)
else:
print(n-n_th) | Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s083171337 | Runtime Error | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | import sys
N = int(input())
P = [input() for i in range(N)]
P = list(map(int, P))
ans = 0
if N == 1:
print(1)
sys.exti()
err = [1]
P_lft = []
P_rgh = []
while len(err) > 0:
# print(P)
del err
err = []
del P_lft
P_lft = P[: N // 2]
for i in P_lft:
if i > N // 2:
err.append(i)
P.remove(i)
ans = ans + len(err)
err.sort()
P = P + err
P_lft = P[: N // 2]
tmp = [int(i + 1) for i in range(N // 2)]
while tmp != P_lft:
ans = ans + 1
if P_lft[0] != 1:
P_lft.remove(P_lft[0] - 1)
P_lft.insert(0, P_lft[0] - 1)
else:
P_lft.remove(N // 2)
P_lft.insert(0, N // 2)
del P_lft
P_lft = P[N // 2 :]
tmp = []
tmp = [int(i + N // 2 + 1) for i in range(N // 2)]
while tmp != P_lft:
ans = ans + 1
if P_lft[-1] != N:
P_lft.remove(P_lft[-1] + 1)
P_lft.append(P_lft[-1] + 1)
else:
P_lft.remove(N // 2 + 1)
P_lft.append(P_lft[-1] + 1)
print(ans)
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s830727734 | Wrong Answer | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | # coding: utf-8
import re
import math
from copy import deepcopy
import fractions
import random
from heapq import heappop, heappush
import time
import sys
readline = sys.stdin.readline
# import numpy as np
mod = int(10**9 + 7)
inf = int(10**20)
class union_find:
def __init__(self, n):
self.n = n
self.P = [a for a in range(N)]
self.rank = [0] * n
def find(self, x):
if x != self.P[x]:
self.P[x] = self.find(self.P[x])
return self.P[x]
def same(self, x, y):
return self.find(x) == self.find(y)
def link(self, x, y):
if self.rank[x] < self.rank[y]:
self.P[x] = y
elif self.rank[y] < self.rank[x]:
self.P[y] = x
else:
self.P[x] = y
self.rank[y] += 1
def unite(self, x, y):
self.link(self.find(x), self.find(y))
def size(self):
S = set()
for a in range(self.n):
S.add(self.find(a))
return len(S)
def bin_(num, size):
A = [0] * size
for a in range(size):
if (num >> (size - a - 1)) & 1 == 1:
A[a] = 1
else:
A[a] = 0
return A
def fac_list(n, mod_=0):
A = [1] * (n + 1)
for a in range(2, len(A)):
A[a] = A[a - 1] * a
if mod > 0:
A[a] %= mod_
return A
def comb(n, r, mod, fac):
if n - r < 0:
return 0
return (fac[n] * pow(fac[n - r], mod - 2, mod) * pow(fac[r], mod - 2, mod)) % mod
def next_comb(num, size):
x = num & (-num)
y = num + x
z = num & (~y)
z //= x
z = z >> 1
num = y | z
if num >= (1 << size):
return False
else:
return num
def get_primes(n, type="number"):
A = [True] * (n + 1)
A[0] = False
A[1] = False
for a in range(2, n + 1):
if A[a]:
for b in range(a * 2, n + 1, a):
A[b] = False
if type == "bool":
return A
B = []
for a in range(n + 1):
if A[a]:
B.append(a)
return B
def is_prime(num):
if num <= 2:
return False
i = 2
while i * i <= num:
if num % i == 0:
return False
i += 1
return True
fac = fac_list(10**5 + 100, mod)
def C(n, r):
if n - r < 0:
return 0
return (fac[n] * pow(fac[n - r], mod - 2, mod) * pow(fac[r], mod - 2, mod)) % mod
# main
N = int(input())
Q = [0] * N
for a in range(N):
Q[int(input()) - 1] = a
ans = 1
K = 1
for a in range(1, N - 1):
if Q[a - 1] < Q[a]:
K += 1
else:
K = 1
ans = max(K, ans)
ans = N - ans
print(ans)
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s842974991 | Wrong Answer | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | def main():
N = int(input())
P = [0 for _ in range(N)]
A = [i + 1 for i in range(N)]
for i in range(N):
P[i] = int(input())
count = [1, 1]
for i in range(N - 1):
if P[i] + 1 == P[i + 1]:
count[0] += 1
count[1] = max(count[0], count[1])
else:
count[0] = 1
K = N - count[1]
if N % 2 == 0:
if N == 2:
if P[0] > P[1]:
return 1
else:
return 0
a = P.index(N // 2)
b = P.index(N // 2 + 1)
if a < b:
if (P[0] == N // 2 + 2) and (P[1] == N // 2 - 1):
return min(N - 3, K)
elif (P[-1] == N // 2 - 1) and (P[-2] == N // 2 + 2):
return min(N - 3, K)
elif (P[0] == N // 2 - 1) and (P[-1] == N // 2 + 2):
return min(K, N - 4)
elif (P[0] == N // 2 - 1) or (P[-1] == N // 2 + 2):
return min(K, N - 3)
else:
return min(K, N - 2)
else:
if (P[0] == N // 2 + 2) and (P[1] == N // 2 - 1):
return min(K, N - 2)
elif (P[-1] == N // 2 - 1) and (P[-2] == N // 2 + 2):
return min(K, N - 2)
elif (P[0] == N // 2 - 1) and (P[-1] == N // 2 + 2):
return min(K, N - 2)
elif (P[0] == N // 2 - 1) or (P[-1] == N // 2 + 2):
return min(K, N - 2)
else:
return min(K, N - 1)
else:
if N == 1:
return 0
elif (P[0] == N // 2 + 2) and (P[1] == N // 2):
return min(K, N - 2)
elif (P[-1] == N // 2) and (P[-2] == N // 2 + 2):
return min(K, N - 2)
elif (P[0] == N // 2) and (P[-1] == N // 2 + 2):
return min(K, N - 3)
elif (P[0] == N // 2) or (P[-1] == N // 2 + 2):
return min(K, N - 2)
else:
return min(K, N - 1)
if __name__ == "__main__":
print(main())
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the minimum number of operations required.
* * * | s535680364 | Accepted | p03346 | Input is given from Standard Input in the following format:
N
P_1
:
P_N | ip = lambda: int(input())
n = ip()
p = [ip() for _ in range(n)]
d = [0] * (n + 1)
for q in p:
d[q] += d[q - 1] + 1
print(n - max(d))
| Statement
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the
integers from 1 through N. You would like to sort this sequence in ascending
order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is
actually possible to sort the sequence using this operation. | [{"input": "4\n 1\n 3\n 2\n 4", "output": "2\n \n\nFor example, the sequence can be sorted in ascending order as follows:\n\n * Move 2 to the beginning. The sequence is now (2,1,3,4).\n * Move 1 to the beginning. The sequence is now (1,2,3,4).\n\n* * *"}, {"input": "6\n 3\n 2\n 5\n 1\n 4\n 6", "output": "4\n \n\n* * *"}, {"input": "8\n 6\n 3\n 1\n 2\n 7\n 4\n 8\n 5", "output": "5"}] |
Print the answer \bmod (10^9+7).
* * * | s385973043 | Wrong Answer | p02804 | Input is given from Standard Input in the following format:
N K
A_1 ... A_N | n, k = map(int, input().split())
a = map(int, input().split())
if n == k:
raise RuntimeError()
| Statement
For a finite set of integers X, let f(X)=\max X - \min X.
Given are N integers A_1,...,A_N.
We will choose K of them and let S be the set of the integers chosen. If we
distinguish elements with different indices even when their values are the
same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over
all those ways.
Since the answer can be enormous, print it \bmod (10^9+7). | [{"input": "4 2\n 1 1 3 4", "output": "11\n \n\nThere are six ways to choose S:\n\\\\{1,1\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\}, \\\\{3,4\\\\} (we distinguish\nthe two 1s). The value of f(S) for these choices are 0,2,3,2,3,1,\nrespectively, for the total of 11.\n\n* * *"}, {"input": "6 3\n 10 10 10 -10 -10 -10", "output": "360\n \n\nThere are 20 ways to choose S. In 18 of them, f(S)=20, and in 2 of them,\nf(S)=0.\n\n* * *"}, {"input": "3 1\n 1 1 1", "output": "0\n \n\n* * *"}, {"input": "10 6\n 1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0", "output": "999998537\n \n\nPrint the sum \\bmod (10^9+7)."}] |
Print the answer \bmod (10^9+7).
* * * | s135546774 | Runtime Error | p02804 | Input is given from Standard Input in the following format:
N K
A_1 ... A_N | import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer / denom
def main():
N, K = list(map(int, input().split()))
As = list(map(int, input().split()))
As.sort()
mod = 10**9 + 7
s = 0
for i in range(N):
for j in range(i + K - 1, N):
# print(i, j, (As[j] - As[i]) , ncr(j-i-1, K-2), ncr(2, 3))
s += (As[j] - As[i]) * ncr(j - i - 1, K - 2)
# combs = combinations(range(N), K)
# for tup in combs:
# mn_idx = tup[0]
# mx_idx = tup[-1]
# s += As[mx_idx] - As[mn_idx]
print(int(s % mod))
if __name__ == "__main__":
main()
| Statement
For a finite set of integers X, let f(X)=\max X - \min X.
Given are N integers A_1,...,A_N.
We will choose K of them and let S be the set of the integers chosen. If we
distinguish elements with different indices even when their values are the
same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over
all those ways.
Since the answer can be enormous, print it \bmod (10^9+7). | [{"input": "4 2\n 1 1 3 4", "output": "11\n \n\nThere are six ways to choose S:\n\\\\{1,1\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\}, \\\\{3,4\\\\} (we distinguish\nthe two 1s). The value of f(S) for these choices are 0,2,3,2,3,1,\nrespectively, for the total of 11.\n\n* * *"}, {"input": "6 3\n 10 10 10 -10 -10 -10", "output": "360\n \n\nThere are 20 ways to choose S. In 18 of them, f(S)=20, and in 2 of them,\nf(S)=0.\n\n* * *"}, {"input": "3 1\n 1 1 1", "output": "0\n \n\n* * *"}, {"input": "10 6\n 1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0", "output": "999998537\n \n\nPrint the sum \\bmod (10^9+7)."}] |
Print the answer \bmod (10^9+7).
* * * | s770454605 | Accepted | p02804 | Input is given from Standard Input in the following format:
N K
A_1 ... A_N | import unittest
class TestE(unittest.TestCase):
def test_1(self):
self.assertEqual(think(2, [1, 1, 3, 4]), 11)
def test_2(self):
self.assertEqual(think(3, [10, 10, 10, -10, -10, -10]), 360)
def test_3(self):
self.assertEqual(think(1, [1, 1, 1]), 0)
def test_4(self):
self.assertEqual(
think(
6,
[
1000000000,
1000000000,
1000000000,
1000000000,
1000000000,
0,
0,
0,
0,
0,
],
),
999998537,
)
def solve():
k, a = read()
result = think(k, a)
write(result)
def read():
n, k = read_int(2)
return k, read_int(n)
def read_int(n):
return read_type(int, n, sep=" ")
def read_float(n):
return read_type(float, n, sep=" ")
def read_type(t, n, sep):
return list(map(lambda x: t(x), read_line().split(sep)))[:n]
def read_line(n=0):
if n == 0:
return input().rstrip()
else:
return input().rstrip()[:n]
def think(k, a):
mode = 10**9 + 7
n = len(a)
fact_table, inverse_fact_table = prepare_fact_table(n, mode)
a.sort()
sum_of_max = 0
sum_of_min = 0
for i, x in enumerate(a):
if i >= k - 1:
sum_of_max += x * combination(
i, k - 1, fact_table, inverse_fact_table, mode
)
sum_of_max %= mode
if n - i >= k:
sum_of_min += x * combination(
n - i - 1, k - 1, fact_table, inverse_fact_table, mode
)
sum_of_min %= mode
return (sum_of_max - sum_of_min) % mode
def write(result):
print(result)
def prepare_fact_table(n, mode):
fact_table = [1 for i in range(n + 1)]
inverse_fact_table = [1 for i in range(n + 1)]
for i in range(2, len(fact_table)):
fact_table[i] = fact_table[i - 1] * i % mode
inverse_fact_table[i] = divmod(fact_table[i], mode)
return fact_table, inverse_fact_table
def divmod(x, mode):
return pow(x, mode - 2, mode)
def combination(n, k, fact_table, inverse_fact_table, mode):
return fact_table[n] * inverse_fact_table[k] * inverse_fact_table[n - k] % mode
if __name__ == "__main__":
# unittest.main()
solve()
| Statement
For a finite set of integers X, let f(X)=\max X - \min X.
Given are N integers A_1,...,A_N.
We will choose K of them and let S be the set of the integers chosen. If we
distinguish elements with different indices even when their values are the
same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over
all those ways.
Since the answer can be enormous, print it \bmod (10^9+7). | [{"input": "4 2\n 1 1 3 4", "output": "11\n \n\nThere are six ways to choose S:\n\\\\{1,1\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\}, \\\\{3,4\\\\} (we distinguish\nthe two 1s). The value of f(S) for these choices are 0,2,3,2,3,1,\nrespectively, for the total of 11.\n\n* * *"}, {"input": "6 3\n 10 10 10 -10 -10 -10", "output": "360\n \n\nThere are 20 ways to choose S. In 18 of them, f(S)=20, and in 2 of them,\nf(S)=0.\n\n* * *"}, {"input": "3 1\n 1 1 1", "output": "0\n \n\n* * *"}, {"input": "10 6\n 1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0", "output": "999998537\n \n\nPrint the sum \\bmod (10^9+7)."}] |
Print the answer \bmod (10^9+7).
* * * | s284331818 | Accepted | p02804 | Input is given from Standard Input in the following format:
N K
A_1 ... A_N | N, K = map(int, input().split())
A = list(map(int, input().split()))
mod = int(1e9 + 7)
p = mod - 2
ax = []
while p != 0:
ax = [p % 2] + ax[:]
p //= 2
A.sort()
S = 0
fact = 1
invK = 1
for i in range(K - 1):
fact *= i + 1
fact %= mod
for j in range(len(ax)):
if ax[j] == 1:
invK *= fact
invK %= mod
if j != len(ax) - 1:
invK *= invK
invK %= mod
invf = 1
for k in range(K, N + 1):
S += ((A[k - 1] - A[N - k]) * (fact * invf)) % mod
S %= mod
fact *= k
fact %= mod
lead = 1
for j in range(len(ax)):
if ax[j] == 1:
lead *= k + 1 - K
lead %= mod
if j != len(ax) - 1:
lead *= lead
lead %= mod
invf *= lead
invf %= mod
print((S * invK) % mod)
| Statement
For a finite set of integers X, let f(X)=\max X - \min X.
Given are N integers A_1,...,A_N.
We will choose K of them and let S be the set of the integers chosen. If we
distinguish elements with different indices even when their values are the
same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over
all those ways.
Since the answer can be enormous, print it \bmod (10^9+7). | [{"input": "4 2\n 1 1 3 4", "output": "11\n \n\nThere are six ways to choose S:\n\\\\{1,1\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\}, \\\\{3,4\\\\} (we distinguish\nthe two 1s). The value of f(S) for these choices are 0,2,3,2,3,1,\nrespectively, for the total of 11.\n\n* * *"}, {"input": "6 3\n 10 10 10 -10 -10 -10", "output": "360\n \n\nThere are 20 ways to choose S. In 18 of them, f(S)=20, and in 2 of them,\nf(S)=0.\n\n* * *"}, {"input": "3 1\n 1 1 1", "output": "0\n \n\n* * *"}, {"input": "10 6\n 1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0", "output": "999998537\n \n\nPrint the sum \\bmod (10^9+7)."}] |
Print the answer \bmod (10^9+7).
* * * | s050278648 | Runtime Error | p02804 | Input is given from Standard Input in the following format:
N K
A_1 ... A_N | nk = input().split()
n = int(nk[0])
k = int(nk[1])
a = [int(s) for s in input().split()]
a.sort()
fx = 0
for j in range(n):
if j >= k - 1:
jCk_1 = 1
for i in range(k - 1):
jCk_1 = jCk_1 * (j - i) / (i + 1)
fx = fx + jCk_1 * a[j]
if n - j - 1 >= k - 1:
jCk_1 = 1
for i in range(k - 1):
jCk_1 = jCk_1 * (n - j - 1 - i) / (i + 1)
fx = fx - jCk_1 * a[j]
print(str(int(fx % (10**9 + 7))))
| Statement
For a finite set of integers X, let f(X)=\max X - \min X.
Given are N integers A_1,...,A_N.
We will choose K of them and let S be the set of the integers chosen. If we
distinguish elements with different indices even when their values are the
same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over
all those ways.
Since the answer can be enormous, print it \bmod (10^9+7). | [{"input": "4 2\n 1 1 3 4", "output": "11\n \n\nThere are six ways to choose S:\n\\\\{1,1\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\},\\\\{1,3\\\\},\\\\{1,4\\\\}, \\\\{3,4\\\\} (we distinguish\nthe two 1s). The value of f(S) for these choices are 0,2,3,2,3,1,\nrespectively, for the total of 11.\n\n* * *"}, {"input": "6 3\n 10 10 10 -10 -10 -10", "output": "360\n \n\nThere are 20 ways to choose S. In 18 of them, f(S)=20, and in 2 of them,\nf(S)=0.\n\n* * *"}, {"input": "3 1\n 1 1 1", "output": "0\n \n\n* * *"}, {"input": "10 6\n 1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0", "output": "999998537\n \n\nPrint the sum \\bmod (10^9+7)."}] |
Print the maximum possible score of a'.
* * * | s948381767 | Accepted | p03716 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{3N} | from heapq import heapify, heappushpop
N, *A = map(int, open(0).read().split())
L, C, R = A[:N], A[N : 2 * N], A[2 * N :]
heapify(L)
red = [sum(L)]
for c in C:
red.append(red[-1] + c - heappushpop(L, c))
R = [-r for r in R]
heapify(R)
blue = [sum(R)]
for c in reversed(C):
blue.append(blue[-1] - c - heappushpop(R, -c))
print(max(r + b for r, b in zip(red, reversed(blue))))
| Statement
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke
is constructing a new sequence of length 2N, a', by removing exactly N
elements from a without changing the order of the remaining elements. Here,
the score of a' is defined as follows: (the sum of the elements in the first
half of a') - (the sum of the elements in the second half of a').
Find the maximum possible score of a'. | [{"input": "2\n 3 1 4 1 5 9", "output": "1\n \n\nWhen a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3\n+ 4) - (1 + 5) = 1.\n\n* * *"}, {"input": "1\n 1 2 3", "output": "-1\n \n\nFor example, when a_1 are removed, a' will be (2, 3), which has a score of 2 -\n3 = -1.\n\n* * *"}, {"input": "3\n 8 2 2 7 4 6 5 3 8", "output": "5\n \n\nFor example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3),\nwhich has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5."}] |
Print the maximum possible score of a'.
* * * | s627755574 | Accepted | p03716 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{3N} | from heapq import heappush, heappop, heapify
N = int(input())
a = list(map(int, input().split()))
ans_list = []
def red_sum():
red = sum(a[:N])
pqr = a[:N]
heapify(pqr)
ans_list.append(red)
for i in range(N, 2 * N):
heappush(pqr, a[i])
red += a[i] - heappop(pqr)
ans_list.append(red)
def blue_sum():
blue = sum(a[2 * N :])
pqb = [-a[i] for i in range(2 * N, 3 * N)]
heapify(pqb)
ans_list[N] -= blue
for i in range(2 * N - 1, N - 1, -1):
heappush(pqb, -a[i])
tmp = heappop(pqb)
blue += a[i] + tmp
ans_list[i - N] -= blue
red_sum()
blue_sum()
print(max(ans_list))
| Statement
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke
is constructing a new sequence of length 2N, a', by removing exactly N
elements from a without changing the order of the remaining elements. Here,
the score of a' is defined as follows: (the sum of the elements in the first
half of a') - (the sum of the elements in the second half of a').
Find the maximum possible score of a'. | [{"input": "2\n 3 1 4 1 5 9", "output": "1\n \n\nWhen a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3\n+ 4) - (1 + 5) = 1.\n\n* * *"}, {"input": "1\n 1 2 3", "output": "-1\n \n\nFor example, when a_1 are removed, a' will be (2, 3), which has a score of 2 -\n3 = -1.\n\n* * *"}, {"input": "3\n 8 2 2 7 4 6 5 3 8", "output": "5\n \n\nFor example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3),\nwhich has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5."}] |
Print the maximum possible score of a'.
* * * | s464991576 | Runtime Error | p03716 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{3N} | import bisect
import heapq
import sys
input = sys.stdin.readline
N = int(input())
a = list(map(int,input().split()))
a_left = sorted(a[:N])
a_right = sorted(a[N:])
sum_left = sum(a_left)
sum_right = sum(a_right[:N])
res = sum_left - sum_right
heapq.heapify(a_left)
len_left = N
for elem in a[N:2*N]:
le = bisect.bisect_left(a_right, elem)
a_right[le:] = a_right[le+1:]
if le < N:
sum_right -= elem
sum_right += a_right[N-1]
now = heapq.heappop(a_left)
if now < elem:
heapq.heappush(a_left, elem)
sum_left += (elem-now)
else:
heapq.heappush(a_left, now)
res = max(res, sum_left-sum_right)
print(res)
"""
| Statement
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke
is constructing a new sequence of length 2N, a', by removing exactly N
elements from a without changing the order of the remaining elements. Here,
the score of a' is defined as follows: (the sum of the elements in the first
half of a') - (the sum of the elements in the second half of a').
Find the maximum possible score of a'. | [{"input": "2\n 3 1 4 1 5 9", "output": "1\n \n\nWhen a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3\n+ 4) - (1 + 5) = 1.\n\n* * *"}, {"input": "1\n 1 2 3", "output": "-1\n \n\nFor example, when a_1 are removed, a' will be (2, 3), which has a score of 2 -\n3 = -1.\n\n* * *"}, {"input": "3\n 8 2 2 7 4 6 5 3 8", "output": "5\n \n\nFor example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3),\nwhich has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5."}] |
Print the maximum possible score of a'.
* * * | s640190184 | Accepted | p03716 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{3N} | # from collections import deque,defaultdict
printn = lambda x: print(x, end="")
inn = lambda: int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
ins = lambda: input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
def ddprint(x):
if DBG:
print(x)
# # # # class Segtree # # # #
# 0
# 1 2
# 3 4 5 6
# :
# leaf i - n-1+i
# parent - (i-1)//2
# children - 2*i+1, 2*i+2
class Segtree:
# modify UNIT and oper depending on the reduce operation
# UNIT = 0 # sum/or:0 and:fff..f min:BIG max:-BIG gcd:0 lcm:1 ..
# @classmethod
# def oper(c,x,y):
# return x|y # sum:+ or/and/min/max/gcd/lcm:(same)
# call like this: sgt = Segtree(n, 0, lambda x,y: max(x,y))
def __init__(s, l, unit, oper):
s.unit = unit
s.oper = oper
s.n = 1
while s.n < l:
s.n *= 2
s.ary = [s.unit for i in range(2 * s.n - 1)]
def get(s, i):
return s.ary[i + s.n - 1]
def set(s, i, v):
k = i + s.n - 1
s.ary[k] = v
while k > 0:
k = (k - 1) // 2
s.ary[k] = s.oper(s.ary[2 * k + 1], s.ary[2 * k + 2])
def setary(s, a):
for i, v in enumerate(a):
s.ary[i + s.n - 1] = v
for k in range(s.n - 2, -1, -1):
s.ary[k] = s.oper(s.ary[2 * k + 1], s.ary[2 * k + 2])
def query(s, x, y):
l = x + s.n - 1
r = y + s.n - 1
res = s.unit
while l < r:
if not l % 2:
res = s.oper(res, s.ary[l])
l += 1
if not r % 2:
r -= 1
res = s.oper(res, s.ary[r])
l >>= 1
r >>= 1
return res
# # # # class Segtree end # # # #
import heapq
n = inn()
a = inl()
lmax = a[:n]
lsum = sum(lmax)
heapq.heapify(lmax)
r = a[n:]
r = [(r[i], i) for i in range(2 * n)]
r.sort()
rsum = sum([x[0] for x in r[:n]])
rmax = [BIG] * (2 * n)
h = {}
for v, i in r[n:]:
if v not in h:
h[v] = []
h[v].append(i)
rmax[i] = v
sgt = Segtree(2 * n, BIG, lambda x, y: min(x, y))
sgt.setary(rmax)
if False:
ddprint(a)
# ddprint(f"{n=} {lsum=} {rsum=}")
ddprint(lmax)
ddprint(rmax)
ddprint(h)
mx = lsum - rsum
for i in range(n):
v = a[n + i]
v2 = heapq.heappushpop(lmax, v)
lsum += v - v2
if sgt.get(i) == BIG:
vnew = sgt.query(i + 1, 2 * n)
rsum += vnew - v
suf = h[vnew].pop()
sgt.set(suf, BIG)
# ddprint(f"{i=} {v=} {v2=} {vnew=} {suf=} {lsum=} {rsum=}")
mx = max(mx, lsum - rsum)
print(mx)
| Statement
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke
is constructing a new sequence of length 2N, a', by removing exactly N
elements from a without changing the order of the remaining elements. Here,
the score of a' is defined as follows: (the sum of the elements in the first
half of a') - (the sum of the elements in the second half of a').
Find the maximum possible score of a'. | [{"input": "2\n 3 1 4 1 5 9", "output": "1\n \n\nWhen a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3\n+ 4) - (1 + 5) = 1.\n\n* * *"}, {"input": "1\n 1 2 3", "output": "-1\n \n\nFor example, when a_1 are removed, a' will be (2, 3), which has a score of 2 -\n3 = -1.\n\n* * *"}, {"input": "3\n 8 2 2 7 4 6 5 3 8", "output": "5\n \n\nFor example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3),\nwhich has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5."}] |
Print the maximum possible score of a'.
* * * | s397588725 | Accepted | p03716 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{3N} | from heapq import *
(N,) = map(int, input().split())
A = list(map(int, input().split()))
s = sum(A[:N])
rs = [s] + [0] * N
l = []
for i in range(N):
heappush(l, A[i])
for i in range(N, 2 * N):
s += A[i]
heappush(l, A[i])
x = heappop(l)
s -= x
rs[i - N + 1] = s
l2 = []
s2 = 0
for i in range(2 * N, 3 * N):
heappush(l2, -A[i])
s2 += A[i]
rs2 = [0] * N + [s2]
for i in range(2 * N - 1, N - 1, -1):
s2 += A[i]
heappush(l2, -A[i])
x = -heappop(l2)
# print(A[i])
# print(x)
s2 -= x
rs2[i - N] = s2
# print(rs2)
r = -(10**18)
for i in range(N + 1):
c = rs[i] - rs2[i]
r = max(c, r)
print(r)
| Statement
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke
is constructing a new sequence of length 2N, a', by removing exactly N
elements from a without changing the order of the remaining elements. Here,
the score of a' is defined as follows: (the sum of the elements in the first
half of a') - (the sum of the elements in the second half of a').
Find the maximum possible score of a'. | [{"input": "2\n 3 1 4 1 5 9", "output": "1\n \n\nWhen a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3\n+ 4) - (1 + 5) = 1.\n\n* * *"}, {"input": "1\n 1 2 3", "output": "-1\n \n\nFor example, when a_1 are removed, a' will be (2, 3), which has a score of 2 -\n3 = -1.\n\n* * *"}, {"input": "3\n 8 2 2 7 4 6 5 3 8", "output": "5\n \n\nFor example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3),\nwhich has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5."}] |
Print the maximum possible score of a'.
* * * | s523705522 | Accepted | p03716 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{3N} | n = int(input())
a = list(map(int, input().split()))
a_l = a[:n]
a_c = a[n : 2 * n]
a_r = [-1 * i for i in a[2 * n :]]
left = [0] * (n + 1)
right = [0] * (n + 1)
# ヒープキュー(最小値・最大値の取得)
from heapq import heapify, heappop, heappush
left[0] = sum(a_l)
heapify(a_l)
for i, val in enumerate(a_c):
heappush(a_l, val)
left[i + 1] = left[i] + val - heappop(a_l)
right[-1] = -1 * sum(a_r)
heapify(a_r)
for i, val in enumerate(a_c[::-1], 1):
heappush(a_r, val * -1)
right[n - i] = right[n + 1 - i] + val + heappop(a_r)
lr = [i - j for i, j in zip(left, right)]
print(max(lr))
| Statement
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke
is constructing a new sequence of length 2N, a', by removing exactly N
elements from a without changing the order of the remaining elements. Here,
the score of a' is defined as follows: (the sum of the elements in the first
half of a') - (the sum of the elements in the second half of a').
Find the maximum possible score of a'. | [{"input": "2\n 3 1 4 1 5 9", "output": "1\n \n\nWhen a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3\n+ 4) - (1 + 5) = 1.\n\n* * *"}, {"input": "1\n 1 2 3", "output": "-1\n \n\nFor example, when a_1 are removed, a' will be (2, 3), which has a score of 2 -\n3 = -1.\n\n* * *"}, {"input": "3\n 8 2 2 7 4 6 5 3 8", "output": "5\n \n\nFor example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3),\nwhich has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5."}] |
Print the number of actions Takahashi will end up performing.
* * * | s186575856 | Accepted | p03203 | Input is given from Standard Input in the following format:
H W N
X_1 Y_1
:
X_N Y_N | h, w, n = map(int, input().split())
xy = sorted([list(map(int, input().split())) for _ in range(n)])
dx = 0
dy = 0
for x, y in xy:
x -= dx
y -= dy
if x == y:
dx += x - 1
dy += y - 2
elif y < x:
print(dx + x - 1)
break
else:
print(h)
| Statement
Takahashi and Aoki will play a game using a grid with H rows and W columns of
square cells. There are N obstacles on this grid; the i-th obstacle is at
(X_i,Y_i). Here, we represent the cell at the i-th row and j-th column (1 \leq
i \leq H, 1 \leq j \leq W) by (i,j). There is no obstacle at (1,1), and there
is a piece placed there at (1,1).
Starting from Takahashi, he and Aoki alternately perform one of the following
actions:
* Move the piece to an adjacent cell. Here, let the position of the piece be (x,y). Then Takahashi can only move the piece to (x+1,y), and Aoki can only move the piece to (x,y+1). If the destination cell does not exist or it is occupied by an obstacle, this action cannot be taken.
* Do not move the piece, and end his turn without affecting the grid.
The game ends when the piece does not move twice in a row.
Takahashi would like to perform as many actions (including not moving the
piece) as possible before the game ends, while Aoki would like to perform as
few actions as possible before the game ends. How many actions will Takahashi
end up performing? | [{"input": "3 3 1\n 3 2", "output": "2\n \n\nFor example, the game proceeds as follows:\n\n * Takahashi moves the piece to (2,1).\n * Aoki does not move the piece.\n * Takahashi moves the piece to (3,1).\n * Aoki does not move the piece.\n * Takahashi does not move the piece.\n\nTakahashi performs three actions in this case, but if both players play\noptimally, Takahashi will perform only two actions before the game ends.\n\n* * *"}, {"input": "10 10 14\n 4 3\n 2 2\n 7 3\n 9 10\n 7 7\n 8 1\n 10 10\n 5 4\n 3 4\n 2 8\n 6 4\n 4 4\n 5 8\n 9 2", "output": "6\n \n\n* * *"}, {"input": "100000 100000 0", "output": "100000"}] |
Print the number of actions Takahashi will end up performing.
* * * | s594119547 | Wrong Answer | p03203 | Input is given from Standard Input in the following format:
H W N
X_1 Y_1
:
X_N Y_N | H, W, N = map(int, input().split())
m = W
for _ in range(N):
x, y = map(int, input().split())
if x > y:
print(x, y)
m = min(m, x - 1)
print(m)
| Statement
Takahashi and Aoki will play a game using a grid with H rows and W columns of
square cells. There are N obstacles on this grid; the i-th obstacle is at
(X_i,Y_i). Here, we represent the cell at the i-th row and j-th column (1 \leq
i \leq H, 1 \leq j \leq W) by (i,j). There is no obstacle at (1,1), and there
is a piece placed there at (1,1).
Starting from Takahashi, he and Aoki alternately perform one of the following
actions:
* Move the piece to an adjacent cell. Here, let the position of the piece be (x,y). Then Takahashi can only move the piece to (x+1,y), and Aoki can only move the piece to (x,y+1). If the destination cell does not exist or it is occupied by an obstacle, this action cannot be taken.
* Do not move the piece, and end his turn without affecting the grid.
The game ends when the piece does not move twice in a row.
Takahashi would like to perform as many actions (including not moving the
piece) as possible before the game ends, while Aoki would like to perform as
few actions as possible before the game ends. How many actions will Takahashi
end up performing? | [{"input": "3 3 1\n 3 2", "output": "2\n \n\nFor example, the game proceeds as follows:\n\n * Takahashi moves the piece to (2,1).\n * Aoki does not move the piece.\n * Takahashi moves the piece to (3,1).\n * Aoki does not move the piece.\n * Takahashi does not move the piece.\n\nTakahashi performs three actions in this case, but if both players play\noptimally, Takahashi will perform only two actions before the game ends.\n\n* * *"}, {"input": "10 10 14\n 4 3\n 2 2\n 7 3\n 9 10\n 7 7\n 8 1\n 10 10\n 5 4\n 3 4\n 2 8\n 6 4\n 4 4\n 5 8\n 9 2", "output": "6\n \n\n* * *"}, {"input": "100000 100000 0", "output": "100000"}] |
Print the number of actions Takahashi will end up performing.
* * * | s640309718 | Wrong Answer | p03203 | Input is given from Standard Input in the following format:
H W N
X_1 Y_1
:
X_N Y_N | def quick_sort(arr):
left = []
right = []
middle = []
if len(arr) <= 1:
return arr
ref = arr[0][0]
ref_count = 0
for ele in arr:
if ele[0] < ref:
left.append(ele)
elif ele[0] > ref:
right.append(ele)
else:
middle.append(ele)
left = quick_sort(left)
right = quick_sort(right)
return left + middle + right
def main():
line_1 = input().split(" ")
x = int(line_1[0])
y = int(line_1[1])
jama = int(line_1[2])
jalist = []
for jm in range(jama):
line_n = input().split(" ")
jama_n = [int(line_n[0]), int(line_n[1])]
jalist.append(jama_n)
xlist = quick_sort(jalist)
# print(xlist)
now_x = 1
now_y = 1
now_list = 0
list_2 = []
while now_x <= x:
checkpoint = 0
for xl in xlist:
now_x2 = now_x + 1
if xl[0] == now_x2:
if xl[1] == now_y + 1:
checkpoint = 1
elif xl[1] < now_y + 1:
return now_x
elif xl[0] > now_x2:
break
if checkpoint == 1:
now_x += 1
else:
now_x += 1
now_y += 1
# print(now_x, now_y)
def honban():
answer = main()
print(answer)
honban()
| Statement
Takahashi and Aoki will play a game using a grid with H rows and W columns of
square cells. There are N obstacles on this grid; the i-th obstacle is at
(X_i,Y_i). Here, we represent the cell at the i-th row and j-th column (1 \leq
i \leq H, 1 \leq j \leq W) by (i,j). There is no obstacle at (1,1), and there
is a piece placed there at (1,1).
Starting from Takahashi, he and Aoki alternately perform one of the following
actions:
* Move the piece to an adjacent cell. Here, let the position of the piece be (x,y). Then Takahashi can only move the piece to (x+1,y), and Aoki can only move the piece to (x,y+1). If the destination cell does not exist or it is occupied by an obstacle, this action cannot be taken.
* Do not move the piece, and end his turn without affecting the grid.
The game ends when the piece does not move twice in a row.
Takahashi would like to perform as many actions (including not moving the
piece) as possible before the game ends, while Aoki would like to perform as
few actions as possible before the game ends. How many actions will Takahashi
end up performing? | [{"input": "3 3 1\n 3 2", "output": "2\n \n\nFor example, the game proceeds as follows:\n\n * Takahashi moves the piece to (2,1).\n * Aoki does not move the piece.\n * Takahashi moves the piece to (3,1).\n * Aoki does not move the piece.\n * Takahashi does not move the piece.\n\nTakahashi performs three actions in this case, but if both players play\noptimally, Takahashi will perform only two actions before the game ends.\n\n* * *"}, {"input": "10 10 14\n 4 3\n 2 2\n 7 3\n 9 10\n 7 7\n 8 1\n 10 10\n 5 4\n 3 4\n 2 8\n 6 4\n 4 4\n 5 8\n 9 2", "output": "6\n \n\n* * *"}, {"input": "100000 100000 0", "output": "100000"}] |
Print the number of actions Takahashi will end up performing.
* * * | s700802174 | Runtime Error | p03203 | Input is given from Standard Input in the following format:
H W N
X_1 Y_1
:
X_N Y_N | H, W, N = map(int, input().split())
xlist, ylist = [], []
for i in range(N):
p = input().split()
xlist.append(int(p[0]))
ylist.append(int(p[1]))
map = []
for i in range(H):
map.append([])
for j in range(W):
map[i].append(0)
for i in range(N):
map[ylist[i] - 1][xlist[i] - 1] = 1
x_shougai = W + 1
for i in range(1, W):
for j in range(W):
if map[j][i] == 1:
xlevel = i
ylevel = j
p, q = i - 2, j - 1
while p >= 0 and q >= 0:
if map[q][p] == 1:
ylevel += 1
p -= 2
q -= 1
if x_shougai > xlevel > ylevel:
x_shougai = xlevel
if x_shougai == W + 1:
x_shougai -= 1
print(x_shougai)
| Statement
Takahashi and Aoki will play a game using a grid with H rows and W columns of
square cells. There are N obstacles on this grid; the i-th obstacle is at
(X_i,Y_i). Here, we represent the cell at the i-th row and j-th column (1 \leq
i \leq H, 1 \leq j \leq W) by (i,j). There is no obstacle at (1,1), and there
is a piece placed there at (1,1).
Starting from Takahashi, he and Aoki alternately perform one of the following
actions:
* Move the piece to an adjacent cell. Here, let the position of the piece be (x,y). Then Takahashi can only move the piece to (x+1,y), and Aoki can only move the piece to (x,y+1). If the destination cell does not exist or it is occupied by an obstacle, this action cannot be taken.
* Do not move the piece, and end his turn without affecting the grid.
The game ends when the piece does not move twice in a row.
Takahashi would like to perform as many actions (including not moving the
piece) as possible before the game ends, while Aoki would like to perform as
few actions as possible before the game ends. How many actions will Takahashi
end up performing? | [{"input": "3 3 1\n 3 2", "output": "2\n \n\nFor example, the game proceeds as follows:\n\n * Takahashi moves the piece to (2,1).\n * Aoki does not move the piece.\n * Takahashi moves the piece to (3,1).\n * Aoki does not move the piece.\n * Takahashi does not move the piece.\n\nTakahashi performs three actions in this case, but if both players play\noptimally, Takahashi will perform only two actions before the game ends.\n\n* * *"}, {"input": "10 10 14\n 4 3\n 2 2\n 7 3\n 9 10\n 7 7\n 8 1\n 10 10\n 5 4\n 3 4\n 2 8\n 6 4\n 4 4\n 5 8\n 9 2", "output": "6\n \n\n* * *"}, {"input": "100000 100000 0", "output": "100000"}] |
Print the number of actions Takahashi will end up performing.
* * * | s656939241 | Accepted | p03203 | Input is given from Standard Input in the following format:
H W N
X_1 Y_1
:
X_N Y_N | import bisect
import os
import sys
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10**9)
INF = float("inf")
IINF = 10**18
MOD = 10**9 + 7
# MOD = 998244353
H, W, N = list(map(int, sys.stdin.buffer.readline().split()))
XY = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
blocked = set()
blocks = [[] for _ in range(W + 1)]
for h, w in sorted(XY):
blocked.add((h, w))
blocks[w].append(h)
for w in range(W + 1):
blocks[w].append(H + 1)
# 高橋くんは毎回動く
# 青木くんが動く回数を決めたとき、先に動けるだけ動くとする
# 後から動いたほうがいい場合はもっと動く回数を少なくできるので
h, w = 1, 1
hist = []
while True:
hist.append((h, w))
if h + 1 <= H and (h + 1, w) not in blocked:
h += 1
else:
break
if w + 1 <= W and (h, w + 1) not in blocked:
w += 1
ans = INF
for h, w in hist:
hi = bisect.bisect_left(blocks[w], h + 1)
ans = min(ans, blocks[w][hi] - 1)
# print(h, w, blocks[w])
print(ans)
| Statement
Takahashi and Aoki will play a game using a grid with H rows and W columns of
square cells. There are N obstacles on this grid; the i-th obstacle is at
(X_i,Y_i). Here, we represent the cell at the i-th row and j-th column (1 \leq
i \leq H, 1 \leq j \leq W) by (i,j). There is no obstacle at (1,1), and there
is a piece placed there at (1,1).
Starting from Takahashi, he and Aoki alternately perform one of the following
actions:
* Move the piece to an adjacent cell. Here, let the position of the piece be (x,y). Then Takahashi can only move the piece to (x+1,y), and Aoki can only move the piece to (x,y+1). If the destination cell does not exist or it is occupied by an obstacle, this action cannot be taken.
* Do not move the piece, and end his turn without affecting the grid.
The game ends when the piece does not move twice in a row.
Takahashi would like to perform as many actions (including not moving the
piece) as possible before the game ends, while Aoki would like to perform as
few actions as possible before the game ends. How many actions will Takahashi
end up performing? | [{"input": "3 3 1\n 3 2", "output": "2\n \n\nFor example, the game proceeds as follows:\n\n * Takahashi moves the piece to (2,1).\n * Aoki does not move the piece.\n * Takahashi moves the piece to (3,1).\n * Aoki does not move the piece.\n * Takahashi does not move the piece.\n\nTakahashi performs three actions in this case, but if both players play\noptimally, Takahashi will perform only two actions before the game ends.\n\n* * *"}, {"input": "10 10 14\n 4 3\n 2 2\n 7 3\n 9 10\n 7 7\n 8 1\n 10 10\n 5 4\n 3 4\n 2 8\n 6 4\n 4 4\n 5 8\n 9 2", "output": "6\n \n\n* * *"}, {"input": "100000 100000 0", "output": "100000"}] |
Print the minimum number of operations required, or `-1` if the objective
cannot be achieved.
* * * | s565221632 | Accepted | p02941 | Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
B_1 B_2 ... B_N | N = int(input())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
if N > 10000:
A = A[5050:] + A[:5050]
B = B[5050:] + B[:5050]
ans = -1
D = [0] * N
L = [i - 1 for i in range(N)]
R = [i + 1 for i in range(N)]
def calc():
i = 0
c = 0
ans = 0
while c < N:
while i < N:
if B[i] == A[i]:
if D[i] == 0:
c += 1
D[i] = 1
if L[i] >= 0:
R[L[i]] = R[i]
if R[i] < N:
L[R[i]] = L[i]
if B[i] > A[i] and B[i] >= max(B[i - 1], B[(i + 1) % N]):
k = -(
-(B[i] - max(B[i - 1], B[(i + 1) % N], A[i]))
// (B[i - 1] + B[(i + 1) % N])
)
B[i] -= (B[i - 1] + B[(i + 1) % N]) * k
ans += k
if k <= 0:
return -1
i = R[i]
i = N - 1
while i >= 0:
if B[i] == A[i]:
if D[i] == 0:
c += 1
D[i] = 1
if L[i] >= 0:
R[L[i]] = R[i]
if R[i] < N:
L[R[i]] = L[i]
if B[i] > A[i] and B[i] >= max(B[i - 1], B[(i + 1) % N]):
k = -(
-(B[i] - max(B[i - 1], B[(i + 1) % N], A[i]))
// (B[i - 1] + B[(i + 1) % N])
)
B[i] -= (B[i - 1] + B[(i + 1) % N]) * k
ans += k
if k <= 0:
return -1
i = L[i]
return ans
print(calc())
| Statement
There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For
this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.
Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st
number.
Determine if Takahashi can achieve his objective. If the answer is yes, find
the minimum number of operations required. | [{"input": "3\n 1 1 1\n 13 5 7", "output": "4\n \n\nTakahashi can achieve his objective by, for example, performing the following\noperations:\n\n * Replace the second number with 3.\n * Replace the second number with 5.\n * Replace the third number with 7.\n * Replace the first number with 13.\n\n* * *"}, {"input": "4\n 1 2 3 4\n 2 3 4 5", "output": "-1\n \n\n* * *"}, {"input": "5\n 5 6 5 2 1\n 9817 1108 6890 4343 8704", "output": "25"}] |
Print the minimum number of operations required, or `-1` if the objective
cannot be achieved.
* * * | s684454450 | Wrong Answer | p02941 | Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
B_1 B_2 ... B_N | print(-1)
| Statement
There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For
this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.
Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st
number.
Determine if Takahashi can achieve his objective. If the answer is yes, find
the minimum number of operations required. | [{"input": "3\n 1 1 1\n 13 5 7", "output": "4\n \n\nTakahashi can achieve his objective by, for example, performing the following\noperations:\n\n * Replace the second number with 3.\n * Replace the second number with 5.\n * Replace the third number with 7.\n * Replace the first number with 13.\n\n* * *"}, {"input": "4\n 1 2 3 4\n 2 3 4 5", "output": "-1\n \n\n* * *"}, {"input": "5\n 5 6 5 2 1\n 9817 1108 6890 4343 8704", "output": "25"}] |
Print the minimum number of operations required, or `-1` if the objective
cannot be achieved.
* * * | s217450293 | Accepted | p02941 | Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
B_1 B_2 ... B_N | from heapq import heapify, heappush, heappop
def max2(x, y):
return x if x >= y else y
def solve(As, Bs):
for A, B in zip(As, Bs):
if A > B:
return -1
PQ = [(-B, i) for i, (A, B) in enumerate(zip(As, Bs)) if A != B]
heapify(PQ)
ans = 0
while PQ:
B, i = heappop(PQ)
A, B = As[i], -B
sumNeib = Bs[i - 1] + Bs[(i + 1) % N]
if B <= sumNeib or B - sumNeib < A:
return -1
num = (B - max2(A, sumNeib)) // sumNeib
B -= sumNeib * num
if B - sumNeib >= A:
B -= sumNeib
num += 1
if A != B:
heappush(PQ, (-B, i))
Bs[i] = B
ans += num
return ans
N = int(input())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
ans = solve(As, Bs)
print(ans)
| Statement
There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For
this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.
Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st
number.
Determine if Takahashi can achieve his objective. If the answer is yes, find
the minimum number of operations required. | [{"input": "3\n 1 1 1\n 13 5 7", "output": "4\n \n\nTakahashi can achieve his objective by, for example, performing the following\noperations:\n\n * Replace the second number with 3.\n * Replace the second number with 5.\n * Replace the third number with 7.\n * Replace the first number with 13.\n\n* * *"}, {"input": "4\n 1 2 3 4\n 2 3 4 5", "output": "-1\n \n\n* * *"}, {"input": "5\n 5 6 5 2 1\n 9817 1108 6890 4343 8704", "output": "25"}] |
Print the minimum number of operations required, or `-1` if the objective
cannot be achieved.
* * * | s141751389 | Accepted | p02941 | Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
B_1 B_2 ... B_N | import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
def getN():
return int(input())
def getList():
return list(map(int, input().split()))
import math
n = getN()
anums = getList()
bnums = getList()
ans = 0
okay = [0 for i in range(n)]
update = True
while update:
update = False
for i in range(n):
if not okay[i]:
if i == n - 1:
j = 0
else:
j = i + 1
h = i - 1
a, b, c, tgt = bnums[h], bnums[i], bnums[j], anums[i]
# print(a,b,c)
if b > max(a, c):
if tgt > b:
print(-1)
sys.exit()
if tgt != b:
dec = math.ceil((b - (max(a, c, tgt))) / (a + c))
bnums[i] -= dec * (a + c)
ans += dec
update = True
if anums[i] == bnums[i]:
okay[i] = 1
# print(coll, anums, bnums)
print(ans)
| Statement
There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For
this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.
Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st
number.
Determine if Takahashi can achieve his objective. If the answer is yes, find
the minimum number of operations required. | [{"input": "3\n 1 1 1\n 13 5 7", "output": "4\n \n\nTakahashi can achieve his objective by, for example, performing the following\noperations:\n\n * Replace the second number with 3.\n * Replace the second number with 5.\n * Replace the third number with 7.\n * Replace the first number with 13.\n\n* * *"}, {"input": "4\n 1 2 3 4\n 2 3 4 5", "output": "-1\n \n\n* * *"}, {"input": "5\n 5 6 5 2 1\n 9817 1108 6890 4343 8704", "output": "25"}] |
Print the minimum number of operations required, or `-1` if the objective
cannot be achieved.
* * * | s243517134 | Wrong Answer | p02941 | Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
B_1 B_2 ... B_N | import sys
readline = sys.stdin.readline
class Segtree:
def __init__(self, A, intv, initialize=True, segf=max):
self.N = len(A)
self.N0 = 2 ** (self.N - 1).bit_length()
self.intv = intv
self.segf = segf
if initialize:
self.data = [intv] * self.N0 + A + [intv] * (self.N0 - self.N)
for i in range(self.N0 - 1, 0, -1):
self.data[i] = self.segf(self.data[2 * i], self.data[2 * i + 1])
else:
self.data = [intv] * (2 * self.N0)
def update(self, k, x):
k += self.N0
# self.data[k] = x
while k > 0:
k >>= 1
self.data[k] = self.segf(self.data[2 * k], self.data[2 * k + 1])
def query(self, l, r):
L, R = l + self.N0, r + self.N0
s = self.intv
while L < R:
if R & 1:
R -= 1
s = self.segf(s, self.data[R])
if L & 1:
s = self.segf(s, self.data[L])
L += 1
L >>= 1
R >>= 1
return s
def binsearch(self, l, r, check, reverse=False):
L, R = l + self.N0, r + self.N0
SL, SR = [], []
while L < R:
if R & 1:
R -= 1
SR.append(R)
if L & 1:
SL.append(L)
L += 1
L >>= 1
R >>= 1
if reverse:
for idx in SR + SL[::-1]:
if check(self.data[idx]):
break
else:
return -1
while idx < self.N0:
if check(self.data[2 * idx + 1]):
idx = 2 * idx + 1
else:
idx = 2 * idx
return idx
else:
for idx in SL + SR[::-1]:
if check(self.data[idx]):
break
else:
return -1
while idx < self.N0:
if check(self.data[2 * idx]):
idx = 2 * idx
else:
idx = 2 * idx + 1
return idx
N = int(readline())
A = list(map(int, readline().split()))
B = list(map(int, readline().split()))
inf = 10**10 + 7
C = B + [-inf]
res = 0
T = Segtree(
list(range(N)), N, initialize=True, segf=lambda x, y: x if C[x] > C[y] else y
)
cnt = 0
while True:
res += 1
idx = T.query(0, T.N0)
B[idx] -= B[(idx - 1) % N] + B[(idx + 1) % N]
C[idx] -= B[(idx - 1) % N] + B[(idx + 1) % N]
if A[idx] > C[idx]:
res = -1
break
if A[idx] == C[idx]:
cnt += 1
C[idx] = -inf
if cnt == N:
break
T.update(idx, B[idx])
print(res)
| Statement
There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For
this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.
Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st
number.
Determine if Takahashi can achieve his objective. If the answer is yes, find
the minimum number of operations required. | [{"input": "3\n 1 1 1\n 13 5 7", "output": "4\n \n\nTakahashi can achieve his objective by, for example, performing the following\noperations:\n\n * Replace the second number with 3.\n * Replace the second number with 5.\n * Replace the third number with 7.\n * Replace the first number with 13.\n\n* * *"}, {"input": "4\n 1 2 3 4\n 2 3 4 5", "output": "-1\n \n\n* * *"}, {"input": "5\n 5 6 5 2 1\n 9817 1108 6890 4343 8704", "output": "25"}] |
Print the minimum number of operations required, or `-1` if the objective
cannot be achieved.
* * * | s673119885 | Accepted | p02941 | Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
B_1 B_2 ... B_N | import glob
# 問題ごとのディレクトリのトップからの相対パス
REL_PATH = "ABC\\AGC\\C"
# テスト用ファイル置き場のトップ
TOP_PATH = "C:\\AtCoder"
class Common:
problem = []
index = 0
def __init__(self, rel_path):
self.rel_path = rel_path
def initialize(self, path):
file = open(path)
self.problem = file.readlines()
self.index = 0
return
def input_data(self):
try:
IS_TEST
self.index += 1
return self.problem[self.index - 1]
except NameError:
return input()
def resolve(self):
pass
def exec_resolve(self):
try:
IS_TEST
for path in glob.glob(TOP_PATH + "\\" + self.rel_path + "/*.txt"):
print("Test: " + path)
self.initialize(path)
self.resolve()
print("\n\n")
except NameError:
self.resolve()
class C(Common):
def resolve(self):
ring_len = int(self.input_data())
first_ring = [int(i) for i in self.input_data().split()]
now_ring = [int(i) for i in self.input_data().split()]
count = 0
result = True
loop = True
while loop:
result = True
loop = False
i = 0
while i < ring_len:
if first_ring[i] == now_ring[i]:
i += 1
continue
result = False
if first_ring[i] > now_ring[i]:
break
if i != 0:
prv = i - 1
else:
prv = ring_len - 1
if i != ring_len - 1:
nxt = i + 1
else:
nxt = 0
if now_ring[i] > now_ring[prv] + now_ring[nxt]:
loop = True
tmp = int(
(now_ring[i] - first_ring[i]) / (now_ring[prv] + now_ring[nxt])
)
if tmp == 0:
loop = False
break
loop = True
now_ring[i] -= (now_ring[prv] + now_ring[nxt]) * tmp
count += tmp
i = i - 2
if i < -1:
i += ring_len
i += 1
if result:
loop = False
if result:
print(str(count))
else:
print("-1")
solver = C(REL_PATH)
solver.exec_resolve()
| Statement
There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For
this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.
Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st
number.
Determine if Takahashi can achieve his objective. If the answer is yes, find
the minimum number of operations required. | [{"input": "3\n 1 1 1\n 13 5 7", "output": "4\n \n\nTakahashi can achieve his objective by, for example, performing the following\noperations:\n\n * Replace the second number with 3.\n * Replace the second number with 5.\n * Replace the third number with 7.\n * Replace the first number with 13.\n\n* * *"}, {"input": "4\n 1 2 3 4\n 2 3 4 5", "output": "-1\n \n\n* * *"}, {"input": "5\n 5 6 5 2 1\n 9817 1108 6890 4343 8704", "output": "25"}] |
Print the maximum possible total number of coins of all colors he gets.
* * * | s081999686 | Wrong Answer | p03653 | Input is given from Standard Input in the following format:
X Y Z
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{X+Y+Z} B_{X+Y+Z} C_{X+Y+Z} | from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
sys.setrecursionlimit(2147483647)
INF = 10**13
def LI():
return list(map(int, sys.stdin.readline().split()))
def I():
return int(sys.stdin.readline())
def LS():
return sys.stdin.readline().rstrip().split()
def S():
return sys.stdin.readline().rstrip()
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
def SRL(n):
return [list(S()) for i in range(n)]
def MSRL(n):
return [[int(j) for j in list(S())] for i in range(n)]
mod = 10**9 + 7
x, y, z = LI()
A = []
B = []
C = []
T = []
for i in range(x + y + z):
a, b, c = LI()
A += [a]
B += [b]
C += [c]
T += [(a, i, 0), (b, i, 1), (c, i, 2)]
T.sort(reverse=True)
D = [x, y, z]
F = [0] * (x + y + z)
ans = 0
for t, j, k in T:
if D[k] and F[j] == 0:
ans += t
D[k] -= 1
F[j] = 1
print(ans)
| Statement
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has
A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins
from Y of the people and bronze coins from Z of the people. It is not possible
to get two or more different colors of coins from a single person. On the
other hand, a person will give all of his/her coins of the color specified by
Snuke.
Snuke would like to maximize the total number of coins of all colors he gets.
Find the maximum possible number of coins. | [{"input": "1 2 1\n 2 4 4\n 3 2 1\n 7 6 7\n 5 2 3", "output": "18\n \n\nGet silver coins from Person 1, silver coins from Person 2, bronze coins from\nPerson 3 and gold coins from Person 4. In this case, the total number of coins\nwill be 4+2+7+5=18. It is not possible to get 19 or more coins, and the answer\nis therefore 18.\n\n* * *"}, {"input": "3 3 2\n 16 17 1\n 2 7 5\n 2 16 12\n 17 7 7\n 13 2 10\n 12 18 3\n 16 15 19\n 5 6 2", "output": "110\n \n\n* * *"}, {"input": "6 2 4\n 33189 87907 277349742\n 71616 46764 575306520\n 8801 53151 327161251\n 58589 4337 796697686\n 66854 17565 289910583\n 50598 35195 478112689\n 13919 88414 103962455\n 7953 69657 699253752\n 44255 98144 468443709\n 2332 42580 752437097\n 39752 19060 845062869\n 60126 74101 382963164", "output": "3093929975"}] |
Print the maximum possible total number of coins of all colors he gets.
* * * | s810451327 | Wrong Answer | p03653 | Input is given from Standard Input in the following format:
X Y Z
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{X+Y+Z} B_{X+Y+Z} C_{X+Y+Z} | import math
def sum_coin(a, b):
# 転置して該当列を合算
temp1 = list(map(list, zip(*a)))
temp2 = list(map(list, zip(*b)))
coins = (
sum(temp1[2][:Y])
+ sum(temp1[3][Y:])
+ sum(temp2[3][:(-X)])
+ sum(temp2[1][(-X):])
)
return coins
###入力###
input1 = input("").split(" ")
X = int(input1[0])
Y = int(input1[1])
Z = int(input1[2])
N = X + Y + Z
temp = [input() for _ in range(N)]
matrix = [None] * N
for i in range(N):
a = int(temp[i].split(" ")[0])
b = int(temp[i].split(" ")[1])
c = int(temp[i].split(" ")[2])
matrix[i] = [i, a, b, c, (a - b), (b - c), (c - a)]
###処理###
matrix.sort(key=lambda k: k[4]) # (金-銀)で昇順ソート
print(matrix)
head = sorted(matrix[:Y], key=lambda k: k[5], reverse=True) # (銀-銅)で降順ソート
tail = sorted(matrix[Y:], key=lambda k: k[6], reverse=True) # (銅-金)で降順ソート
print("head:", head)
print("tail:", tail)
result = sum_coin(head, tail)
print("coins", result)
# Y<=k<=(N-X)の中でコイン最大値を求める
for k in range(Y, N - X):
print("k", k)
# headにmatrix[Y+1]を追加
if head[0][5] < matrix[k][5]:
p = 0
elif head[-1][5] > matrix[k][5]:
p = len(head) - 1
else:
start = 0
last = len(head) - 1
p = last
while (last - start) > 1:
j = math.ceil((start + last) / 2)
print("j", j)
if head[j][5] < matrix[k][5]:
last = j
elif head[j][5] > matrix[k][5]:
start = j
else:
p = j
break
p = last
head.insert(p, matrix[k])
# tailからmatrix[Y+1]を削除
tail.pop(tail.index(matrix[k]))
print("head:", head)
print("tail:", tail)
coins = sum_coin(head, tail)
print("coins", coins)
# 暫定1位更新
if result < coins:
result = coins
###出力###
print(result)
| Statement
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has
A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins
from Y of the people and bronze coins from Z of the people. It is not possible
to get two or more different colors of coins from a single person. On the
other hand, a person will give all of his/her coins of the color specified by
Snuke.
Snuke would like to maximize the total number of coins of all colors he gets.
Find the maximum possible number of coins. | [{"input": "1 2 1\n 2 4 4\n 3 2 1\n 7 6 7\n 5 2 3", "output": "18\n \n\nGet silver coins from Person 1, silver coins from Person 2, bronze coins from\nPerson 3 and gold coins from Person 4. In this case, the total number of coins\nwill be 4+2+7+5=18. It is not possible to get 19 or more coins, and the answer\nis therefore 18.\n\n* * *"}, {"input": "3 3 2\n 16 17 1\n 2 7 5\n 2 16 12\n 17 7 7\n 13 2 10\n 12 18 3\n 16 15 19\n 5 6 2", "output": "110\n \n\n* * *"}, {"input": "6 2 4\n 33189 87907 277349742\n 71616 46764 575306520\n 8801 53151 327161251\n 58589 4337 796697686\n 66854 17565 289910583\n 50598 35195 478112689\n 13919 88414 103962455\n 7953 69657 699253752\n 44255 98144 468443709\n 2332 42580 752437097\n 39752 19060 845062869\n 60126 74101 382963164", "output": "3093929975"}] |
Print the maximum possible total number of coins of all colors he gets.
* * * | s464437801 | Runtime Error | p03653 | Input is given from Standard Input in the following format:
X Y Z
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{X+Y+Z} B_{X+Y+Z} C_{X+Y+Z} | # -*- coding: utf-8 -*-
X, Y, Z = map(int, input().split())
N = X + Y + Z
arys_orig = []
arys = []
for i in range(N):
tmp = input()
ary = [int(a) for a in tmp.split()]
arys_orig.append(ary)
m = max(ary)
ary2 = [a - m for a in ary]
arys.append(ary2)
def argsort(ary):
x, y, z = ary
if x < y:
if y < z:
return (0, 1, 2)
elif x < z:
# x < z <= y
return (0, 2, 1)
else:
# z <= x < y
return (2, 0, 1)
else:
# y <= x
if x < z:
# y <= x < z
return (1, 0, 2)
elif y < z:
# y < z <= x
return (1, 2, 0)
else:
# z <= y <= x
return (2, 1, 0)
remain = [X, Y, Z]
choice = [None for i in range(N)]
for i, ary in enumerate(arys):
so = argsort(ary)
for s in so[::-1]:
if remain[s] > 0:
remain[s] -= 1
choice[i] = s
break
change_cand = [[0, 1], [0, 2], [1, 2]]
i = 0
while True:
changer_2 = change_cand[i]
changers = [changer_2, changer_2[::-1]]
max_dis = [None, None]
max_can = [None, None]
for j, changer in enumerate(changers):
for cand in range(N):
if choice[cand] != changer[0]:
continue
get = arys[cand][changer[1]] - arys[cand][changer[0]]
if max_dis[j] is None or max_dis[j] < get:
max_dis[j] = get
max_can[j] = cand
if max_dis[0] + max_dis[1] > 0:
choice[max_can[0]], choice[max_can[1]] = choice[max_can[1]], choice[max_can[0]]
i = 0
else:
i += 1
sum = 0
for i in range(N):
sum += arys_orig[choice[i]]
print(sum)
| Statement
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has
A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins
from Y of the people and bronze coins from Z of the people. It is not possible
to get two or more different colors of coins from a single person. On the
other hand, a person will give all of his/her coins of the color specified by
Snuke.
Snuke would like to maximize the total number of coins of all colors he gets.
Find the maximum possible number of coins. | [{"input": "1 2 1\n 2 4 4\n 3 2 1\n 7 6 7\n 5 2 3", "output": "18\n \n\nGet silver coins from Person 1, silver coins from Person 2, bronze coins from\nPerson 3 and gold coins from Person 4. In this case, the total number of coins\nwill be 4+2+7+5=18. It is not possible to get 19 or more coins, and the answer\nis therefore 18.\n\n* * *"}, {"input": "3 3 2\n 16 17 1\n 2 7 5\n 2 16 12\n 17 7 7\n 13 2 10\n 12 18 3\n 16 15 19\n 5 6 2", "output": "110\n \n\n* * *"}, {"input": "6 2 4\n 33189 87907 277349742\n 71616 46764 575306520\n 8801 53151 327161251\n 58589 4337 796697686\n 66854 17565 289910583\n 50598 35195 478112689\n 13919 88414 103962455\n 7953 69657 699253752\n 44255 98144 468443709\n 2332 42580 752437097\n 39752 19060 845062869\n 60126 74101 382963164", "output": "3093929975"}] |
Print the maximum possible total number of coins of all colors he gets.
* * * | s833302439 | Wrong Answer | p03653 | Input is given from Standard Input in the following format:
X Y Z
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{X+Y+Z} B_{X+Y+Z} C_{X+Y+Z} | import numpy as np
x, y, z = map(int, input().split())
n = x + y + z
a = np.zeros((n,), dtype=np.int64)
b = np.zeros((n,), dtype=np.int64)
c = np.zeros((n,), dtype=np.int64)
for i in range(n):
a[i], b[i], c[i] = map(int, input().split())
sub_ab = b - a
idx_arg = np.argsort(sub_ab)
top = x + z - 1
bottom = x - 1
def solve(mid):
sub_ac = c[idx_arg[:mid]] - a[idx_arg[:mid]]
sub_bc = c[idx_arg[mid:]] - b[idx_arg[mid:]]
idx_arg_ac = np.argsort(sub_ac)
idx_arg_bc = np.argsort(sub_bc)
# print(mid, idx_arg_ac, idx_arg_bc)
# print(mid, idx_arg[:mid][idx_arg_ac], idx_arg[mid:][idx_arg_bc])
return (
a[idx_arg[:mid][idx_arg_ac[:x]]].sum()
+ c[idx_arg[:mid][idx_arg_ac[x:]]].sum()
+ b[idx_arg[mid:][idx_arg_bc[:y]]].sum()
+ c[idx_arg[mid:][idx_arg_bc[y:]]].sum()
)
# for i in range(x, x+z+1):
# print(solve(i))
while top - bottom > 1:
middle = (top + bottom) // 2
if solve(middle) > solve(middle + 1):
top = middle
else:
bottom = middle
ans = max(solve(top), solve(x + z))
print(ans)
| Statement
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has
A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins
from Y of the people and bronze coins from Z of the people. It is not possible
to get two or more different colors of coins from a single person. On the
other hand, a person will give all of his/her coins of the color specified by
Snuke.
Snuke would like to maximize the total number of coins of all colors he gets.
Find the maximum possible number of coins. | [{"input": "1 2 1\n 2 4 4\n 3 2 1\n 7 6 7\n 5 2 3", "output": "18\n \n\nGet silver coins from Person 1, silver coins from Person 2, bronze coins from\nPerson 3 and gold coins from Person 4. In this case, the total number of coins\nwill be 4+2+7+5=18. It is not possible to get 19 or more coins, and the answer\nis therefore 18.\n\n* * *"}, {"input": "3 3 2\n 16 17 1\n 2 7 5\n 2 16 12\n 17 7 7\n 13 2 10\n 12 18 3\n 16 15 19\n 5 6 2", "output": "110\n \n\n* * *"}, {"input": "6 2 4\n 33189 87907 277349742\n 71616 46764 575306520\n 8801 53151 327161251\n 58589 4337 796697686\n 66854 17565 289910583\n 50598 35195 478112689\n 13919 88414 103962455\n 7953 69657 699253752\n 44255 98144 468443709\n 2332 42580 752437097\n 39752 19060 845062869\n 60126 74101 382963164", "output": "3093929975"}] |
Print the maximum possible total number of coins of all colors he gets.
* * * | s362254342 | Runtime Error | p03653 | Input is given from Standard Input in the following format:
X Y Z
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{X+Y+Z} B_{X+Y+Z} C_{X+Y+Z} | from sys import stdin
a = int(stdin.readline().rstrip())
b = int(stdin.readline().rstrip())
c = int(stdin.readline().rstrip())
x = int(stdin.readline().rstrip())
count = 0
for i in range(a + 1):
if i * 500 > x:
continue
for j in range(b + 1):
if i * 500 + j * 100 > x:
continue
for k in range(c + 1):
if i * 500 + j * 100 + k * 50 == x:
count += 1
print(count)
| Statement
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has
A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins
from Y of the people and bronze coins from Z of the people. It is not possible
to get two or more different colors of coins from a single person. On the
other hand, a person will give all of his/her coins of the color specified by
Snuke.
Snuke would like to maximize the total number of coins of all colors he gets.
Find the maximum possible number of coins. | [{"input": "1 2 1\n 2 4 4\n 3 2 1\n 7 6 7\n 5 2 3", "output": "18\n \n\nGet silver coins from Person 1, silver coins from Person 2, bronze coins from\nPerson 3 and gold coins from Person 4. In this case, the total number of coins\nwill be 4+2+7+5=18. It is not possible to get 19 or more coins, and the answer\nis therefore 18.\n\n* * *"}, {"input": "3 3 2\n 16 17 1\n 2 7 5\n 2 16 12\n 17 7 7\n 13 2 10\n 12 18 3\n 16 15 19\n 5 6 2", "output": "110\n \n\n* * *"}, {"input": "6 2 4\n 33189 87907 277349742\n 71616 46764 575306520\n 8801 53151 327161251\n 58589 4337 796697686\n 66854 17565 289910583\n 50598 35195 478112689\n 13919 88414 103962455\n 7953 69657 699253752\n 44255 98144 468443709\n 2332 42580 752437097\n 39752 19060 845062869\n 60126 74101 382963164", "output": "3093929975"}] |
Print the maximum possible total number of coins of all colors he gets.
* * * | s421666303 | Wrong Answer | p03653 | Input is given from Standard Input in the following format:
X Y Z
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{X+Y+Z} B_{X+Y+Z} C_{X+Y+Z} | """
https://atcoder.jp/contests/agc018/tasks/agc018_c
絶対最大なのは、全員から一番たくさん持ってるコインを貰う事
とりあえずそうして、後から人数を調整することを考える
金と銀を貰いすぎたとする
金をN個減らす、銀をM個減らす、銅をN+M個増やす…?
→必ずしもこうではなさそう…
金を貰いすぎたとする。
貰いすぎたコインを減らし、別のコインを増やす
削った時の減少量が銀にするとA-B , 銅だとA-C
減少量最小化問題になる
→あれなんかやったことがある気が…?
方針違う?
適当にX,Y,Z人で振り分ける
swapすると増える限りswapし続ける?
金銀でswapする場合(1が金→銀)
(B1-A1) + (A2-B2)増える
どちらもheapqに突っ込んで、正な限りswapし続ける?
金銀・金銅・銀銅でやれば最適解になるか?
→そんなことはない(改善できない局所解がある…)
なんもわからん…
=====ちょっと答えを見た=====
まず銅を無視する(金銀だけに分ける)
A-Bで降順ソート(B-A)で昇順ソート
ここで金銀グループはどこかで切って左右にすっぱり分けられる
その中で金銅・銀銅を同様に求めればよい?
→ヒープを使って切り方を全探索
まずX個金・Y+Z個銀グループにしたとする
→銀グループは B-Cで昇順ソート小さいほうからZ個の和*-1 + 大きいほうからY個の和が現在の解
左からX個金・右からZ個銅にして、ずらしていって解を求める
X側では、a-c をヒープに入れ、最小のやつを取り除いて-1をかけて寄与に足せばいい
Z側では逆
"""
import heapq
X, Y, Z = map(int, input().split())
ABC = []
for i in range(X + Y + Z):
a, b, c = map(int, input().split())
ABC.append((b - a, a, b, c))
ABC.sort()
# 金側
q = []
ansX = []
now = 0
for i in range(X):
tmp, a, b, c = ABC[i]
heapq.heappush(q, a - c)
now += a
ansX.append(now)
for i in range(X, X + Z):
tmp, a, b, c = ABC[i]
heapq.heappush(q, a - c)
now += a
pp = heapq.heappop(q)
now -= pp
ansX.append(now)
# 銀側
ABC.reverse()
q = []
ansY = []
now = 0
for i in range(Y):
tmp, a, b, c = ABC[i]
heapq.heappush(q, b - c)
now += b
ansY.append(now)
for i in range(Y, Y + Z):
tmp, a, b, c = ABC[i]
heapq.heappush(q, b - c)
now += b
pp = heapq.heappop(q)
now -= pp
ansY.append(now)
ansY.reverse()
# print (ABC)
# print (ansX,ansY)
ans = 0
for i in range(Z):
ans = max(ans, ansX[i] + ansY[i])
print(ans)
| Statement
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has
A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins
from Y of the people and bronze coins from Z of the people. It is not possible
to get two or more different colors of coins from a single person. On the
other hand, a person will give all of his/her coins of the color specified by
Snuke.
Snuke would like to maximize the total number of coins of all colors he gets.
Find the maximum possible number of coins. | [{"input": "1 2 1\n 2 4 4\n 3 2 1\n 7 6 7\n 5 2 3", "output": "18\n \n\nGet silver coins from Person 1, silver coins from Person 2, bronze coins from\nPerson 3 and gold coins from Person 4. In this case, the total number of coins\nwill be 4+2+7+5=18. It is not possible to get 19 or more coins, and the answer\nis therefore 18.\n\n* * *"}, {"input": "3 3 2\n 16 17 1\n 2 7 5\n 2 16 12\n 17 7 7\n 13 2 10\n 12 18 3\n 16 15 19\n 5 6 2", "output": "110\n \n\n* * *"}, {"input": "6 2 4\n 33189 87907 277349742\n 71616 46764 575306520\n 8801 53151 327161251\n 58589 4337 796697686\n 66854 17565 289910583\n 50598 35195 478112689\n 13919 88414 103962455\n 7953 69657 699253752\n 44255 98144 468443709\n 2332 42580 752437097\n 39752 19060 845062869\n 60126 74101 382963164", "output": "3093929975"}] |
Print the maximum possible total number of coins of all colors he gets.
* * * | s871984224 | Wrong Answer | p03653 | Input is given from Standard Input in the following format:
X Y Z
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{X+Y+Z} B_{X+Y+Z} C_{X+Y+Z} | import heapq
x, y, z = [int(item) for item in input().split()]
gsb = []
for i in range(x + y + z):
gsb.append([int(item) for item in input().split()])
gsb.sort(key=lambda x: x[0] - x[1], reverse=True)
g_sum = sum(item[0] for item in gsb[:x])
s_sum = sum(item[1] for item in gsb[x + z : x + y + z])
b_sum = sum(item[2] for item in gsb[x : x + z])
gb_pq = [a - c for a, b, c in gsb[:x]]
sb_pq = [b - c for a, b, c in gsb[x + z : x + y + z]]
heapq.heapify(gb_pq)
heapq.heapify(sb_pq)
ans_gb = [0]
gb_total_delta = 0
for a, b, c in gsb[x : x + z]:
new_gb = a - c
small_gb = heapq.heappushpop(gb_pq, new_gb)
gb_total_delta += new_gb - small_gb
ans_gb.append(gb_total_delta)
ans_sb = [0]
sb_total_delta = 0
for a, b, c in gsb[x : x + z][::-1]:
new_sb = b - c
small_sb = heapq.heappushpop(sb_pq, new_sb)
sb_total_delta = new_sb - small_sb
ans_sb.append(sb_total_delta)
ans_sb.reverse()
max_delta = 0
for gb, sb in zip(ans_gb, ans_sb):
max_delta = max(max_delta, gb + sb)
print(g_sum + s_sum + b_sum + max_delta)
| Statement
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has
A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins
from Y of the people and bronze coins from Z of the people. It is not possible
to get two or more different colors of coins from a single person. On the
other hand, a person will give all of his/her coins of the color specified by
Snuke.
Snuke would like to maximize the total number of coins of all colors he gets.
Find the maximum possible number of coins. | [{"input": "1 2 1\n 2 4 4\n 3 2 1\n 7 6 7\n 5 2 3", "output": "18\n \n\nGet silver coins from Person 1, silver coins from Person 2, bronze coins from\nPerson 3 and gold coins from Person 4. In this case, the total number of coins\nwill be 4+2+7+5=18. It is not possible to get 19 or more coins, and the answer\nis therefore 18.\n\n* * *"}, {"input": "3 3 2\n 16 17 1\n 2 7 5\n 2 16 12\n 17 7 7\n 13 2 10\n 12 18 3\n 16 15 19\n 5 6 2", "output": "110\n \n\n* * *"}, {"input": "6 2 4\n 33189 87907 277349742\n 71616 46764 575306520\n 8801 53151 327161251\n 58589 4337 796697686\n 66854 17565 289910583\n 50598 35195 478112689\n 13919 88414 103962455\n 7953 69657 699253752\n 44255 98144 468443709\n 2332 42580 752437097\n 39752 19060 845062869\n 60126 74101 382963164", "output": "3093929975"}] |
Print the maximum possible total number of coins of all colors he gets.
* * * | s493078604 | Wrong Answer | p03653 | Input is given from Standard Input in the following format:
X Y Z
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{X+Y+Z} B_{X+Y+Z} C_{X+Y+Z} | x, y, z = map(int, input().split())
ko = []
gou = 0
for i in range(x + y + z):
a = list(map(int, input().split()))
a.append(a[1] - a[0])
a.append(a[2] - a[0])
a.append(a[3] - a[4])
gou += a[0]
ko.append(a)
inf = float("inf")
ko = sorted(ko, key=lambda x: -x[5])
for i in range(y):
gou += ko[i][3]
ko[i] = [-inf, -inf, -inf, -inf, -inf, -inf]
ko = sorted(ko, key=lambda x: -x[4])
for i in range(z):
gou += ko[i][4]
print(gou)
| Statement
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has
A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins
from Y of the people and bronze coins from Z of the people. It is not possible
to get two or more different colors of coins from a single person. On the
other hand, a person will give all of his/her coins of the color specified by
Snuke.
Snuke would like to maximize the total number of coins of all colors he gets.
Find the maximum possible number of coins. | [{"input": "1 2 1\n 2 4 4\n 3 2 1\n 7 6 7\n 5 2 3", "output": "18\n \n\nGet silver coins from Person 1, silver coins from Person 2, bronze coins from\nPerson 3 and gold coins from Person 4. In this case, the total number of coins\nwill be 4+2+7+5=18. It is not possible to get 19 or more coins, and the answer\nis therefore 18.\n\n* * *"}, {"input": "3 3 2\n 16 17 1\n 2 7 5\n 2 16 12\n 17 7 7\n 13 2 10\n 12 18 3\n 16 15 19\n 5 6 2", "output": "110\n \n\n* * *"}, {"input": "6 2 4\n 33189 87907 277349742\n 71616 46764 575306520\n 8801 53151 327161251\n 58589 4337 796697686\n 66854 17565 289910583\n 50598 35195 478112689\n 13919 88414 103962455\n 7953 69657 699253752\n 44255 98144 468443709\n 2332 42580 752437097\n 39752 19060 845062869\n 60126 74101 382963164", "output": "3093929975"}] |
Print the maximum possible total number of coins of all colors he gets.
* * * | s403406174 | Wrong Answer | p03653 | Input is given from Standard Input in the following format:
X Y Z
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{X+Y+Z} B_{X+Y+Z} C_{X+Y+Z} | from heapq import heappush, heappop
x, y, z = map(int, input().split())
l = [list(map(int, input().split())) for _ in range(x + y + z)]
l.sort(key=lambda x: x[1] - x[0])
res = (
sum([p[2] for p in l[:z]])
+ sum([p[0] for p in l[z : z + x]])
+ sum([p[1] for p in l[z + x :]])
)
is_a = [False for _ in range(x + y + z)]
for i in range(z, z + x):
is_a[i] = True
rm = z + x - 1 # rm: rightmost
a_heap, b_heap = [], []
for i in range(z):
heappush(a_heap, [l[i][2] - l[i][0], i])
for i in range(z, z + x):
# print(a_heap[0])
if l[i][2] - l[i][0] - a_heap[0][0] > 0:
# print("hoge")
is_a[i] = False
is_a[a_heap[0][1]] = True
while is_a[rm] == False:
rm -= 1
res += l[i][2] - l[i][0] - a_heap[0][0]
heappop(a_heap)
heappush(a_heap, [l[i][2] - l[i][0], i])
for i in range(z + x, x + y + z):
if b_heap == []:
if l[i][2] - l[i][1] - a_heap[0][0] + l[rm][1] - l[rm][0] > 0:
# print("hoge")
is_a[rm] = False
is_a[a_heap[0][1]] = True
res += l[i][2] - l[i][1] - a_heap[0][0] + l[rm][1] - l[rm][0]
while is_a[rm] == False:
rm -= 1
heappop(a_heap)
heappush(b_heap, l[i][2] - l[i][1])
elif a_heap == []:
q = l[i][2] - l[i][1] - b_heap[0]
if q > 0:
res += q
heappop(b_heap)
heappush(b_heap, l[i][2] - l[i][1])
else:
p = l[i][2] - l[i][1] - a_heap[0][0] + l[rm][1] - l[rm][0]
q = l[i][2] - l[i][1] - b_heap[0]
if max(p, q) > 0:
if p > q:
is_a[rm] = False
is_a[a_heap[0][1]] = True
while is_a[rm] == False:
rm -= 1
res += p
heappop(a_heap)
heappush(b_heap, l[i][2] - l[i][1])
else:
res += q
heappop(b_heap)
heappush(b_heap, l[i][2] - l[i][1])
# print(res)
print(res)
| Statement
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has
A_i gold coins, B_i silver coins and C_i bronze coins.
Snuke is thinking of getting gold coins from X of those people, silver coins
from Y of the people and bronze coins from Z of the people. It is not possible
to get two or more different colors of coins from a single person. On the
other hand, a person will give all of his/her coins of the color specified by
Snuke.
Snuke would like to maximize the total number of coins of all colors he gets.
Find the maximum possible number of coins. | [{"input": "1 2 1\n 2 4 4\n 3 2 1\n 7 6 7\n 5 2 3", "output": "18\n \n\nGet silver coins from Person 1, silver coins from Person 2, bronze coins from\nPerson 3 and gold coins from Person 4. In this case, the total number of coins\nwill be 4+2+7+5=18. It is not possible to get 19 or more coins, and the answer\nis therefore 18.\n\n* * *"}, {"input": "3 3 2\n 16 17 1\n 2 7 5\n 2 16 12\n 17 7 7\n 13 2 10\n 12 18 3\n 16 15 19\n 5 6 2", "output": "110\n \n\n* * *"}, {"input": "6 2 4\n 33189 87907 277349742\n 71616 46764 575306520\n 8801 53151 327161251\n 58589 4337 796697686\n 66854 17565 289910583\n 50598 35195 478112689\n 13919 88414 103962455\n 7953 69657 699253752\n 44255 98144 468443709\n 2332 42580 752437097\n 39752 19060 845062869\n 60126 74101 382963164", "output": "3093929975"}] |
For each dataset, print the number of combinations in a line. | s974302428 | Accepted | p02412 | The input consists of multiple datasets. For each dataset, two integers n and
x are given in a line.
The input ends with two zeros for n and x respectively. Your program should
not process for these terminal symbols. | def isEnd(list):
if (list[0] == 0) and (list[1] == 0):
return True
return False
def answer(list):
kumi = 0
if list[1] < 6:
return kumi
for i in range(1, list[1] + 1):
for j in range(i + 1, list[1] + 1):
another = list[1] - i - j
if (another > j) and (another <= list[0]):
kumi += 1
return kumi
flag = True
a = []
while flag:
t = list(map(int, input().split()))
if isEnd(t):
flag = False
continue
a.append(t)
for i in a:
ans = answer(i)
print(ans)
| How many ways?
Write a program which identifies the number of combinations of three integers
which satisfy the following conditions:
* You should select three distinct integers from 1 to n.
* A total sum of the three integers is x.
For example, there are two combinations for n = 5 and x = 9.
* 1 + 3 + 5 = 9
* 2 + 3 + 4 = 9 | [{"input": "9\n 0 0", "output": "## Note\n\n \u89e3\u8aac"}] |
For each dataset, print the number of combinations in a line. | s520845769 | Runtime Error | p02412 | The input consists of multiple datasets. For each dataset, two integers n and
x are given in a line.
The input ends with two zeros for n and x respectively. Your program should
not process for these terminal symbols. | while True:
a = input().split(" ")
b = 0
s = []
c = [number + 1 for number in range(int(a[0]))]
for i in c:
for e in c:
for f in c:
if i + e + f == int(a[1]) and not (i * e * f in s):
if not (i == e or e == f or f == i):
s.append(i * e * f)
b += 1
print(b)
| How many ways?
Write a program which identifies the number of combinations of three integers
which satisfy the following conditions:
* You should select three distinct integers from 1 to n.
* A total sum of the three integers is x.
For example, there are two combinations for n = 5 and x = 9.
* 1 + 3 + 5 = 9
* 2 + 3 + 4 = 9 | [{"input": "9\n 0 0", "output": "## Note\n\n \u89e3\u8aac"}] |
For each dataset, print the number of combinations in a line. | s922345819 | Wrong Answer | p02412 | The input consists of multiple datasets. For each dataset, two integers n and
x are given in a line.
The input ends with two zeros for n and x respectively. Your program should
not process for these terminal symbols. | x, n = tuple(int(i) for i in input().split())
r = 0
def transnum(int: n):
if n % 3 != 0:
return n + 3 - n % 3
else:
return n
amin = n // 3 + 1
amax = 2 * transnum(n) // 3
if amax > x:
amax = x
A = [j for j in range(amin, amax + 1)]
# print(A)
for a in A:
bmin = (n - a) // 3 + 1
bmax = 2 * transnum(n - a) // 3
if bmax > a:
bmax = a
B = [j for j in range(bmin, bmax) if j + j != n - a]
# print(B)
for b in B:
cmin = (n - a - b) // 3 + 1
cmax = 2 * transnum(n - a - b) // 3
if cmax > b:
cmax = b
C = [k for k in range(cmin, cmax) if k == n - a - b]
# print(C)
r += len(C)
C.clear()
B.clear()
print(r)
| How many ways?
Write a program which identifies the number of combinations of three integers
which satisfy the following conditions:
* You should select three distinct integers from 1 to n.
* A total sum of the three integers is x.
For example, there are two combinations for n = 5 and x = 9.
* 1 + 3 + 5 = 9
* 2 + 3 + 4 = 9 | [{"input": "9\n 0 0", "output": "## Note\n\n \u89e3\u8aac"}] |
For each dataset, print the number of combinations in a line. | s087378482 | Accepted | p02412 | The input consists of multiple datasets. For each dataset, two integers n and
x are given in a line.
The input ends with two zeros for n and x respectively. Your program should
not process for these terminal symbols. | # coding: utf-8
# Here your code !
def func():
data = []
while True:
try:
line = [int(item) for item in input().rstrip().split(" ")]
if line == [0, 0]:
break
data.append(line)
except EOFError:
break
except:
return inputError()
left = 1
numbers = 3
[print(len(sumcombination(left, line[0], numbers, line[1]))) for line in data]
def sumcombination(left, right, numbers, total):
"""
left ~ right??????????????°??????(numbers)????????´??°???????¨????total?????????????????????????????????????????????
"""
result = []
if numbers == 1:
if (left <= total) and (right >= total):
result = [total]
return result
for i in range(left, right + 1):
if numbers == 2:
if i >= total - i:
break
elif (i != total - i) and (left <= total - i) and (right >= total - i):
result.append([i, total - i])
elif (len(range(i, right + 1)) < numbers) or (
sum(range(i + 1, i + numbers)) > total - i
):
break
elif sum(range(right - numbers + 2, right + 1)) < total - i:
continue
else:
sub = sumcombination(i + 1, right, numbers - 1, total - i)
if len(sub) > 0:
[items.insert(0, i) for items in sub]
result.extend(sub)
return result
def inputError():
print("input error")
return -1
func()
| How many ways?
Write a program which identifies the number of combinations of three integers
which satisfy the following conditions:
* You should select three distinct integers from 1 to n.
* A total sum of the three integers is x.
For example, there are two combinations for n = 5 and x = 9.
* 1 + 3 + 5 = 9
* 2 + 3 + 4 = 9 | [{"input": "9\n 0 0", "output": "## Note\n\n \u89e3\u8aac"}] |
For each dataset, print the number of combinations in a line. | s148955144 | Wrong Answer | p02412 | The input consists of multiple datasets. For each dataset, two integers n and
x are given in a line.
The input ends with two zeros for n and x respectively. Your program should
not process for these terminal symbols. | n, x = [int(temp) for temp in input().split()]
cen = x // 3
for temp in range(1, cen):
pass
print(temp)
| How many ways?
Write a program which identifies the number of combinations of three integers
which satisfy the following conditions:
* You should select three distinct integers from 1 to n.
* A total sum of the three integers is x.
For example, there are two combinations for n = 5 and x = 9.
* 1 + 3 + 5 = 9
* 2 + 3 + 4 = 9 | [{"input": "9\n 0 0", "output": "## Note\n\n \u89e3\u8aac"}] |
For each dataset, print the number of combinations in a line. | s885003214 | Wrong Answer | p02412 | The input consists of multiple datasets. For each dataset, two integers n and
x are given in a line.
The input ends with two zeros for n and x respectively. Your program should
not process for these terminal symbols. | n, x = map(int, input().split())
li = []
for i in range(1, x // 3):
y = x - i
li.append((y - 1) // 2 - max(i, y - n - 1))
print(sum([comb for comb in li if comb > 0]))
| How many ways?
Write a program which identifies the number of combinations of three integers
which satisfy the following conditions:
* You should select three distinct integers from 1 to n.
* A total sum of the three integers is x.
For example, there are two combinations for n = 5 and x = 9.
* 1 + 3 + 5 = 9
* 2 + 3 + 4 = 9 | [{"input": "9\n 0 0", "output": "## Note\n\n \u89e3\u8aac"}] |
For each dataset, print the number of combinations in a line. | s782064777 | Wrong Answer | p02412 | The input consists of multiple datasets. For each dataset, two integers n and
x are given in a line.
The input ends with two zeros for n and x respectively. Your program should
not process for these terminal symbols. | while True:
n,x=map(int,input().split())
if n==0 and x==0:
break
sum=0
for i in range(x//3+1,n):
if (x-i)%2==0:
sum+=(x-i)/2-1
elif(x-i)%2==1:
sum+=(x-i-1)/2
elif 2*i<x:
sum-=1
print(int(sum)) | How many ways?
Write a program which identifies the number of combinations of three integers
which satisfy the following conditions:
* You should select three distinct integers from 1 to n.
* A total sum of the three integers is x.
For example, there are two combinations for n = 5 and x = 9.
* 1 + 3 + 5 = 9
* 2 + 3 + 4 = 9 | [{"input": "9\n 0 0", "output": "## Note\n\n \u89e3\u8aac"}] |
For each dataset, print the number of combinations in a line. | s425880387 | Accepted | p02412 | The input consists of multiple datasets. For each dataset, two integers n and
x are given in a line.
The input ends with two zeros for n and x respectively. Your program should
not process for these terminal symbols. | def mapt(fn, *args):
return tuple(map(fn, *args))
# def sum_num_is_x(n, x):
# seen = set()
# for a in range(1, n+1):
# for b in range(1, n+1):
# for c in range(1, n+1):
# if a != b and a != c and b != c:
# if a + b + c == x:
# k = tuple(sorted([a,b,c]))
# seen.add(k)
# return len(seen)
from itertools import combinations
def sum_num_is_x(n, x):
return len([row for row in combinations(range(1, n + 1), 3) if sum(row) == x])
def Input():
while True:
n, x = mapt(int, input().split(" "))
if n == x == 0:
break
print(sum_num_is_x(n, x))
Input()
| How many ways?
Write a program which identifies the number of combinations of three integers
which satisfy the following conditions:
* You should select three distinct integers from 1 to n.
* A total sum of the three integers is x.
For example, there are two combinations for n = 5 and x = 9.
* 1 + 3 + 5 = 9
* 2 + 3 + 4 = 9 | [{"input": "9\n 0 0", "output": "## Note\n\n \u89e3\u8aac"}] |
For each query, print the distance. The output values should be in a decimal
fraction with an error less than 0.00000001. | s561436608 | Accepted | p02296 | The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the
following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3 | import math
from typing import Union
class Point(object):
__slots__ = ["x", "y"]
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, other: Union[int, float]):
return Point(self.x * other, self.y * other)
def norm(self):
return pow(self.x, 2) + pow(self.y, 2)
def abs(self):
return math.sqrt(self.norm())
def __repr__(self):
return f"({self.x},{self.y})"
class Vector(Point):
__slots__ = ["x", "y", "pt1", "pt2"]
def __init__(self, pt1: Point, pt2: Point):
super().__init__(pt2.x - pt1.x, pt2.y - pt1.y)
self.pt1 = pt1
self.pt2 = pt2
def dot(self, other):
return self.x * other.x + self.y * other.y
def cross(self, other):
return self.x * other.y - self.y * other.x
def __repr__(self):
return f"{self.pt1},{self.pt2}"
class Segment(Vector):
__slots__ = ["x", "y", "pt1", "pt2"]
def __init__(self, pt1: Point, pt2: Point):
super().__init__(pt1, pt2)
def projection(self, pt: Point) -> Point:
t = self.dot(Vector(self.pt1, pt)) / self.norm()
return self.pt1 + self * t
def reflection(self, pt: Point) -> Point:
return self.projection(pt) * 2 - pt
def is_intersected_with(self, other) -> bool:
if (
self.point_geometry(other.pt1) * self.point_geometry(other.pt2)
) <= 0 and other.point_geometry(self.pt1) * other.point_geometry(self.pt2) <= 0:
return True
else:
return False
def point_geometry(self, pt: Point) -> int:
"""
[-2:"Online Back", -1:"Counter Clockwise", 0:"On Segment", 1:"Clockwise", 2:"Online Front"]
"""
vec_pt1_to_pt = Vector(self.pt1, pt)
cross = self.cross(vec_pt1_to_pt)
if cross > 0:
return -1 # counter clockwise
elif cross < 0:
return 1 # clockwise
else: # cross == 0
dot = self.dot(vec_pt1_to_pt)
if dot < 0:
return -2 # online back
else: # dot > 0
if self.abs() < vec_pt1_to_pt.abs():
return 2 # online front
else:
return 0 # on segment
def cross_point(self, other) -> Point:
d1 = abs(self.cross(Vector(self.pt1, other.pt1))) # / self.abs()
d2 = abs(self.cross(Vector(self.pt1, other.pt2))) # / self.abs()
t = d1 / (d1 + d2)
return other.pt1 + other * t
def distance_to_point(self, pt: Point) -> Union[int, float]:
vec_pt1_to_pt = Vector(self.pt1, pt)
if self.dot(vec_pt1_to_pt) <= 0:
return vec_pt1_to_pt.abs()
vec_pt2_to_pt = Vector(self.pt2, pt)
if Vector.dot(self * -1, vec_pt2_to_pt) <= 0:
return vec_pt2_to_pt.abs()
return (self.projection(pt) - pt).abs()
def segment_distance(self, other) -> Union[int, float]:
if self.is_intersected_with(other):
return 0.0
else:
return min(
self.distance_to_point(other.pt1),
self.distance_to_point(other.pt2),
other.distance_to_point(self.pt1),
other.distance_to_point(self.pt2),
)
def __repr__(self):
return f"{self.pt1},{self.pt2}"
def main():
num_query = int(input())
for i in range(num_query):
p0_x, p0_y, p1_x, p1_y, p2_x, p2_y, p3_x, p3_y = map(int, input().split())
seg_1 = Segment(Point(p0_x, p0_y), Point(p1_x, p1_y))
seg_2 = Segment(Point(p2_x, p2_y), Point(p3_x, p3_y))
print(f"{seg_1.segment_distance(seg_2):.10f}")
return
main()
| Distance
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and
p3. | [{"input": "0 0 1 0 0 1 1 1\n 0 0 1 0 2 1 1 2\n -1 0 1 0 0 1 0 -1", "output": ".0000000000\n 1.4142135624\n 0.0000000000"}] |
For each query, print the distance. The output values should be in a decimal
fraction with an error less than 0.00000001. | s443355786 | Runtime Error | p02296 | The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the
following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
4 5 1
0 1 2
0 2 3
1 2 -5
1 3 1
2 3 2
output:
INF
0
-5
-3
OR
input:
4 6 0
0 1 2
0 2 3
1 2 -5
1 3 1
2 3 2
3 1 0
output:
NEGATIVE CYCLE
"""
import sys
from math import isinf
def generate_adj_table(_v_info):
for each in _v_info:
source, target, cost = map(int, each)
init_adj_table[source][target] = cost
return init_adj_table
def bellman_ford():
distance[root] = 0
for j in range(vertices - 1):
for current, current_info in enumerate(adj_table):
for adj, cost in current_info.items():
if distance[current] + cost < distance[adj]:
distance[adj] = distance[current] + cost
for current, current_info in enumerate(adj_table):
for adj, cost in current_info.items():
if distance[current] + cost < distance[adj]:
print("NEGATIVE CYCLE")
return list()
return distance
if __name__ == "__main__":
_input = sys.stdin.readlines()
vertices, edges, root = map(int, _input[0].split())
v_info = map(lambda x: x.split(), _input[1:])
distance = [float("inf")] * vertices
init_adj_table = tuple(dict() for _ in range(vertices))
adj_table = generate_adj_table(v_info)
res = bellman_ford()
for ele in res:
if isinf(ele):
print("INF")
else:
print(ele)
| Distance
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and
p3. | [{"input": "0 0 1 0 0 1 1 1\n 0 0 1 0 2 1 1 2\n -1 0 1 0 0 1 0 -1", "output": ".0000000000\n 1.4142135624\n 0.0000000000"}] |
For each query, print the distance. The output values should be in a decimal
fraction with an error less than 0.00000001. | s491952413 | Wrong Answer | p02296 | The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the
following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3 | import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, pnt):
return math.sqrt((self.x - pnt.x) ** 2 + (self.y - pnt.y) ** 2)
class Segment:
def __init__(self, x1, y1, x2, y2):
self.p1 = Point(x1, y1)
self.p2 = Point(x2, y2)
if self.p1.x == self.p2.x:
self.a = float("inf")
self.b = None
else:
self.a = (self.p1.y - self.p2.y) / (self.p1.x - self.p2.x)
self.b = self.p1.y - self.a * self.p1.x
def is_intersect(self, seg):
a = (seg.p1.x - seg.p2.x) * (self.p1.y - seg.p1.y) + (seg.p1.y - seg.p2.y) * (
seg.p1.x - self.p1.x
)
b = (seg.p1.x - seg.p2.x) * (self.p2.y - seg.p1.y) + (seg.p1.y - seg.p2.y) * (
seg.p1.x - self.p2.x
)
c = (self.p1.x - self.p2.x) * (seg.p1.y - self.p1.y) + (
self.p1.y - self.p2.y
) * (self.p1.x - seg.p1.x)
d = (self.p1.x - self.p2.x) * (seg.p2.y - self.p1.y) + (
self.p1.y - self.p2.y
) * (self.p1.x - seg.p2.x)
e = (self.p1.x - seg.p1.x) * (self.p2.x - seg.p2.x)
f = (self.p1.x - seg.p2.x) * (self.p2.x - seg.p1.x)
g = (self.p1.y - seg.p1.y) * (self.p2.y - seg.p2.y)
h = (self.p1.y - seg.p2.y) * (self.p2.y - seg.p1.y)
return a * b <= 0 and c * d <= 0 and (e <= 0 or f <= 0) and (g <= 0 or h <= 0)
def cross_point(self, seg):
if self.is_intersect(seg) == False:
return None
if self.a == float("inf"):
return self.p1.x, seg.a * self.p1.x + seg.b
elif seg.a == float("inf"):
return seg.p1.x, self.a * seg.p1.x + self.b
else:
x = -(self.b - seg.b) / (self.a - seg.a)
y = seg.a * x + seg.b
return x, y
def distance_with_point(self, pnt):
if self.a == float("inf"):
return abs(pnt.x - self.p1.x)
dist = abs(pnt.y - self.a * pnt.x - self.b) / math.sqrt(1 + self.a**2)
a, b = pnt.distance(self.p1), pnt.distance(self.p2)
lower_bound = min(a, b)
if lower_bound < dist:
return dist
else:
return lower_bound
def distance(self, seg):
if self.is_intersect(seg):
return 0
a = self.distance_with_point(seg.p1)
b = self.distance_with_point(seg.p2)
c = seg.distance_with_point(self.p1)
d = seg.distance_with_point(self.p2)
return min(a, b, c, d)
q = int(input())
for i in range(q):
x0, y0, x1, y1, x2, y2, x3, y3 = list(map(int, input().split(" ")))
line1, line2 = Segment(x0, y0, x1, y1), Segment(x2, y2, x3, y3)
dist = line1.distance(line2)
print("%.9f" % dist)
| Distance
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and
p3. | [{"input": "0 0 1 0 0 1 1 1\n 0 0 1 0 2 1 1 2\n -1 0 1 0 0 1 0 -1", "output": ".0000000000\n 1.4142135624\n 0.0000000000"}] |
For each query, print the distance. The output values should be in a decimal
fraction with an error less than 0.00000001. | s018722494 | Wrong Answer | p02296 | The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the
following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3 | from sys import stdin
readline = stdin.readline
def main():
q = int(readline())
for i in range(q):
xy = map(int, readline().split())
p0, p1, p2, p3 = [x + y * 1j for x, y in zip(*[xy] * 2)]
print("{:.10f}".format(distance(p0, p1, p2, p3)))
def lt(a, b):
if a.real != b.real:
return a.real < b.real
return a.imag < b.imag
import itertools
def distance(p0, p1, p2, p3):
if is_intersected_ls(p0, p1, p2, p3):
return 0
p = []
for i, j in itertools.product([p0, p1], [p2, p3]):
p.append(abs(i - j))
for i, j, k in [(p0, p1, p2), (p0, p1, p3), (p2, p3, p0), (p2, p3, p1)]:
tmp = intersection_of_perpendicular(i, j, k)
if (lt(i, k) and lt(k, j)) or (lt(j, k) and lt(k, i)):
p.append(abs(tmp - k))
return min(p)
# line(p1, p2) point(p3)
def intersection_of_perpendicular(p1, p2, p3):
return p1 + (p2 - p1) * projecter(p2 - p1, p3 - p1)
def projecter(a, b):
return dot(a, b) / dot(a, a)
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def is_intersected_ls(a1, a2, b1, b2):
eps = 0
if (
max(a1.real, a2.real) < min(b1.real, b2.real)
or max(b1.real, b2.real) < min(a1.real, a2.real)
or max(a1.imag, a2.imag) < min(b1.imag, b2.imag)
or max(b1.imag, b2.imag) < min(a1.imag, a2.imag)
):
return False
return (cross(a2 - a1, b1 - a1) * cross(a2 - a1, b2 - a1) <= eps) and (
cross(b2 - b1, a1 - b1) * cross(b2 - b1, a2 - b1) <= eps
)
# http://imagingsolution.blog107.fc2.com/blog-entry-137.html
def intersection(p1, p2, p3, p4):
a1 = p4 - p2
b1 = p2 - p3
b2 = p1 - p2
s1 = cross(a1, b2) / 2
s2 = cross(a1, b1) / 2
c1 = p1 + (p3 - p1) * s1 / (s1 + s2)
return c1
def cross(a, b):
return a.real * b.imag - a.imag * b.real
main()
| Distance
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and
p3. | [{"input": "0 0 1 0 0 1 1 1\n 0 0 1 0 2 1 1 2\n -1 0 1 0 0 1 0 -1", "output": ".0000000000\n 1.4142135624\n 0.0000000000"}] |
Print the minimum number of elements that needs to be removed so that a will
be a good sequence.
* * * | s648736736 | Accepted | p03487 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N | from collections import Counter
from sys import exit, stdin
N = int(stdin.readline().rstrip())
A = Counter(int(_) for _ in stdin.readline().rstrip().split())
ans = []
for k, v in A.items():
if k - v > 0:
ans.append(v)
elif k - v < 0:
ans.append(abs(k - v))
print(sum(ans))
| Statement
You are given a sequence of positive integers of length N, a = (a_1, a_2, ...,
a_N). Your objective is to remove some of the elements in a so that a will be
a **good sequence**.
Here, an sequence b is a **good sequence** when the following condition holds
true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are
good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be
a good sequence. | [{"input": "4\n 3 3 3 3", "output": "1\n \n\nWe can, for example, remove one occurrence of 3. Then, (3, 3, 3) is a good\nsequence.\n\n* * *"}, {"input": "5\n 2 4 1 4 2", "output": "2\n \n\nWe can, for example, remove two occurrences of 4. Then, (2, 1, 2) is a good\nsequence.\n\n* * *"}, {"input": "6\n 1 2 2 3 3 3", "output": "0\n \n\n* * *"}, {"input": "1\n 1000000000", "output": "1\n \n\nRemove one occurrence of 10^9. Then, () is a good sequence.\n\n* * *"}, {"input": "8\n 2 7 1 8 2 8 1 8", "output": "5"}] |
Print the minimum number of elements that needs to be removed so that a will
be a good sequence.
* * * | s533456125 | Accepted | p03487 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N | from sys import stdin
import collections
n = int(stdin.readline().rstrip())
li = list(map(int, stdin.readline().rstrip().split()))
c = collections.Counter(li)
count = c.items()
point = 0
for i in count:
if i[0] < i[1]:
point += i[1] - i[0]
elif i[0] > i[1]:
point += i[1]
print(point)
| Statement
You are given a sequence of positive integers of length N, a = (a_1, a_2, ...,
a_N). Your objective is to remove some of the elements in a so that a will be
a **good sequence**.
Here, an sequence b is a **good sequence** when the following condition holds
true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are
good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be
a good sequence. | [{"input": "4\n 3 3 3 3", "output": "1\n \n\nWe can, for example, remove one occurrence of 3. Then, (3, 3, 3) is a good\nsequence.\n\n* * *"}, {"input": "5\n 2 4 1 4 2", "output": "2\n \n\nWe can, for example, remove two occurrences of 4. Then, (2, 1, 2) is a good\nsequence.\n\n* * *"}, {"input": "6\n 1 2 2 3 3 3", "output": "0\n \n\n* * *"}, {"input": "1\n 1000000000", "output": "1\n \n\nRemove one occurrence of 10^9. Then, () is a good sequence.\n\n* * *"}, {"input": "8\n 2 7 1 8 2 8 1 8", "output": "5"}] |
Print the minimum number of elements that needs to be removed so that a will
be a good sequence.
* * * | s624459021 | Accepted | p03487 | Input is given from Standard Input in the following format:
N
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
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):
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 search(self, s, g):
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),
]
def solve():
n = getN()
nums = getList()
c = Counter(nums)
ans = 0
for k, v in c.items():
if v < k:
ans += v
elif v > k:
ans += v - k
print(ans)
return
def main():
n = getN()
for _ in range(n):
solve()
return
if __name__ == "__main__":
# main()
solve()
| Statement
You are given a sequence of positive integers of length N, a = (a_1, a_2, ...,
a_N). Your objective is to remove some of the elements in a so that a will be
a **good sequence**.
Here, an sequence b is a **good sequence** when the following condition holds
true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are
good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be
a good sequence. | [{"input": "4\n 3 3 3 3", "output": "1\n \n\nWe can, for example, remove one occurrence of 3. Then, (3, 3, 3) is a good\nsequence.\n\n* * *"}, {"input": "5\n 2 4 1 4 2", "output": "2\n \n\nWe can, for example, remove two occurrences of 4. Then, (2, 1, 2) is a good\nsequence.\n\n* * *"}, {"input": "6\n 1 2 2 3 3 3", "output": "0\n \n\n* * *"}, {"input": "1\n 1000000000", "output": "1\n \n\nRemove one occurrence of 10^9. Then, () is a good sequence.\n\n* * *"}, {"input": "8\n 2 7 1 8 2 8 1 8", "output": "5"}] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.