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 value displayed in the board after N operations.
* * * | s799668976 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | n=int(input())
k=int(input())
now=1
for i in range(n):
if now*2 >=k
now+=k
else:
now*=2
print(now)
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s808609282 | Wrong Answer | p03564 | Input is given from Standard Input in the following format:
N
K | R = int(input())
G = int(input())
print(2 * G - R)
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s296527913 | Accepted | p03564 | Input is given from Standard Input in the following format:
N
K | # ABC 076
def getInt():
return int(input())
def zeros(n):
return [0] * n
def genBit(n): # n個の0/1のリストを生成 [0]から変化
blist = zeros(n)
for i in range(2**n):
for k in range(n):
blist[k] = i % 2
i //= 2
yield blist
def db(x):
global debug
if debug:
print(x)
debug = False
N = getInt()
K = getInt()
minD = 0
for b in genBit(N):
d = 1
for i in range(N):
if b[i] == 0:
d *= 2
if b[i] == 1:
d += K
if minD == 0:
minD = d
elif d < minD:
minD = d
db(minD)
print(minD)
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s731179804 | Wrong Answer | p03564 | Input is given from Standard Input in the following format:
N
K | S = input()
if S == "a":
print(-1)
else:
print("a")
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s832325200 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | n=int(input())
k=int(input())
a=1
for i range(n):
if a >=k:
a=+k
else:
a=2*a
print(a) | Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s946468198 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | n=int(input())
k=int(input())
i=0
while i < n && 2**i<=k:
i+=1
print(2**i+k*(n-i))
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s345741372 | Accepted | p03564 | Input is given from Standard Input in the following format:
N
K | import sys
stdin = sys.stdin
sys.setrecursionlimit(10**5)
def li():
return map(int, stdin.readline().split())
def li_():
return map(lambda x: int(x) - 1, stdin.readline().split())
def lf():
return map(float, stdin.readline().split())
def ls():
return stdin.readline().split()
def ns():
return stdin.readline().rstrip()
def lc():
return list(ns())
def ni():
return int(stdin.readline())
def nf():
return float(stdin.readline())
n = ni()
k = ni()
res = 1
for _ in range(n):
res = min(res + k, 2 * res)
print(res)
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s493538483 | Wrong Answer | p03564 | Input is given from Standard Input in the following format:
N
K | N = int(input())
K = int(input())
A = 1 + (N * K)
B = 1 * 2 + (N - 1) * K
C = 1 * 2 * 2 + ((N - 2) * K)
D = 1 * 2 * 2 * 2 + (N - 3) * K
E = 1 * 2 * 2 * 2 * 2 + (N - 4) * K
F = 1 * 2 * 2 * 2 * 2 * 2 + (N - 5) * K
if 0 < A < B:
print(A)
elif 0 < B < C:
print(B)
elif 0 < C < D:
print(C)
elif 0 < D < E:
print(D)
elif 0 < E < F:
print(E)
elif 0 < F:
print(F)
else:
print(A)
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s608110615 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | def B_Addition_and_Multiplication(N, K):
if N==1:
return 2
multiply = 0 # 掛け算する回数
add = 0 # 足し算する回数
tmp = 1
while tmp < K:
tmp *= 2
multiply += 1
add = N - multiply
ans = pow(2, multiply) + K * add
return ans
N = int(input())
K = int(input())
print(B_Addition_and_Multiplication(N, K)) | Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s194683645 | Wrong Answer | p03564 | Input is given from Standard Input in the following format:
N
K | n = int(input())
k = int(input())
if 1 <= k < 2:
print(k * n)
elif 2 <= k < 4:
print(4 + k * (n - 2))
elif 4 <= k < 8:
print(8 + k * (n - 3))
elif 8 <= k <= 10:
print(16 + k * (n - 4))
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s028701209 | Wrong Answer | p03564 | Input is given from Standard Input in the following format:
N
K | N = int(input())
K = int(input())
C = N * K
if K == 0:
B = 0
elif K == 1 or 2:
B = 1
elif K == 3:
B = 2
elif K == 4 or 5 or 6 or 7 or 8:
B = 3
elif K == 9 or 10:
B = 4
p = 0
i = 1
while p < B:
i = i * 2
p = p + 1
A = N - B
print(i + A * K)
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s698524727 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | n = int(input())
k = int(input())
a = 1
for x range(n):
if a * 2 > a + k:
a + k
else :
a * 2
print(a) | Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s695792249 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | N = int(input())
K = int(input())
now = 1
for i in range(N):
if now >= K:
now *= 2
else:
now+=K
print(now)
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s698997963 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | N = int(input())
K = int(input())
ans = 1
for i in range(N):
ans = min(ans * 2 , ans + K)
print(an | Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s738681218 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | N = int(input())
K = int(input())
a = 1
for i in range(N):
if a < K:
a *= 2:
else:
a += K
print(a) | Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s164329686 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | n=int(input())
k=int(input())
a=1
for i in range (1:n):
if a < k:
a=2*a
else:
a=a+k
print(a) | Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s945851509 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | N = int(input())
K = int(input())
ans = 1
for i in range(N)
if ans < K:
ans *= 2
else:
ans += K
print(ans) | Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s725877777 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | N = int(input())
K = int(input())
now = 1
for i in range(N):
if(now>=K):
now*=2
else:
now+=K
print(now) | Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s587946945 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | n= int(input())
k = int(input())
z = 1
for i in range(n):
if z < k:
z = 2Z
else:
z = z+k
print(z) | Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the minimum possible value displayed in the board after N operations.
* * * | s456626195 | Runtime Error | p03564 | Input is given from Standard Input in the following format:
N
K | N = int(input())
K = int(input())
now = 1
for i in range(N):
if(now >= K):
now *= 2
else:
now+=K
print(now)
| Statement
Square1001 has seen an electric bulletin board displaying the integer 1. He
can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the
minimum possible value displayed in the board after N operations. | [{"input": "4\n 3", "output": "10\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 7 \u2192 10.\n\n* * *"}, {"input": "10\n 10", "output": "76\n \n\nThe value will be minimized when the operations are performed in the following\norder: A, A, A, A, B, B, B, B, B, B. \nIn this case, the value will change as follows: 1 \u2192 2 \u2192 4 \u2192 8 \u2192 16 \u2192 26 \u2192 36 \u2192\n46 \u2192 56 \u2192 66 \u2192 76.\n\nBy the way, this contest is AtCoder Beginner Contest 076."}] |
Print the number of the possible sequences Takahashi may have after repeating
the procedure 2N times, modulo 998244353.
* * * | s784600685 | Runtime Error | p03134 | Input is given from Standard Input in the following format:
S | #!/usr/bin/env python3
import sys
MOD = 998244353 # type: int
def comb(n, k):
if k > n:
return 0
k = min(k, n - k)
ret = 1
for i in range(k):
ret *= n - i
ret //= i + 1
return ret
def solve(S: str):
n = len(S)
b_total = 0
b_counts = []
for c in S:
b_total += ord(c) - ord("0")
b_counts.append(b_total)
dp = [[0] * (b_total + 1) for _ in range(2 * n + 1)]
dp[0][0] = 1
for i in range(n):
for j in range(min(i + 1, b_total + 1)):
if b_counts[i] >= j + 1:
dp[i + 1][j + 1] += dp[i][j]
if (i + 1) * 2 - b_counts[i] >= (i + 1) - j:
dp[i + 1][j] += dp[i][j]
# print(dp[i])
# print(dp[n])
comb = [0] * (n + 1)
comb[0] = 1
for i in range(n):
comb[i + 1] = comb[i] * (n - i) // (i + 1)
ret = 0
for b, val in enumerate(dp[n]):
# ret += val * comb(n, b_total - b)
ret += val * comb[b_total - b]
print(ret % MOD)
return
##dp[0][0] = 1
##for i in range(2 * n):
## for j in range(min(i + 1, b_total + 1)):
## b_max = b_counts[i] if i < n else b_total
## r_max = (i + 1) * 2 - b_max if i < n else 2 * n - b_total
## if b_max >= j + 1:
## dp[i + 1][j + 1] += dp[i][j]
## if r_max >= (i + 1) - j:
## dp[i + 1][j] += dp[i][j]
##ret = sum(dp[2 * n])
##print(ret % MOD)
##return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
S = str(next(tokens))
solve(S)
if __name__ == "__main__":
main()
| Statement
There are N Snukes lining up in a row. You are given a string S of length N.
The i-th Snuke from the front has two red balls if the i-th character in S is
`0`; one red ball and one blue ball if the i-th character in S is `1`; two
blue balls if the i-th character in S is `2`.
Takahashi has a sequence that is initially empty. Find the number of the
possible sequences he may have after repeating the following procedure 2N
times, modulo 998244353:
* Each Snuke who has one or more balls simultaneously chooses one of his balls and hand it to the Snuke in front of him, or hand it to Takahashi if he is the first Snuke in the row.
* Takahashi receives the ball and put it to the end of his sequence. | [{"input": "02", "output": "3\n \n\nThere are three sequences that Takahashi may have: `rrbb`, `rbrb` and `rbbr`,\nwhere `r` and `b` stand for red and blue balls, respectively.\n\n* * *"}, {"input": "1210", "output": "55\n \n\n* * *"}, {"input": "12001021211100201020", "output": "543589959"}] |
Print the number of the possible sequences Takahashi may have after repeating
the procedure 2N times, modulo 998244353.
* * * | s295605941 | Wrong Answer | p03134 | Input is given from Standard Input in the following format:
S | mod = 998244353
s = list(map(int, list(input())))
n = len(s)
dp = [[0] * (sum(s) + 1) for _ in range(2 * n + 1)]
dp[0][0] = 1
curr = curb = 0
for i in range(2 * n):
if i < n:
curb += s[i]
curr += 2 - s[i]
for j in range(min(i, curb) + 1):
if dp[i][j]:
dp[i][j] %= mod
if i - j < curr:
dp[i + 1][j] += dp[i][j]
if j < curb:
dp[i + 1][j + 1] += dp[i][j]
print(dp[2 * n][curb])
| Statement
There are N Snukes lining up in a row. You are given a string S of length N.
The i-th Snuke from the front has two red balls if the i-th character in S is
`0`; one red ball and one blue ball if the i-th character in S is `1`; two
blue balls if the i-th character in S is `2`.
Takahashi has a sequence that is initially empty. Find the number of the
possible sequences he may have after repeating the following procedure 2N
times, modulo 998244353:
* Each Snuke who has one or more balls simultaneously chooses one of his balls and hand it to the Snuke in front of him, or hand it to Takahashi if he is the first Snuke in the row.
* Takahashi receives the ball and put it to the end of his sequence. | [{"input": "02", "output": "3\n \n\nThere are three sequences that Takahashi may have: `rrbb`, `rbrb` and `rbbr`,\nwhere `r` and `b` stand for red and blue balls, respectively.\n\n* * *"}, {"input": "1210", "output": "55\n \n\n* * *"}, {"input": "12001021211100201020", "output": "543589959"}] |
For each dataset, output the number of people whose incomes are less than or
equal to the average. | s426270832 | Runtime Error | p01109 | The input consists of multiple datasets, each in the following format.
> _n_
> _a_ 1 _a_ 2 ... _a n_
A dataset consists of two lines. In the first line, the number of people _n_
is given. _n_ is an integer satisfying 2 ≤ _n_ ≤ 10 000\. In the second line,
incomes of _n_ people are given. _a i_ (1 ≤ _i_ ≤ _n_) is the income of the
_i_ -th person. This value is an integer greater than or equal to 1 and less
than or equal to 100 000\.
The end of the input is indicated by a line containing a zero. The sum of _n_
's of all the datasets does not exceed 50 000\. | n = int(input())
a = [int(i) for i in input().split]
total = 0
for i in a:
total += i
hei = total / n
count = 0
for i in a:
if i <= hei:
count += 1
print(count)
| Income Inequality
We often compute the average as the first step in processing statistical data.
Yes, the average is a good tendency measure of data, but it is not always the
best. In some cases, the average may hinder the understanding of the data.
For example, consider the national income of a country. As the term _income
inequality_ suggests, a small number of people earn a good portion of the
gross national income in many countries. In such cases, the average income
computes much higher than the income of the vast majority. It is not
appropriate to regard the average as the income of typical people.
Let us observe the above-mentioned phenomenon in some concrete data. Incomes
of _n_ people, _a_ 1, ... , _a n_, are given. You are asked to write a program
that reports the number of people whose incomes are less than or equal to the
average (_a_ 1 \+ ... + _a n_) / _n_. | [{"input": "15 15 15 15 15 15 15\n 4\n 10 20 30 60\n 10\n 1 1 1 1 1 1 1 1 1 100\n 7\n 90 90 90 90 90 90 10\n 7\n 2 7 1 8 2 8 4\n 0", "output": "3\n 9\n 1\n 4"}] |
For each dataset, output the number of people whose incomes are less than or
equal to the average. | s356434831 | Accepted | p01109 | The input consists of multiple datasets, each in the following format.
> _n_
> _a_ 1 _a_ 2 ... _a n_
A dataset consists of two lines. In the first line, the number of people _n_
is given. _n_ is an integer satisfying 2 ≤ _n_ ≤ 10 000\. In the second line,
incomes of _n_ people are given. _a i_ (1 ≤ _i_ ≤ _n_) is the income of the
_i_ -th person. This value is an integer greater than or equal to 1 and less
than or equal to 100 000\.
The end of the input is indicated by a line containing a zero. The sum of _n_
's of all the datasets does not exceed 50 000\. | while True:
n = input()
if n == "0":
break
elif (int)(n) > 50000:
continue
hairetu = input()
tarou = hairetu.split(" ")
avg = 0
for i in range(0, (int)(n)):
avg = avg + (int)(tarou[i])
avg = avg / (int)(n)
cdnt = 0
for j in range(0, (int)(n)):
if (int)(tarou[j]) <= (int)(avg):
cdnt = cdnt + 1
print(cdnt)
| Income Inequality
We often compute the average as the first step in processing statistical data.
Yes, the average is a good tendency measure of data, but it is not always the
best. In some cases, the average may hinder the understanding of the data.
For example, consider the national income of a country. As the term _income
inequality_ suggests, a small number of people earn a good portion of the
gross national income in many countries. In such cases, the average income
computes much higher than the income of the vast majority. It is not
appropriate to regard the average as the income of typical people.
Let us observe the above-mentioned phenomenon in some concrete data. Incomes
of _n_ people, _a_ 1, ... , _a n_, are given. You are asked to write a program
that reports the number of people whose incomes are less than or equal to the
average (_a_ 1 \+ ... + _a n_) / _n_. | [{"input": "15 15 15 15 15 15 15\n 4\n 10 20 30 60\n 10\n 1 1 1 1 1 1 1 1 1 100\n 7\n 90 90 90 90 90 90 10\n 7\n 2 7 1 8 2 8 4\n 0", "output": "3\n 9\n 1\n 4"}] |
For each dataset, output the number of people whose incomes are less than or
equal to the average. | s059623269 | Accepted | p01109 | The input consists of multiple datasets, each in the following format.
> _n_
> _a_ 1 _a_ 2 ... _a n_
A dataset consists of two lines. In the first line, the number of people _n_
is given. _n_ is an integer satisfying 2 ≤ _n_ ≤ 10 000\. In the second line,
incomes of _n_ people are given. _a i_ (1 ≤ _i_ ≤ _n_) is the income of the
_i_ -th person. This value is an integer greater than or equal to 1 and less
than or equal to 100 000\.
The end of the input is indicated by a line containing a zero. The sum of _n_
's of all the datasets does not exceed 50 000\. | import statistics
def get_data():
data = int(input())
return data
def get_data_list():
data_list = input().split()
for i, v in enumerate(data_list):
data_list[i] = int(v)
return data_list
def count_num_under_average(list_num, reverse_sorted_num_list, average_num):
count = list_num
for v in reverse_sorted_income_list:
if v > average_num:
count -= 1
else:
break
return count
if __name__ == "__main__":
while True:
population = get_data()
if population == 0:
break
income_list = get_data_list()
reverse_sorted_income_list = sorted(income_list, reverse=True)
average_income = statistics.mean(reverse_sorted_income_list)
count = count_num_under_average(
population, reverse_sorted_income_list, average_income
)
print(count)
| Income Inequality
We often compute the average as the first step in processing statistical data.
Yes, the average is a good tendency measure of data, but it is not always the
best. In some cases, the average may hinder the understanding of the data.
For example, consider the national income of a country. As the term _income
inequality_ suggests, a small number of people earn a good portion of the
gross national income in many countries. In such cases, the average income
computes much higher than the income of the vast majority. It is not
appropriate to regard the average as the income of typical people.
Let us observe the above-mentioned phenomenon in some concrete data. Incomes
of _n_ people, _a_ 1, ... , _a n_, are given. You are asked to write a program
that reports the number of people whose incomes are less than or equal to the
average (_a_ 1 \+ ... + _a n_) / _n_. | [{"input": "15 15 15 15 15 15 15\n 4\n 10 20 30 60\n 10\n 1 1 1 1 1 1 1 1 1 100\n 7\n 90 90 90 90 90 90 10\n 7\n 2 7 1 8 2 8 4\n 0", "output": "3\n 9\n 1\n 4"}] |
For each specification, your program should print an MCXI-string in a line.
Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in
the specification. No other characters should appear in the output. | s377148427 | Accepted | p00718 | The input is as follows. The first line contains a positive integer _n_ (<=
500) that indicates the number of the following lines. The _k_ +1 th line is
the specification of the _k_ th computation (_k_ =1, ..., _n_).
> _n_
> _specification_ 1
> _specification_ 2
> ...
> _specification_ _n_
>
Each specification is described in a line:
> _MCXI-string_ 1 _MCXI-string_ 2
The two MCXI-strings are separated by a space.
You may assume that the sum of the two MCXI-values of the two MCXI-strings in
each specification is less than or equal to 9999. | def m_i(l):
stack = 1
ans = 0
l = list(l)
for i in l:
if i == "m":
ans += stack * 1000
stack = 1
elif i == "c":
ans += stack * 100
stack = 1
elif i == "x":
ans += stack * 10
stack = 1
elif i == "i":
ans += stack
stack = 1
else:
stack = int(i)
return ans
def i_m(l):
ans = []
a = l // 1000
if a == 1:
ans.append("m")
elif a != 0:
ans.append(str(a))
ans.append("m")
l -= a * 1000
a = l // 100
if a == 1:
ans.append("c")
elif a != 0:
ans.append(str(a))
ans.append("c")
l -= a * 100
a = l // 10
if a == 1:
ans.append("x")
elif a != 0:
ans.append(str(a))
ans.append("x")
a = l - a * 10
if a == 1:
ans.append("i")
elif a != 0:
ans.append(str(a))
ans.append("i")
ans = "".join(ans)
return ans
n = int(input())
for i in range(n):
a, b = input().split()
ans = m_i(a) + m_i(b)
print(i_m(ans))
| C: Numeral System
Prof. Hachioji has devised a new numeral system of integral numbers with four
lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5",
"6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1,
respectively, and the digits "2", ...,"9" correspond to 2, ..., 9,
respectively. This system has nothing to do with the Roman numeral system.
For example, character strings
> "5m2c3x4i", "m2c4i" and "5m2c3x"
correspond to the integral numbers 5234 (=5*1000+2*100+3*10+4*1), 1204
(=1000+2*100+4*1), and 5230 (=5*1000+2*100+3*10), respectively. The parts of
strings in the above example, "5m", "2c", "3x" and "4i" represent 5000
(=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1), respectively.
Each of the letters "m", "c", "x" and "i" may be prefixed by one of the digits
"2", "3", ..., "9". In that case, the prefix digit and the letter are regarded
as a pair. A pair that consists of a prefix digit and a letter corresponds to
an integer that is equal to the original value of the letter multiplied by the
value of the prefix digit.
For each letter "m", "c", "x" and "i", the number of its occurrence in a
string is at most one. When it has a prefix digit, it should appear together
with the prefix digit. The letters "m", "c", "x" and "i" must appear in this
order, from left to right. Moreover, when a digit exists in a string, it
should appear as the prefix digit of the following letter. Each letter may be
omitted in a string, but the whole string must not be empty. A string made in
this manner is called an _MCXI-string_.
An MCXI-string corresponds to a positive integer that is the sum of the values
of the letters and those of the pairs contained in it as mentioned above. The
positive integer corresponding to an MCXI-string is called its MCXI-value.
Moreover, given an integer from 1 to 9999, there is a unique MCXI-string whose
MCXI-value is equal to the given integer. For example, the MCXI-value of an
MCXI-string "m2c4i" is 1204 that is equal to `1000 + 2*100 + 4*1`. There are
no MCXI-strings but "m2c4i" that correspond to 1204. Note that strings
"1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are not valid MCXI-strings. The
reasons are use of "1", multiple occurrences of "c", use of "0", and the wrong
order of "c" and "m", respectively.
Your job is to write a program for Prof. Hachioji that reads two MCXI-strings,
computes the sum of their MCXI-values, and prints the MCXI-string
corresponding to the result. | [{"input": "xi x9i\n i 9i\n c2x2i 4c8x8i\n m2ci 4m7c9x8i\n 9c9x9i i\n i 9m9c9x8i\n m i\n i m\n m9i i\n 9m8c7xi c2x8i", "output": "x\n x\n 6cx\n 5m9c9x9i\n m\n 9m9c9x9i\n mi\n mi\n mx\n 9m9c9x9i"}] |
For each specification, your program should print an MCXI-string in a line.
Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in
the specification. No other characters should appear in the output. | s966314704 | Wrong Answer | p00718 | The input is as follows. The first line contains a positive integer _n_ (<=
500) that indicates the number of the following lines. The _k_ +1 th line is
the specification of the _k_ th computation (_k_ =1, ..., _n_).
> _n_
> _specification_ 1
> _specification_ 2
> ...
> _specification_ _n_
>
Each specification is described in a line:
> _MCXI-string_ 1 _MCXI-string_ 2
The two MCXI-strings are separated by a space.
You may assume that the sum of the two MCXI-values of the two MCXI-strings in
each specification is less than or equal to 9999. | n = int(input())
for i in range(n):
s0, s1 = map(str, input().split())
ans = ""
ans0 = 0
ans1 = 0
ans2 = 0
p = 1
for j in range(len(s0)):
if s0[j] != "m" and s0[j] != "c" and s0[j] != "x" and s0[j] != "i":
p = int(s0[j])
continue
if s0[j] == "m":
ans0 += p * 1000
p = 1
if s0[j] == "c":
ans0 += p * 100
p = 1
if s0[j] == "x":
ans0 += p * 10
p = 1
if s0[j] == "i":
ans0 += p * 1
p = 1
for k in range(len(s1)):
if s1[k] != "m" and s1[k] != "c" and s1[k] != "x" and s1[k] != "i":
p = int(s1[k])
continue
if s1[k] == "m":
ans1 += p * 1000
p = 1
if s1[k] == "c":
ans1 += p * 100
p = 1
if s1[k] == "x":
ans1 += p * 10
p = 1
if s1[k] == "i":
ans1 += p * 1
p = 1
print(ans0)
print(ans1)
ans2 = ans0 + ans1
while ans2 > 0:
if ans2 >= 1000:
sans2 = str(ans2)
if sans2[0] == "1":
ans = ans + "m"
else:
ans = ans + sans2[0] + "m"
ans2 = int(sans2[1:])
continue
if ans2 >= 100:
sans2 = str(ans2)
if sans2[0] == "1":
ans = ans + "c"
else:
ans = ans + sans2[0] + "c"
ans2 = int(sans2[1:])
continue
if ans2 >= 10:
sans2 = str(ans2)
if sans2[0] == "1":
ans = ans + "x"
else:
ans = ans + sans2[0] + "x"
ans2 = int(sans2[1:])
continue
if ans2 >= 1:
sans2 = str(ans2)
if sans2[0] == "1":
ans = ans + "i"
else:
ans = ans + sans2[0] + "i"
break
print(ans)
| C: Numeral System
Prof. Hachioji has devised a new numeral system of integral numbers with four
lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5",
"6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1,
respectively, and the digits "2", ...,"9" correspond to 2, ..., 9,
respectively. This system has nothing to do with the Roman numeral system.
For example, character strings
> "5m2c3x4i", "m2c4i" and "5m2c3x"
correspond to the integral numbers 5234 (=5*1000+2*100+3*10+4*1), 1204
(=1000+2*100+4*1), and 5230 (=5*1000+2*100+3*10), respectively. The parts of
strings in the above example, "5m", "2c", "3x" and "4i" represent 5000
(=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1), respectively.
Each of the letters "m", "c", "x" and "i" may be prefixed by one of the digits
"2", "3", ..., "9". In that case, the prefix digit and the letter are regarded
as a pair. A pair that consists of a prefix digit and a letter corresponds to
an integer that is equal to the original value of the letter multiplied by the
value of the prefix digit.
For each letter "m", "c", "x" and "i", the number of its occurrence in a
string is at most one. When it has a prefix digit, it should appear together
with the prefix digit. The letters "m", "c", "x" and "i" must appear in this
order, from left to right. Moreover, when a digit exists in a string, it
should appear as the prefix digit of the following letter. Each letter may be
omitted in a string, but the whole string must not be empty. A string made in
this manner is called an _MCXI-string_.
An MCXI-string corresponds to a positive integer that is the sum of the values
of the letters and those of the pairs contained in it as mentioned above. The
positive integer corresponding to an MCXI-string is called its MCXI-value.
Moreover, given an integer from 1 to 9999, there is a unique MCXI-string whose
MCXI-value is equal to the given integer. For example, the MCXI-value of an
MCXI-string "m2c4i" is 1204 that is equal to `1000 + 2*100 + 4*1`. There are
no MCXI-strings but "m2c4i" that correspond to 1204. Note that strings
"1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are not valid MCXI-strings. The
reasons are use of "1", multiple occurrences of "c", use of "0", and the wrong
order of "c" and "m", respectively.
Your job is to write a program for Prof. Hachioji that reads two MCXI-strings,
computes the sum of their MCXI-values, and prints the MCXI-string
corresponding to the result. | [{"input": "xi x9i\n i 9i\n c2x2i 4c8x8i\n m2ci 4m7c9x8i\n 9c9x9i i\n i 9m9c9x8i\n m i\n i m\n m9i i\n 9m8c7xi c2x8i", "output": "x\n x\n 6cx\n 5m9c9x9i\n m\n 9m9c9x9i\n mi\n mi\n mx\n 9m9c9x9i"}] |
For each specification, your program should print an MCXI-string in a line.
Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in
the specification. No other characters should appear in the output. | s565107936 | Accepted | p00718 | The input is as follows. The first line contains a positive integer _n_ (<=
500) that indicates the number of the following lines. The _k_ +1 th line is
the specification of the _k_ th computation (_k_ =1, ..., _n_).
> _n_
> _specification_ 1
> _specification_ 2
> ...
> _specification_ _n_
>
Each specification is described in a line:
> _MCXI-string_ 1 _MCXI-string_ 2
The two MCXI-strings are separated by a space.
You may assume that the sum of the two MCXI-values of the two MCXI-strings in
each specification is less than or equal to 9999. | import re
for i in range(int(input())):
s = input().replace(" ", "")
print(
"".join(
re.sub(
r"0\w",
"",
"".join(
[
i + j
for (i, j) in zip(
str(
10000
+ eval(
"+".join(
[
i[0]
+ {
"m": "*1000",
"c": "*100",
"x": "*10",
"i": "",
}[i[1]]
for i in [
"1" + i
for i in "".join(re.split(r"\d\w", s))
]
+ re.findall(r"\d\w", s)
]
)
)
)[1:],
list("mcxi"),
)
]
),
).split("1")
)
)
| C: Numeral System
Prof. Hachioji has devised a new numeral system of integral numbers with four
lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5",
"6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1,
respectively, and the digits "2", ...,"9" correspond to 2, ..., 9,
respectively. This system has nothing to do with the Roman numeral system.
For example, character strings
> "5m2c3x4i", "m2c4i" and "5m2c3x"
correspond to the integral numbers 5234 (=5*1000+2*100+3*10+4*1), 1204
(=1000+2*100+4*1), and 5230 (=5*1000+2*100+3*10), respectively. The parts of
strings in the above example, "5m", "2c", "3x" and "4i" represent 5000
(=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1), respectively.
Each of the letters "m", "c", "x" and "i" may be prefixed by one of the digits
"2", "3", ..., "9". In that case, the prefix digit and the letter are regarded
as a pair. A pair that consists of a prefix digit and a letter corresponds to
an integer that is equal to the original value of the letter multiplied by the
value of the prefix digit.
For each letter "m", "c", "x" and "i", the number of its occurrence in a
string is at most one. When it has a prefix digit, it should appear together
with the prefix digit. The letters "m", "c", "x" and "i" must appear in this
order, from left to right. Moreover, when a digit exists in a string, it
should appear as the prefix digit of the following letter. Each letter may be
omitted in a string, but the whole string must not be empty. A string made in
this manner is called an _MCXI-string_.
An MCXI-string corresponds to a positive integer that is the sum of the values
of the letters and those of the pairs contained in it as mentioned above. The
positive integer corresponding to an MCXI-string is called its MCXI-value.
Moreover, given an integer from 1 to 9999, there is a unique MCXI-string whose
MCXI-value is equal to the given integer. For example, the MCXI-value of an
MCXI-string "m2c4i" is 1204 that is equal to `1000 + 2*100 + 4*1`. There are
no MCXI-strings but "m2c4i" that correspond to 1204. Note that strings
"1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are not valid MCXI-strings. The
reasons are use of "1", multiple occurrences of "c", use of "0", and the wrong
order of "c" and "m", respectively.
Your job is to write a program for Prof. Hachioji that reads two MCXI-strings,
computes the sum of their MCXI-values, and prints the MCXI-string
corresponding to the result. | [{"input": "xi x9i\n i 9i\n c2x2i 4c8x8i\n m2ci 4m7c9x8i\n 9c9x9i i\n i 9m9c9x8i\n m i\n i m\n m9i i\n 9m8c7xi c2x8i", "output": "x\n x\n 6cx\n 5m9c9x9i\n m\n 9m9c9x9i\n mi\n mi\n mx\n 9m9c9x9i"}] |
For each specification, your program should print an MCXI-string in a line.
Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in
the specification. No other characters should appear in the output. | s814409898 | Accepted | p00718 | The input is as follows. The first line contains a positive integer _n_ (<=
500) that indicates the number of the following lines. The _k_ +1 th line is
the specification of the _k_ th computation (_k_ =1, ..., _n_).
> _n_
> _specification_ 1
> _specification_ 2
> ...
> _specification_ _n_
>
Each specification is described in a line:
> _MCXI-string_ 1 _MCXI-string_ 2
The two MCXI-strings are separated by a space.
You may assume that the sum of the two MCXI-values of the two MCXI-strings in
each specification is less than or equal to 9999. | import re
[
print(
re.sub(
r"0.",
"",
"".join(
[
str(
10000
+ sum(
[
eval(i[0] + "0" * "ixcm".find(i[1]))
for i in [
"1" + i for i in "".join(re.split(r"\d\w", s))
]
+ re.findall(r"\d\w", s)
]
)
)[i]
+ "1mcxi"[i]
for i in range(5)
]
).replace("1", ""),
)
)
for s in [input().replace(" ", "") for i in range(int(input()))]
]
| C: Numeral System
Prof. Hachioji has devised a new numeral system of integral numbers with four
lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5",
"6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1,
respectively, and the digits "2", ...,"9" correspond to 2, ..., 9,
respectively. This system has nothing to do with the Roman numeral system.
For example, character strings
> "5m2c3x4i", "m2c4i" and "5m2c3x"
correspond to the integral numbers 5234 (=5*1000+2*100+3*10+4*1), 1204
(=1000+2*100+4*1), and 5230 (=5*1000+2*100+3*10), respectively. The parts of
strings in the above example, "5m", "2c", "3x" and "4i" represent 5000
(=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1), respectively.
Each of the letters "m", "c", "x" and "i" may be prefixed by one of the digits
"2", "3", ..., "9". In that case, the prefix digit and the letter are regarded
as a pair. A pair that consists of a prefix digit and a letter corresponds to
an integer that is equal to the original value of the letter multiplied by the
value of the prefix digit.
For each letter "m", "c", "x" and "i", the number of its occurrence in a
string is at most one. When it has a prefix digit, it should appear together
with the prefix digit. The letters "m", "c", "x" and "i" must appear in this
order, from left to right. Moreover, when a digit exists in a string, it
should appear as the prefix digit of the following letter. Each letter may be
omitted in a string, but the whole string must not be empty. A string made in
this manner is called an _MCXI-string_.
An MCXI-string corresponds to a positive integer that is the sum of the values
of the letters and those of the pairs contained in it as mentioned above. The
positive integer corresponding to an MCXI-string is called its MCXI-value.
Moreover, given an integer from 1 to 9999, there is a unique MCXI-string whose
MCXI-value is equal to the given integer. For example, the MCXI-value of an
MCXI-string "m2c4i" is 1204 that is equal to `1000 + 2*100 + 4*1`. There are
no MCXI-strings but "m2c4i" that correspond to 1204. Note that strings
"1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are not valid MCXI-strings. The
reasons are use of "1", multiple occurrences of "c", use of "0", and the wrong
order of "c" and "m", respectively.
Your job is to write a program for Prof. Hachioji that reads two MCXI-strings,
computes the sum of their MCXI-values, and prints the MCXI-string
corresponding to the result. | [{"input": "xi x9i\n i 9i\n c2x2i 4c8x8i\n m2ci 4m7c9x8i\n 9c9x9i i\n i 9m9c9x8i\n m i\n i m\n m9i i\n 9m8c7xi c2x8i", "output": "x\n x\n 6cx\n 5m9c9x9i\n m\n 9m9c9x9i\n mi\n mi\n mx\n 9m9c9x9i"}] |
For each specification, your program should print an MCXI-string in a line.
Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in
the specification. No other characters should appear in the output. | s246534377 | Wrong Answer | p00718 | The input is as follows. The first line contains a positive integer _n_ (<=
500) that indicates the number of the following lines. The _k_ +1 th line is
the specification of the _k_ th computation (_k_ =1, ..., _n_).
> _n_
> _specification_ 1
> _specification_ 2
> ...
> _specification_ _n_
>
Each specification is described in a line:
> _MCXI-string_ 1 _MCXI-string_ 2
The two MCXI-strings are separated by a space.
You may assume that the sum of the two MCXI-values of the two MCXI-strings in
each specification is less than or equal to 9999. | trial = int(input())
numlist = [str(n) for n in range(2, 10)]
cases = []
for t in range(trial):
cases.append(input().split(" "))
print(cases)
for case in range(len(cases)):
num = 0
for ba in range(2):
for n in range(len(cases[case][ba])):
if cases[case][ba][n] == "m":
if n - 1 == 0:
num += int(cases[case][ba][n - 1]) * 1000
else:
num += 1000
elif cases[case][ba][n] == "c":
if (n - 1 == 0 and cases[case][ba][n - 1] != "m") or cases[case][ba][
n - 1
] in numlist:
num += int(cases[case][ba][n - 1]) * 100
else:
num += 100
elif cases[case][ba][n] == "x":
if (n - 1 == 0 and cases[case][ba][n - 1] not in ["m", "c"]) in numlist:
num += int(cases[case][ba][n - 1]) * 10
else:
num += 10
elif cases[case][ba][n] == "i":
if (
n - 1 == 0 and cases[case][ba][n - 1] not in ["m", "c", "x"]
) or cases[case][ba][n - 1] in numlist:
num += int(cases[case][ba][n - 1]) * 1
else:
num += 1
else:
num = str(num)
answer = ""
print(num)
for n in range(len(num)):
if len(num) - 1 - n == 3:
if num[n] == "1":
answer += "m"
elif num[n] == "0":
pass
else:
answer += str(num[n]) + "m"
if len(num) - 1 - n == 2:
if num[n] == "1":
answer += "c"
elif num[n] == "0":
pass
else:
answer += str(num[n]) + "c"
if len(num) - 1 - n == 1:
if num[n] == "1":
answer += "x"
elif num[n] == "0":
pass
else:
answer += str(num[n]) + "x"
if len(num) - 1 - n == 0:
if num[n] == "1":
answer += "i"
elif num[n] == "0":
pass
else:
answer += str(num[n]) + "i"
else:
print(answer)
| C: Numeral System
Prof. Hachioji has devised a new numeral system of integral numbers with four
lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5",
"6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1,
respectively, and the digits "2", ...,"9" correspond to 2, ..., 9,
respectively. This system has nothing to do with the Roman numeral system.
For example, character strings
> "5m2c3x4i", "m2c4i" and "5m2c3x"
correspond to the integral numbers 5234 (=5*1000+2*100+3*10+4*1), 1204
(=1000+2*100+4*1), and 5230 (=5*1000+2*100+3*10), respectively. The parts of
strings in the above example, "5m", "2c", "3x" and "4i" represent 5000
(=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1), respectively.
Each of the letters "m", "c", "x" and "i" may be prefixed by one of the digits
"2", "3", ..., "9". In that case, the prefix digit and the letter are regarded
as a pair. A pair that consists of a prefix digit and a letter corresponds to
an integer that is equal to the original value of the letter multiplied by the
value of the prefix digit.
For each letter "m", "c", "x" and "i", the number of its occurrence in a
string is at most one. When it has a prefix digit, it should appear together
with the prefix digit. The letters "m", "c", "x" and "i" must appear in this
order, from left to right. Moreover, when a digit exists in a string, it
should appear as the prefix digit of the following letter. Each letter may be
omitted in a string, but the whole string must not be empty. A string made in
this manner is called an _MCXI-string_.
An MCXI-string corresponds to a positive integer that is the sum of the values
of the letters and those of the pairs contained in it as mentioned above. The
positive integer corresponding to an MCXI-string is called its MCXI-value.
Moreover, given an integer from 1 to 9999, there is a unique MCXI-string whose
MCXI-value is equal to the given integer. For example, the MCXI-value of an
MCXI-string "m2c4i" is 1204 that is equal to `1000 + 2*100 + 4*1`. There are
no MCXI-strings but "m2c4i" that correspond to 1204. Note that strings
"1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are not valid MCXI-strings. The
reasons are use of "1", multiple occurrences of "c", use of "0", and the wrong
order of "c" and "m", respectively.
Your job is to write a program for Prof. Hachioji that reads two MCXI-strings,
computes the sum of their MCXI-values, and prints the MCXI-string
corresponding to the result. | [{"input": "xi x9i\n i 9i\n c2x2i 4c8x8i\n m2ci 4m7c9x8i\n 9c9x9i i\n i 9m9c9x8i\n m i\n i m\n m9i i\n 9m8c7xi c2x8i", "output": "x\n x\n 6cx\n 5m9c9x9i\n m\n 9m9c9x9i\n mi\n mi\n mx\n 9m9c9x9i"}] |
For each specification, your program should print an MCXI-string in a line.
Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in
the specification. No other characters should appear in the output. | s140735494 | Accepted | p00718 | The input is as follows. The first line contains a positive integer _n_ (<=
500) that indicates the number of the following lines. The _k_ +1 th line is
the specification of the _k_ th computation (_k_ =1, ..., _n_).
> _n_
> _specification_ 1
> _specification_ 2
> ...
> _specification_ _n_
>
Each specification is described in a line:
> _MCXI-string_ 1 _MCXI-string_ 2
The two MCXI-strings are separated by a space.
You may assume that the sum of the two MCXI-values of the two MCXI-strings in
each specification is less than or equal to 9999. | mcxi = "mcxi"
mcxinum = [1000, 100, 10, 1]
n = int(input())
for z in range(n):
nums = list(input().split())
ans = 0
for num in nums:
for ind, c in enumerate(mcxi):
if c in num:
prestr, num = num.split(c)
pre = 1
if prestr:
pre = int(prestr)
ans += pre * mcxinum[ind]
ansstr = ""
for j in range(4):
dig = mcxinum[j]
if ans >= dig:
dign = ans // dig
if dign > 1:
ansstr += str(dign)
ansstr += mcxi[j]
ans %= dig
print(ansstr)
| C: Numeral System
Prof. Hachioji has devised a new numeral system of integral numbers with four
lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5",
"6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1,
respectively, and the digits "2", ...,"9" correspond to 2, ..., 9,
respectively. This system has nothing to do with the Roman numeral system.
For example, character strings
> "5m2c3x4i", "m2c4i" and "5m2c3x"
correspond to the integral numbers 5234 (=5*1000+2*100+3*10+4*1), 1204
(=1000+2*100+4*1), and 5230 (=5*1000+2*100+3*10), respectively. The parts of
strings in the above example, "5m", "2c", "3x" and "4i" represent 5000
(=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1), respectively.
Each of the letters "m", "c", "x" and "i" may be prefixed by one of the digits
"2", "3", ..., "9". In that case, the prefix digit and the letter are regarded
as a pair. A pair that consists of a prefix digit and a letter corresponds to
an integer that is equal to the original value of the letter multiplied by the
value of the prefix digit.
For each letter "m", "c", "x" and "i", the number of its occurrence in a
string is at most one. When it has a prefix digit, it should appear together
with the prefix digit. The letters "m", "c", "x" and "i" must appear in this
order, from left to right. Moreover, when a digit exists in a string, it
should appear as the prefix digit of the following letter. Each letter may be
omitted in a string, but the whole string must not be empty. A string made in
this manner is called an _MCXI-string_.
An MCXI-string corresponds to a positive integer that is the sum of the values
of the letters and those of the pairs contained in it as mentioned above. The
positive integer corresponding to an MCXI-string is called its MCXI-value.
Moreover, given an integer from 1 to 9999, there is a unique MCXI-string whose
MCXI-value is equal to the given integer. For example, the MCXI-value of an
MCXI-string "m2c4i" is 1204 that is equal to `1000 + 2*100 + 4*1`. There are
no MCXI-strings but "m2c4i" that correspond to 1204. Note that strings
"1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are not valid MCXI-strings. The
reasons are use of "1", multiple occurrences of "c", use of "0", and the wrong
order of "c" and "m", respectively.
Your job is to write a program for Prof. Hachioji that reads two MCXI-strings,
computes the sum of their MCXI-values, and prints the MCXI-string
corresponding to the result. | [{"input": "xi x9i\n i 9i\n c2x2i 4c8x8i\n m2ci 4m7c9x8i\n 9c9x9i i\n i 9m9c9x8i\n m i\n i m\n m9i i\n 9m8c7xi c2x8i", "output": "x\n x\n 6cx\n 5m9c9x9i\n m\n 9m9c9x9i\n mi\n mi\n mx\n 9m9c9x9i"}] |
For each specification, your program should print an MCXI-string in a line.
Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in
the specification. No other characters should appear in the output. | s144279698 | Wrong Answer | p00718 | The input is as follows. The first line contains a positive integer _n_ (<=
500) that indicates the number of the following lines. The _k_ +1 th line is
the specification of the _k_ th computation (_k_ =1, ..., _n_).
> _n_
> _specification_ 1
> _specification_ 2
> ...
> _specification_ _n_
>
Each specification is described in a line:
> _MCXI-string_ 1 _MCXI-string_ 2
The two MCXI-strings are separated by a space.
You may assume that the sum of the two MCXI-values of the two MCXI-strings in
each specification is less than or equal to 9999. | a = {"m": 1000, "c": 100, "x": 10, "i": 1}
for _ in range(int(input())):
b, s, t = input(), 0, 1
for x in b:
if x == " ":
continue
if x in a:
s += a[x] * t
t = 1
else:
t = int(x)
ans = ""
for k in ["m", "c", "x", "i"]:
c, s = divmod(s, a[k])
if c:
ans += ["", str(c)][c != 0] + k
print(ans)
| C: Numeral System
Prof. Hachioji has devised a new numeral system of integral numbers with four
lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5",
"6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1,
respectively, and the digits "2", ...,"9" correspond to 2, ..., 9,
respectively. This system has nothing to do with the Roman numeral system.
For example, character strings
> "5m2c3x4i", "m2c4i" and "5m2c3x"
correspond to the integral numbers 5234 (=5*1000+2*100+3*10+4*1), 1204
(=1000+2*100+4*1), and 5230 (=5*1000+2*100+3*10), respectively. The parts of
strings in the above example, "5m", "2c", "3x" and "4i" represent 5000
(=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1), respectively.
Each of the letters "m", "c", "x" and "i" may be prefixed by one of the digits
"2", "3", ..., "9". In that case, the prefix digit and the letter are regarded
as a pair. A pair that consists of a prefix digit and a letter corresponds to
an integer that is equal to the original value of the letter multiplied by the
value of the prefix digit.
For each letter "m", "c", "x" and "i", the number of its occurrence in a
string is at most one. When it has a prefix digit, it should appear together
with the prefix digit. The letters "m", "c", "x" and "i" must appear in this
order, from left to right. Moreover, when a digit exists in a string, it
should appear as the prefix digit of the following letter. Each letter may be
omitted in a string, but the whole string must not be empty. A string made in
this manner is called an _MCXI-string_.
An MCXI-string corresponds to a positive integer that is the sum of the values
of the letters and those of the pairs contained in it as mentioned above. The
positive integer corresponding to an MCXI-string is called its MCXI-value.
Moreover, given an integer from 1 to 9999, there is a unique MCXI-string whose
MCXI-value is equal to the given integer. For example, the MCXI-value of an
MCXI-string "m2c4i" is 1204 that is equal to `1000 + 2*100 + 4*1`. There are
no MCXI-strings but "m2c4i" that correspond to 1204. Note that strings
"1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are not valid MCXI-strings. The
reasons are use of "1", multiple occurrences of "c", use of "0", and the wrong
order of "c" and "m", respectively.
Your job is to write a program for Prof. Hachioji that reads two MCXI-strings,
computes the sum of their MCXI-values, and prints the MCXI-string
corresponding to the result. | [{"input": "xi x9i\n i 9i\n c2x2i 4c8x8i\n m2ci 4m7c9x8i\n 9c9x9i i\n i 9m9c9x8i\n m i\n i m\n m9i i\n 9m8c7xi c2x8i", "output": "x\n x\n 6cx\n 5m9c9x9i\n m\n 9m9c9x9i\n mi\n mi\n mx\n 9m9c9x9i"}] |
For each specification, your program should print an MCXI-string in a line.
Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in
the specification. No other characters should appear in the output. | s621572712 | Accepted | p00718 | The input is as follows. The first line contains a positive integer _n_ (<=
500) that indicates the number of the following lines. The _k_ +1 th line is
the specification of the _k_ th computation (_k_ =1, ..., _n_).
> _n_
> _specification_ 1
> _specification_ 2
> ...
> _specification_ _n_
>
Each specification is described in a line:
> _MCXI-string_ 1 _MCXI-string_ 2
The two MCXI-strings are separated by a space.
You may assume that the sum of the two MCXI-values of the two MCXI-strings in
each specification is less than or equal to 9999. | def MCXI_integer(mcxi):
n = 0
buff = 1
for c in mcxi:
if c in "mcxi":
buff *= 10 ** (3 - ["m", "c", "x", "i"].index(c))
n += buff
buff = 1
else:
buff = int(c)
return n
def integer_MCXI(n):
mcxi = ""
buff = 0
for i in range(4):
buff = n % (10 ** (4 - i)) // (10 ** (3 - i))
if buff == 0:
pass
elif buff == 1:
mcxi += "mcxi"[i]
else:
mcxi += str(buff) + "mcxi"[i]
return mcxi
def main():
n = int(input())
for _ in range(n):
s = [x for x in input().split()]
print(integer_MCXI(MCXI_integer(s[0]) + MCXI_integer(s[1])))
if __name__ == "__main__":
main()
| C: Numeral System
Prof. Hachioji has devised a new numeral system of integral numbers with four
lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5",
"6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1,
respectively, and the digits "2", ...,"9" correspond to 2, ..., 9,
respectively. This system has nothing to do with the Roman numeral system.
For example, character strings
> "5m2c3x4i", "m2c4i" and "5m2c3x"
correspond to the integral numbers 5234 (=5*1000+2*100+3*10+4*1), 1204
(=1000+2*100+4*1), and 5230 (=5*1000+2*100+3*10), respectively. The parts of
strings in the above example, "5m", "2c", "3x" and "4i" represent 5000
(=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1), respectively.
Each of the letters "m", "c", "x" and "i" may be prefixed by one of the digits
"2", "3", ..., "9". In that case, the prefix digit and the letter are regarded
as a pair. A pair that consists of a prefix digit and a letter corresponds to
an integer that is equal to the original value of the letter multiplied by the
value of the prefix digit.
For each letter "m", "c", "x" and "i", the number of its occurrence in a
string is at most one. When it has a prefix digit, it should appear together
with the prefix digit. The letters "m", "c", "x" and "i" must appear in this
order, from left to right. Moreover, when a digit exists in a string, it
should appear as the prefix digit of the following letter. Each letter may be
omitted in a string, but the whole string must not be empty. A string made in
this manner is called an _MCXI-string_.
An MCXI-string corresponds to a positive integer that is the sum of the values
of the letters and those of the pairs contained in it as mentioned above. The
positive integer corresponding to an MCXI-string is called its MCXI-value.
Moreover, given an integer from 1 to 9999, there is a unique MCXI-string whose
MCXI-value is equal to the given integer. For example, the MCXI-value of an
MCXI-string "m2c4i" is 1204 that is equal to `1000 + 2*100 + 4*1`. There are
no MCXI-strings but "m2c4i" that correspond to 1204. Note that strings
"1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are not valid MCXI-strings. The
reasons are use of "1", multiple occurrences of "c", use of "0", and the wrong
order of "c" and "m", respectively.
Your job is to write a program for Prof. Hachioji that reads two MCXI-strings,
computes the sum of their MCXI-values, and prints the MCXI-string
corresponding to the result. | [{"input": "xi x9i\n i 9i\n c2x2i 4c8x8i\n m2ci 4m7c9x8i\n 9c9x9i i\n i 9m9c9x8i\n m i\n i m\n m9i i\n 9m8c7xi c2x8i", "output": "x\n x\n 6cx\n 5m9c9x9i\n m\n 9m9c9x9i\n mi\n mi\n mx\n 9m9c9x9i"}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s715906590 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | k, n = map(int, input().split())
spotlist = list(map(int, input().split()))
roadlist = []
for i in range(n - 1):
roadlist.append(spotlist[i + 1] - spotlist[i])
# print(roadlist)
roadlist.append(spotlist[0] + k - spotlist[n - 1])
# print(roadlist)
print(sum(roadlist) - max(roadlist))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s436096077 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | num = input().split(" ")
num_data = [int(num[i]) for i in range(2)]
data = input().split(" ")
data_m = [int(data[i]) for i in range(num_data[1])]
data_m.append(num_data[0] + data_m[0])
key = data_m[0]
locate = 0
for i in range(num_data[1]):
if key < data_m[i + 1] - data_m[i]:
key = data_m[i + 1] - data_m[i]
locate = i + 1
print(num_data[0] - key)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s356355087 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | K, N = map(int, input().strip().split())
A = list(map(int, input().strip().split()))
val = [0, 0]
for i in range(N - 1):
distance = A[i + 1] - A[i]
if distance > val[1]:
val[0] = i
val[1] = distance
last = [N, A[0] + (K - A[N - 1])]
if A[0] + (K - A[N - 1]) > val[1]:
val = last
print(K - val[1])
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s800445696 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | K, N = map(int, input().split(sep=" "))
A = list(map(int, input().split(sep=" ")))
maxA = 0
for i in range(0, N, 1):
if i == N - 1:
tmp = K + A[0] - A[i]
else:
tmp = A[i + 1] - A[i]
if maxA < tmp:
maxA = tmp
print(K - maxA)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s528813082 | Wrong Answer | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | k, n = [int(s) for s in input().split()]
a = [int(s) for s in input().split()]
kyoris = []
for i in range(len(a) - 1):
kyoris.append(abs(a[i] - a[i + 1]))
lastkyori = (k - a[-1]) + a[0]
kyoris.append(lastkyori)
print(max(kyoris))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s335644199 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | K, N = [int(_) for _ in input().split()]
A = [int(_) for _ in input().split()]
dist = [b - a for a, b in zip(A, A[1:])]
dist += [K - A[-1] + A[0]]
print(K - max(dist))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s530231704 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | def bubbleSort(array):
sortCompleted = False
while sortCompleted != True:
sortCompleted = True
for i in range(len(array) - 1):
if array[i] > array[i + 1]:
array[i], array[i + 1] = array[i + 1], array[i]
sortCompleted = False
def getMaxDistance(array):
maxDistance = 0
for i in range(len(array) - 1):
distance = abs(array[i] - array[i + 1])
if maxDistance < distance:
maxDistance = distance
return maxDistance
def function(K, An):
bubbleSort(An)
An.append(K + An[0])
maxDistance = getMaxDistance(An)
minDistance = K - maxDistance
return str(minDistance)
if __name__ == "__main__":
K, N = map(int, input().split())
An = list(map(int, input().split()))
print(function(K, An))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s889237938 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | k, n = [int(i) for i in input().strip().split(" ")]
arr = [int(i) for i in input().strip().split(" ")]
# maxDist=arr[0]+min(k-arr[-1],arr[-1])
maxDist = arr[0] + k - arr[-1]
# maxDist=max(arr)-min(arr)
for i in range(n - 1):
maxDist = maxDist if arr[i + 1] - arr[i] <= maxDist else arr[i + 1] - arr[i]
print(k - maxDist)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s998613873 | Wrong Answer | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | k, n = [int(_) for _ in input().split()]
a = [int(_) for _ in input().split()]
ans1 = a[n - 1] - a[0]
ans2 = a[n - 2] - (a[n - 1] - k)
ans3 = a[0] - (a[n - 2] - k)
print(min(ans1, ans2, ans3))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s422793002 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | k, n = map(int, input().split())
(*a,) = map(int, input().split())
a += [i + k for i in a]
print(min(j - i for i, j in zip(a, a[n - 1 :])))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s833475799 | Wrong Answer | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | K, N = map(int, input().split())
lists = list(map(int, input().split()))
# a = 1000000
# for i in range(len(lists)):
# if abs(K - lists[i]) == 0:
# continue
# elif abs(K - lists[i]) < a:
# a = abs(K - lists[i])
# b = 1000000
# for i in range(len(lists)):
# for j in range(len(lists)):
# if abs(lists[i] - lists[j]) == 0:
# continue
# elif abs(lists[i] - lists[j]) < b:
# b = abs(lists[i] - lists[j])
list_min = min(lists)
list_max = max(lists)
delta = list_max - list_min
kk = K / 2
if delta >= kk:
c = kk
else:
c = delta
# a = []
# for i in range(len(lists)):
# if abs(K - lists[i]) == 0:
# continue
# else:
# a.append(abs(K - lists[i]))
# b = []
# for i in range(len(lists)):
# for j in range(len(lists)):
# if abs(lists[i] - lists[j]) == 0:
# continue
# else:
# b.append(abs(lists[i] - lists[j]))
# a = min(a)
# b = min(b)
# c = a+b
print(int(c))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s273843198 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | score = list(map(int, input().split()))
kenl = list(map(int, input().split()))
syoki = 0
syoki = kenl[0] + (score[0] - kenl[score[1] - 1])
length = [0] * score[1]
length[0] = syoki
for i in range(score[1] - 1):
length[i + 1] = kenl[i + 1] - kenl[i]
length.sort()
answer = length[score[1] - 1]
print(score[0] - answer)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s570253739 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | data1 = input()
data2 = input()
circle = int(data1.split()[0])
house = int(data1.split()[1])
distance = [int(s) for s in data2.split()]
# 隣接間の最大距離を省いてみる
between = []
for i, d in enumerate(distance):
if i != house - 1:
between.append(distance[i + 1] - d)
else:
between.append(circle - d + distance[0])
print(sum(between) - max(between))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s514983635 | Wrong Answer | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | date0 = input().rstrip().split(" ")
date1 = input().rstrip().split(" ")
list0 = []
list1 = []
for i in range(int(date0[1])):
list0.append(int(date1[i]))
# print(list0)
list0 = sorted(list0)
# print(list0)
for j in range(int(date0[1]) - 1):
list1.append(list0[j + 1] - list0[j])
list1.append(int(date0[0]) - list0[int(date0[1]) - 1])
list1 = sorted(list1, reverse=True)
print(int(date0[0]) - list1[0])
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s073261047 | Wrong Answer | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | ddd = [input() for i in range(2)]
eee = ddd[0].split()
fff = ddd[1].split()
longest_distance = int(eee[0]) - int(fff[-1])
for i in range(len(fff) - 1):
distance = int(fff[i + 1]) - int(fff[i])
if longest_distance < distance:
longest_distance = distance
shortest_road = int(eee[0]) - longest_distance
print(shortest_road)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s772821343 | Wrong Answer | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | A = input()
LA = A.split()
K = int(LA[0])
N = int(LA[1])
B = input()
LB = B.split()
C = 0
samax = 0
start = 0
for n in LB:
sa = int(int(n) - int(C))
C = n
if samax < sa:
samax = sa
start = int(n) - int(samax)
ans1 = int(LB[N - 1]) - int(LB[0])
ans2 = int((K - int(LB[N - 1])) + int(start))
if ans2 > ans1:
ans = ans1
else:
ans = ans2
print(ans)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s174499499 | Wrong Answer | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | k, n = map(int, input().split())
n_inf = list(map(int, input().split()))
n_inf.append(k)
n_inf.insert(0, 0)
# print(n_inf)
kyori_list = [j for j in range(n + 1)]
for i in range(n + 1):
kyori_list[i] = n_inf[i + 1] - n_inf[i]
# print(kyori_list)
kyori_list.sort(reverse=1)
# print(kyori_list)
print(sum(kyori_list[1 : n + 1]))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s047397963 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | k, n = map(int, input().split())
lists = list(map(int, input().split()))
lists = sorted(lists)
mini = 0
lists.append(lists[0] + k)
for i in range(1, n + 1):
mini = max(mini, lists[i] - lists[i - 1])
print(k - mini)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s313727063 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | K, N = [int(hoge) for hoge in input().split()]
A = [int(hoge) for hoge in input().split()]
d = K - A[-1] + A[0]
for n in range(N):
d = max(d, A[n] - A[n - 1])
print(K - d)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s515136746 | Accepted | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | # maintain overall min
# iterate over two loops
# find the absolute distance and before exiting the first maintain overall min
# also check the distance of last and first house
def findDistBetween(i, j):
return abs(i - j)
def minDistfindDistBetweenLastAndFirstHouse(i, j):
dist = findDistBetween(i, j)
return K - dist
K, N = input().split()
As = input().split()
K = int(K)
N = int(N)
# print ("As is")
# print (As)
# print (As.split())
A = [0] * len(As)
for i in range(len(As)):
A[i] = int(As[i])
# A = list(map(lambda x: int(x), As))
# print (A)
# overAllMin = float('inf')
# minDist = 0
# for i in range(N):
# minDist = 0
# for j in range(N):
# # print (i, j)
# minDist += findDistBetween(A[i], A[j])
# # find the dist b/w last and first house
# # minDist2 = minDistfindDistBetweenLastAndFirstHouse(A[0], A[-1])
# # minDist = min(minDist, minDist2)
# print ("Min dist", minDist)
# # print ("min dist2", minDist2)
# overAllMin = min(overAllMin, minDist)
# print (overAllMin)
overAllMin = float("inf")
Arev = list(reversed(A))
dist1 = 0
dist2 = 0
prevHouse = -1
for i in range(N):
# print ("PRev house", prevHouse)
# print ("Next house", A[i])
dist1 = max(findDistBetween(A[i], prevHouse), dist1)
prevHouse = A[i]
ma = max(dist1, minDistfindDistBetweenLastAndFirstHouse(A[0], A[-1]))
print(K - ma)
# for i in range(N):
# count = 0
# curHouse = A[i]
# j = i
# flag0 = 0
# flag1 = 0
# dist1 = 0
# dist2 = 0
# while count < N:
# if flag0 is 0:
# dist1 += findDistBetween(curHouse, A[j])
# curHouse = A[j]
# j += 1
# flag0 = 0
# count += 1
# if j == N and count < N:
# print ("in condition")
# j = 0
# dist1 += minDistfindDistBetweenLastAndFirstHouse(A[0], A[-1])
# flag0 = 1
# count += 1
# print ("dist1", dist1)
# count = 0
# curHouse = A[i]
# j = i
# while count < N:
# if flag1 is 0:
# dist2 += findDistBetween(curHouse, A[j])
# curHouse = A[j]
# j -= 1
# count += 1
# flag1 = 0
# if j == -1 and count < N:
# j = N - 1
# dist2 += minDistfindDistBetweenLastAndFirstHouse(A[0], A[-1])
# flag1 = 1
# # count += 1
# overAllMin = min(dist1, K - findDistBetween(A[0], A[-1]), overAllMin)
# print (dist1, K - findDistBetween(A[0], A[-1]), overAllMin)
# print (overAllMin)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s551154514 | Wrong Answer | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | """
2 2 4 4 4
11 12 13 14
21 22 23 24
1 2 3 4
"""
"""o=input().rstrip().split(' ')
x=int(o[0])
y=int(o[1])
a=int(o[2])
b=int(o[3])
c=int(o[4])
H=0;
R=input().rstrip().split(' ')
G=input().rstrip().split(' ')
ANY=input().rstrip().split(' ')
R.sort(key=int,reverse=True)
G.sort(key=int,reverse=True)
ANY.sort(key=int,reverse=True)
while(x>0):
if int(R[0]) > int(ANY[0]):
H+=int(R[0])
del(R[0])
x-=1;
else:
break;
while(y>0):
if int(G[0]) > int(ANY[0]):
H+=int(G[0])
del(G[0])
y-=1;
else:
break;
if(x>0 && y==0):
for i in range(0,x):
if i<len(ANY):
H+=ANY[i];
else:
H+=int(R[0])
del(R[0])
elif(y>0 && x==0):
for i in range(0,y):
if i<len(ANY):
H+=ANY[i];
else:
H+=int(G[0])
del(G[0])
else:
FF=x+y;
if FF<=len(ANY):
for i in range(0,len(ANY)):
H+=int(ANY[i])
else:
for i in range(0,len(ANY)):
H+=int(ANY[i])
XX=0;
YY=0;
for i in range(0,x):
"""
"""
20 3
0 5 15
"""
o = input().rstrip().split(" ")
p = input().rstrip().split(" ")
l = []
for i in range(1, len(p)):
l.append(int(p[i]) - int(p[i - 1]))
l.append(int(o[0]) - int(p[len(p) - 1]))
q = []
C = list(p)
A = list(C[0])
B = C[1 : len(C)]
B.reverse()
C = A + B
# print(C)
for i in range(1, len(C)):
q.append(int(o[0]) - int(C[i]))
q.append(int(o[0]) - int(C[0]))
# print(l,q)
S = 0
D = 0
for i in range(0, len(l)):
S += int(l[i])
D += int(q[i])
W = []
minu = 10000000000
for i in range(0, len(l)):
if i == 0:
F = S - int(l[len(l) - 1])
minu = min(minu, F)
else:
F = S - int(l[i - 1])
minu = min(minu, F)
for i in range(0, len(q)):
if i == 0:
F = D - int(q[len(l) - 1])
minu = min(minu, F)
else:
F = D - int(q[i - 1])
minu = min(minu, F)
print(minu)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s558438919 | Runtime Error | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | l = input().split(" ")
j = input().split(" ")
k = int(l[0])
n = int(l[1])
x = 0
for i in range(n):
d = int(j[i + 1]) - int(j[i])
x = max(x, d)
dt = k - int(x)
print(dt)
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses.
* * * | s023202126 | Wrong Answer | p02725 | Input is given from Standard Input in the following format:
K N
A_1 A_2 ... A_N | K, N = map(int, input().split())
A = list(map(int, input().split()))
maxNum, minNum = 0, K
for n in range(N):
if maxNum < A[n]:
maxNum = A[n]
if minNum > A[n]:
minNum = A[n]
res = maxNum - minNum
maxNum, minNum = 0, K
a = True
for n in range(N):
b = True
if A[n] == K / 2:
a = False
if A[n] > K / 2:
A[n] = (K - A[n]) * -1
b = False
if maxNum < A[n]:
maxNum = A[n]
if minNum > A[n]:
minNum = A[n]
if b == False:
A[n] = K + A[n]
res = min(maxNum - minNum, res)
if a == False:
minNum, maxNum = K, 0
for n in range(N):
if A[n] >= K / 2:
A[n] = (K - A[n]) * -1
if maxNum < A[n]:
maxNum = A[n]
if minNum > A[n]:
minNum = A[n]
print(min(res, maxNum - minNum))
| Statement
There is a circular pond with a perimeter of K meters, and N houses around
them.
The i-th house is built at a distance of A_i meters from the northmost point
of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of
the houses and visit all the N houses. | [{"input": "20 3\n 5 10 15", "output": "10\n \n\nIf you start at the 1-st house and go to the 2-nd and 3-rd houses in this\norder, the total distance traveled will be 10.\n\n* * *"}, {"input": "20 3\n 0 5 15", "output": "10\n \n\nIf you start at the 2-nd house and go to the 1-st and 3-rd houses in this\norder, the total distance traveled will be 10."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s945595786 | Runtime Error | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | from collections import deque
sx, sy, tx, ty = map(int, input().split())
ans_list = []
(tx, ty) = (tx - sx, ty - sy)
(sx, sy) = (0, 0)
H, W = ty + 3, tx + 3
visited = [[0] * (tx + 3) for i in range(ty + 3)]
d = [[1, 0], [0, 1], [-1, 0], [0, -1]]
(sx, sy) = (sx + 1, sy + 1)
(tx, ty) = (tx + 1, ty + 1)
def bfs(si, sj, gi, gj):
tr = [[si, sj]]
q = deque([[si, sj, tr]])
while q:
i, j, tr = q.popleft()
if (i, j) == (gi, gj):
return tr
for di, dj in d:
ni = i + di
nj = j + dj
if 0 <= ni <= H - 1 and 0 <= nj <= W - 1 and visited[ni][nj] == 0:
visited[ni][nj] = 1
ntr = tr[:]
ntr.append([ni, nj])
q.append([ni, nj, ntr])
def change(tr):
def func(d):
if d == (1, 0):
return "U"
if d == (-1, 0):
return "D"
if d == (0, -1):
return "L"
if d == (0, 1):
return "R"
for i in range(len(tr) - 1):
(ni, nj) = (tr[i + 1][0], tr[i + 1][1])
(i, j) = (tr[i][0], tr[i][1])
d = (ni - i, nj - j)
ans_list.append(func(d))
tr = []
for cnt in range(2):
res = bfs(sy, sx, ty, tx)
for k in range(1, len(res)):
i, j = res[k][0], res[k][1]
rei, rej = ty + sx - i, tx + sy - j
res.append([rei, rej])
if cnt == 0:
tr += res
else:
tr += res[1:]
visited = [[0] * W for i in range(H)]
for i, j in tr:
visited[i][j] = 1
visited[ty][tx] = 0
change(tr)
ans = "".join(ans_list)
print(ans)
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s393145895 | Runtime Error | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | class Dijkstra: # 最短経路問題
def __init__(self, route_map, start_point, goal_point=None):
self.route_map = route_map #
self.start_point = start_point # スタート位置
self.goal_point = goal_point
def execute(self):
import heapq
num_of_city = len(self.route_map) # ノード数
dist = [float("inf") for _ in range(num_of_city)] # startからの距離を格納する
prev = [
float("inf") for _ in range(num_of_city)
] # prev[i]:ノードiに向かう前のノード番号。これを持っておけば、goalからstartまで辿れる
dist[self.start_point] = 0 # スタート位置までのコストは0
heap_q = [] # 優先度つきキュー
heapq.heappush(
heap_q, (0, self.start_point)
) # タプル(0,スタート位置)をheap_qに追加
while len(heap_q) != 0:
prev_cost, src = heapq.heappop(
heap_q
) # 直前にheap_qに入れたタプルから取り出す(src=ソース)
if (
dist[src] < prev_cost
): # もし、スタート位置からsrcまでの距離がprev_costより小さいなら問題ないのでok
continue
for dest, cost in self.route_map[
src
].items(): # destはsrcから行ける頂点(目的地)
if (
cost != float("inf") and dist[dest] > dist[src] + cost
): # もし、destに有限のコストで行けて、srcからdestに行くのがスタートからの現状の最短距離になるなら、
dist[dest] = dist[src] + cost # 更新する
heapq.heappush(
heap_q, (dist[dest], dest)
) # 更新したのでheap_qに入れておく。次のノードに移動した時に取り出して無駄な変更がないか確認する
prev[dest] = src
if self.goal_point is not None: # ゴールまでの最短経路を返す
return self.get_path(self.goal_point, prev)
else: # スタートから各頂点までの最短距離を格納したリストを返す
return dist
def get_path(
self, goal, prev
): # prev[i]:ノードiに向かう前のノード番号。これを持っておけば、goalからstartまで辿れる
global edge_num
global used_edge
path = [goal]
dest = goal
while prev[dest] != float("inf"): # prev[start]はfloat("inf")になり、停止する
used_edge[edge_num[prev[dest]][dest]] += 1
path.append(prev[dest]) # 後ろから戻っていく
dest = prev[dest]
return list(reversed(path)) # 逆から辿ったので順を元に戻す
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
route_map = [dict() for _ in range(N)]
edge_num = [dict() for _ in range(N)]
for i in range(M): # M == エッジの数
u, v, cost = map(int, input().split()) # cost は 辺 u -> v の重み(距離,コスト)
u, v = u - 1, v - 1
route_map[u][v] = cost # route_mapの第u番目のdictに{v:cost}が入る
route_map[v][u] = cost # route_mapの第v番目のdictに{u:cost}が入る
edge_num[u][v] = i # redge_numの第u番目のdictに{v:i}が入る
edge_num[v][u] = i # redge_numの第v番目のdictに{u:i}が入る
used_edge = [0 for _ in range(M)]
checked_node = [[0 or _ in range(N)] for __ in range(N)]
for i in range(N - 1):
for j in range(i + 1, N):
if checked_node[i][j] != 0:
continue
dijkstra_result1 = Dijkstra(route_map, i, j).execute()
dijkstra_result2 = Dijkstra(route_map, N - 1 - i, N - 1 - j).execute()
for k in range(len(dijkstra_result1) - 1):
for l in range(k + 1, len(dijkstra_result1)):
checked_node[dijkstra_result1[k]][dijkstra_result1[l]] += 1
for k in range(len(dijkstra_result2) - 1):
for l in range(k + 1, len(dijkstra_result2)):
checked_node[dijkstra_result2[k]][dijkstra_result2[l]] += 1
ans = used_edge.count(0)
print(ans)
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s410440370 | Runtime Error | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | s = input()
k = int(input())
ans = []
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
ans.append(s[i:j])
ans.sort()
a = [ans[0]]
for i in range(1, len(ans)):
if ans[i - 1] != ans[i]:
a.append(ans[i])
print(a[k - 1])
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s954548714 | Wrong Answer | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | def main():
node_num, edge_num = map(int, input().split())
print(edge_num - node_num + 1)
if __name__ == "__main__":
main()
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s002849271 | Runtime Error | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | import copy
N, M = map(int, input().split())
dp = [[float('inf')]*N for _ in range(N)]
for i in range(N):
dp[i][i] = 0
for i in range(M):
a, b, c = map(int, input().split())
dp[a-1][b-1] = c
dp[b-1][a-1] = c
g = copy.deepcopy(dp)
# ワーシャルフロイド
for k in range(N):
for i in range(N):
for j in range(N):
dp[i][j] = min([dp[i][j], dp[i][k]+dp[k][j]])
# 経路復元
p = {}
for i in range(N):
for j in range(N):
c = i
while c != j:
for k in range(N):
if k != c and (g[c][k]+dp[k][j]) == dp[c][j]:
p[(c, k) if c < k else (k, c)] = 1
c = k
break
print(max([0, M-len(p)))
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s353750703 | Wrong Answer | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | # 無向グラフ
class Graph:
# 初期変数は頂点数、辺数、標準入力から受け取った配列形式の入力
def __init__(self, vertex_num, node_num, naive_input):
self.vertex_num = vertex_num
self.node_num = node_num
# nodeには入力時のインデックスも含む
# [接続ノード , インッデクス]のarray
node = [[] for _ in range(vertex_num)]
for i in range(node_num):
u, v = naive_input[i][:2]
w = naive_input[i][2]
node[u].append([v, i, w])
node[v].append([u, i, w])
self.node = node
# それぞれの頂点の辺の数
self.node_num_arr = list(map(lambda x: len(x), node))
# 頂点nowから順にbfs
def bfs(self, s=0):
# 最短経路+αで問題を解くと思うのでcal_distance内で問題を解くための関数を実行する形の方が自然?
def cal_distance(
now_edge, next_edge_info, distance_arr, before_vertex_arr, queue, l_ind
):
next_edge = next_edge_info[0]
weight = next_edge_info[2]
cal_distance_val = distance_arr[now_edge] + weight
if before_vertex_arr[next_edge] == -1:
queue[l_ind] = next_edge
# print("queue is updated")
l_ind += 1
if cal_distance_val < distance_arr[next_edge]:
# 配列渡しなのでこのあたりは返り値に持たせる必要無し
distance_arr[next_edge] = cal_distance_val
before_vertex_arr[next_edge] = now_edge
# for debug
# print(now_edge,"→",next_edge,":",cal_distance_val)
# print(distance_arr)
# print(before_vertex)
return l_ind
# bfs用のキュー
q = [-1 for _ in range(self.vertex_num)]
# pypyを使うときは要変更
# ダイクストラ使用に伴って削除
# 訪問済み頂点は距離から導出
# cal_node_num_arr=self.node_num_arr.copy()
now_ind = 0
q[now_ind] = s
last_ind = 1
distance = [float("inf") for _ in range(self.vertex_num)]
distance[s] = 0
before_vertex = [-1 for _ in range(self.vertex_num)]
before_vertex[s] = s
index_arr = [-1 for _ in range(self.node_num)]
while last_ind < self.vertex_num:
now_edge = q[now_ind]
"""
print()
print()
print("now_node:",now_edge)
print("now_ind:",now_ind,"last_ind",last_ind)
print(q)
print(before_vertex)
"""
for next_edge_info in self.node[now_edge]:
# インデックスを利用したいときは要修正
# cal_node_num_arr[now_edge]-=1
# cal_node_num_arr[next_edge]-=1
# q[last_ind]=next_edge
##ここにやりたい処理をぶち込む!!
#######cal_hogehoge()
# 頂点sから各頂点までの距離を計算する
last_ind = cal_distance(
now_edge, next_edge_info, distance, before_vertex, q, last_ind
)
now_ind += 1
return distance
n, m = list(map(int, input().split()))
"""
maze=[[i for i in input()] for _ in range(n)]
graph=[[] for _ in range(n*m)]
q_num=0
for i in range(n):
for j in range(m):
if maze[i][j]=="#":
continue
ind=i*m+j
q_num+=1
#move[i][j]=ind
if i!=0:
if maze[i-1][j]!="#":
graph[ind].append((i-1)*m+j)
if i!=n-1:
if maze[i+1][j]!="#":
graph[ind].append((i+1)*m+j)
if j!=0:
if maze[i][j-1]!="#":
graph[ind].append(i*m+j-1)
if j!=m-1:
if maze[i][j+1]!="#":
graph[ind].append(i*m+j+1)
a=[]
for num,i in enumerate(graph):
for j in i:
a.append([num,j,1])
#print(a)
tmp=0
for i in maze:
for j in i:
if j==".":
tmp+=1
n=tmp
m=len(a)
"""
a = [list(map(int, input().split())) for _ in range(m)]
a = list(map(lambda x: [x[0] - 1, x[1] - 1, x[2]], a))
G = Graph(n, m, a)
ans = 0
for i in range(n):
cal = G.bfs(i)
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s049609547 | Wrong Answer | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | n, m = input().strip().split(" ")
n, m = [int(n), int(m)]
if m >= n:
print((m - (n - 1)))
else:
print(0)
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s151429992 | Accepted | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | # https://atcoder.jp/contests/abc051/tasks/abc051_d
# 考えたこと
# 1.経路復元
# 2.ダイクストラ時に使った辺記録(こっちで解いてみる)
# あとで必要なのでクラスを準備しておく
from heapq import heapify, heappop, heappush, heappushpop
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate
def read_ints():
return list(map(int, read().split()))
class PriorityQueue:
def __init__(self, heap):
"""
heap ... list
"""
self.heap = heap
heapify(self.heap)
def push(self, item):
heappush(self.heap, item)
def pop(self):
return heappop(self.heap)
def pushpop(self, item):
return heappushpop(self.heap, item)
def __call__(self):
return self.heap
def __len__(self):
return len(self.heap)
INF = 10**9 + 1
def dijkstra(adj: list, s: int, N: int):
Color = [0] * N # 0:未訪問 1:訪問経験あり 2:訪問済み(そこまでの最短経路は確定済み)
D = [INF] * N # 本のdと同じ 始点からの距離を記録する
P = [None] * N # 本のpと同じ 最短経路木における親を記録する
# スタートとするノードについて初期化
D[s] = 0 # スタートまでの距離は必ず0
P[s] = None # 親がない(ROOTである)ことを示す
PQ = PriorityQueue(
[(0, s)]
) # (コスト, ノード番号)で格納 こうするとPQでソートするときに扱いやすい
# while True:
while PQ: # PQに候補がある限り続ける
# min_cost = INF
# for i in range(N):
# if Color[i] != 2 and D[i] < min_cost:
# min_cost = D[i]
# u = i
min_cost, u = PQ.pop() # 上記の処理はこのように簡略化できる
Color[u] = 2 # uは訪問済み これから最短経路木に突っ込む作業をする
if D[u] < min_cost:
# もし今扱っているmin_costがメモしているやつよりも大きいなら何もしないで次へ(メモしている方を扱えばいいので)
continue
# 以下のforではsからの最短経路木にuを追加したときの更新、uまわりで次の最短経路になる候補の更新をしている
for idx_adj_u, w_adj_u in adj[u]:
if Color[idx_adj_u] != 2:
# 訪問済みでなく、u→vへの経路が存在するならば
if D[u] + w_adj_u < D[idx_adj_u]:
D[idx_adj_u] = D[u] + w_adj_u # u周りにおける最短経路の候補の更新
P[idx_adj_u] = u
PQ.push((D[idx_adj_u], idx_adj_u)) # ここで候補に追加していっている
Color[idx_adj_u] = 1
return D, P
# load datas
N, M = read_ints()
adj = [[] for _ in range(N)] # (node_id, 隣接要素, 隣接nodeidとコスト)の順で格納する
for _ in range(M):
a, b, c = read_ints()
a -= 1
b -= 1
adj[a].append((b, c))
adj[b].append((a, c))
used_edges = set()
for s in range(N):
_, P = dijkstra(adj, s, N)
for i, p in enu(P):
if p == None:
continue
if p > i:
i, p = p, i
used_edges.add((i, p))
print(M - len(used_edges))
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s808612499 | Accepted | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | # 2020-05-28 22:26:38
import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
N, M = map(int, input().split())
def modify(x, y):
if x > y:
x, y = y, x
return (x, y)
edge = [[] for _ in range(N)]
edgeid = dict()
for k in range(M):
u, v, r = map(int, input().split())
edge[u - 1].append((v - 1, r))
edge[v - 1].append((u - 1, r))
edgeid[modify(u - 1, v - 1)] = k
from heapq import heappop, heappush, heapify
INF = 10**20
def dijkstra2(S, N, Edge):
# S: start vertex
# N: number of vertices
# Edge: adjacent list [node, cost]
dist = [INF] * N
dist[S] = 0
root = [-1] * N
que = [(0, S)]
heapify(que)
while que:
c, v = heappop(que)
if dist[v] < c:
continue
for nv, nc in Edge[v]:
if c + nc < dist[nv]:
dist[nv] = c + nc
root[nv] = v
heappush(que, (c + nc, nv))
return [dist, root]
def find_path(S, T, root):
# SからTへのパスを逆順で返す
path = []
cur = T
while cur != S:
past = root[cur]
path.append((past, cur))
cur = past
return path
unused_flag = [True] * M
for start in range(N):
dist, root = dijkstra2(start, N, edge)
for goal in range(N):
if start == goal:
continue
for p in find_path(start, goal, root):
unused_flag[edgeid[modify(p[0], p[1])]] = False
print(sum(unused_flag))
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s018839878 | Accepted | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | class DirectedEdge(object):
def __init__(self, v, w, weight, id):
self.v = v
self.w = w
self.weight = weight
self.id = id
def __str__(self):
return "[{} -> {}: {}]".format(self.v, self.w, self.weight)
def edge_from(self):
return self.v
def edge_to(self):
return self.w
def get_weight(self):
return self.weight
def get_id(self):
return self.id
class EdgeWeightedDigraph(object):
def __init__(self, vertex_size):
self.VERTEX_SIZE = vertex_size
self.adj = [set() for x in range(self.get_vertex_size())]
def get_vertex_size(self):
return self.VERTEX_SIZE
def add_edge(self, edge):
v = edge.edge_from()
self.adj[v].add(edge)
def get_adj(self, v):
res = set()
for edge in self.adj[v]:
res.add(edge)
return res
class IndexMinPQ(object):
def __init__(self, size):
self.keys = [None for x in range(size + 1)] # key を格納
self.pq = [
None for x in range(size + 1)
] # tree 構造を形成する. key の id を格納
self.qp = [None for x in range(size + 1)]
self.n = 0
def contains(self, i):
if self.qp[i] is None:
return False
else:
return True
def is_empty(self):
return self.n == 0
def size(self):
return self.n
def decrease_key(self, i, key):
self.keys[i] = key
self._swim(self.qp[i])
def insert(self, i, key):
tail = self.n + 1
self.pq[tail] = i
self.qp[i] = tail
self.keys[i] = key
self._swim(tail)
self.n += 1
def _swim(self, i):
while i != 1:
p = self._get_parent_pos(i)
if not self._is_less(p, i):
self._exch(p, i)
i = p
else:
break
def del_min(self):
head = self.pq[1]
self.pq[1] = None
self.keys[head] = None
self.qp[head] = None
self._exch(1, self.n)
self.n -= 1
self._sink(1)
return head
def _sink(self, i):
while self._get_left_child_pos(i) <= self.n:
left = self._get_left_child_pos(i)
right = left + 1
child = left
if not left == self.n and not self._is_less(left, right):
child = right
if not self._is_less(i, child):
self._exch(i, child)
i = child
else:
break
def _is_less(self, a, b):
a_id = self.pq[a]
b_id = self.pq[b]
return self.keys[a_id] < self.keys[b_id]
def _get_parent_pos(self, i):
return i // 2
def _get_left_child_pos(self, i):
return i * 2
def _exch(self, a, b):
swap = self.pq[a]
self.pq[a] = self.pq[b]
self.pq[b] = swap
if self.pq[a] is not None:
self.qp[self.pq[a]] = a
if self.pq[b] is not None:
self.qp[self.pq[b]] = b
class DijkstraShortestPath(object):
def __init__(self, edge_weighted_digraph, source):
self.digraph = edge_weighted_digraph
self.source = source
self.edge_to = [None for x in range(self.digraph.get_vertex_size())]
self.dist_to = [
float("infinity") for x in range(self.digraph.get_vertex_size())
]
self.ipq = IndexMinPQ(self.digraph.get_vertex_size())
self.dist_to[source] = 0.0
self.ipq.insert(source, self.dist_to[source])
while not self.ipq.is_empty():
v = self.ipq.del_min()
for edge in self.digraph.get_adj(v):
self._relax(edge)
def _relax(self, edge):
v = edge.edge_from()
w = edge.edge_to()
if self.dist_to[v] + edge.get_weight() < self.dist_to[w]:
self.dist_to[w] = self.dist_to[v] + edge.get_weight()
self.edge_to[w] = edge
if self.ipq.contains(w):
self.ipq.decrease_key(w, self.dist_to[w])
else:
self.ipq.insert(w, self.dist_to[w])
def has_path_to(self, v):
return self.dist_to[v] < float("infinity")
def path_to(self, v):
path = []
while self.edge_to[v] is not None:
edge = self.edge_to[v]
path.append(edge)
v = edge.edge_from()
return path
def solve():
N, M = map(int, input().split())
ABC = []
for _ in range(M):
ABC.append(tuple(map(int, input().split())))
edges = []
G = EdgeWeightedDigraph(N + 1)
for a, b, c in ABC:
edge_a = DirectedEdge(int(a), int(b), float(c), (a, b))
edge_b = DirectedEdge(int(b), int(a), float(c), (a, b))
G.add_edge(edge_a)
G.add_edge(edge_b)
edges.append((a, b))
founds = set()
for s in range(1, N + 1):
sp = DijkstraShortestPath(G, s)
for v in range(1, N + 1):
if not v == s:
for e in sp.path_to(v):
# print(s, v, e)
founds.add(e.get_id())
ans = len(edges) - len(founds)
return ans
if __name__ == "__main__":
res = solve()
print(res)
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s014231799 | Wrong Answer | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | def main():
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
# from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby
# from itertools import product
from bisect import bisect_left, bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil
# from operator import itemgetter
# inf = 10**17
# mod = 10**9 + 7
inf = 10**17
def dijkstra_heap(start, edge):
# 始点から各頂点への最短距離(頂点番号:0~N-1)
d = [inf] * N
used = [False] * N
d[start] = 0
used[start] = True
edgelist = []
# a:重み(//), b:次の頂点(%)
for a, b, i in edge[start]:
heappush(edgelist, (a * (10**6) + b, i))
while len(edgelist):
# まだ最短距離が決まっていない頂点の中から最小の距離のものを探す
minedge, i = heappop(edgelist)
if used[minedge % (10**6)]:
continue
node = minedge % (10**6)
d[node] = minedge // (10**6)
res[i] = 1
used[node] = True
for e in edge[node]:
if not used[e[1]]:
heappush(edgelist, ((e[0] + d[node]) * (10**6) + e[1], e[2]))
return d
# N:頂点数 W:辺数
N, W = map(int, input().split())
edge = [[] for i in range(N)]
# edge[i] : iから出る道の[重み,行先]の配列
for i in range(W):
x, y, z = map(int, input().split())
edge[x - 1].append((z, y - 1, i))
edge[y - 1].append((z, x - 1, i))
res = [0] * W
for i in range(N):
d = dijkstra_heap(i, edge)
print(W - sum(res))
if __name__ == "__main__":
main()
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s172288680 | Accepted | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10**7)
# UnionFind
class UnionFind:
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return "\n".join("{}: {}".format(r, self.members(r)) for r in self.roots())
def is_prime(n):
if n == 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# ワーシャルフロイド (任意の2頂点の対に対して最短経路を求める)
# 計算量n^3 (nは頂点の数)
def warshall_floyd(d, n):
# d[i][j]: iからjへの最短距離
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
return d
# ダイクストラ
def dijkstra_heap(s, edge, n):
# 始点sから各頂点への最短距離
d = [10**20] * n
used = [True] * n # True:未確定
d[s] = 0
used[s] = False
edgelist = []
for a, b in edge[s]:
heapq.heappush(edgelist, a * (10**6) + b)
while len(edgelist):
minedge = heapq.heappop(edgelist)
# まだ使われてない頂点の中から最小の距離のものを探す
if not used[minedge % (10**6)]:
continue
v = minedge % (10**6)
d[v] = minedge // (10**6)
used[v] = False
for e in edge[v]:
if used[e[1]]:
heapq.heappush(edgelist, (e[0] + d[v]) * (10**6) + e[1])
return d
# 素因数分解
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
# 2数の最小公倍数
def lcm(x, y):
return (x * y) // gcd(x, y)
# リストの要素の最小公倍数
def lcm_list(numbers):
return reduce(lcm, numbers, 1)
# リストの要素の最大公約数
def gcd_list(numbers):
return reduce(gcd, numbers)
# 素数判定
# limit以下の素数を列挙
def eratosthenes(limit):
A = [i for i in range(2, limit + 1)]
P = []
while True:
prime = min(A)
if prime > sqrt(limit):
break
P.append(prime)
i = 0
while i < len(A):
if A[i] % prime == 0:
A.pop(i)
continue
i += 1
for a in A:
P.append(a)
return P
# 同じものを含む順列
def permutation_with_duplicates(L):
if L == []:
return [[]]
else:
ret = []
# set(集合)型で重複を削除、ソート
S = sorted(set(L))
for i in S:
data = L[:]
data.remove(i)
for j in permutation_with_duplicates(data):
ret.append([i] + j)
return ret
# ここから書き始める
n, m = map(int, input().split())
d = [[INF for j in range(n)] for i in range(n)]
x = []
for i in range(m):
a, b, c = map(int, input().split())
x.append([a - 1, b - 1, c])
d[a - 1][b - 1] = c
d[b - 1][a - 1] = c
d2 = warshall_floyd(d, n)
# print(d2)
ans = 0
for i in x:
if d2[i[0]][i[1]] != i[2]:
ans += 1
print(ans)
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s914829603 | Accepted | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | # import numpy as np
N, M = map(int, input().split())
inf = 10**9
class Node:
def __init__(self, ix):
self.ix = ix # ノード番号
self.done = False # 確定ノードかどうか
self.pay = {} # 頂点番号:コストの一覧を容れる辞書
self.paid = -1 # ここに到達するための最小コスト(未定義なら-1)
self.prev = -1 # 最小コストを与える親ノード(未定義なら-1)
def __str__(self):
# デバッグ用
return "{} <- [{}] <- {}, done:{}, pay:{}".format(
self.ix, self.paid, self.prev, self.done, self.pay
)
# ノードのリストを生成
nodes = []
for i in range(N):
nodes.append(Node(i))
# エッジのリストを生成(これはこの問題用)
# edges = np.zeros((N,N), dtype=np.uint8)
edges = []
for _ in range(N):
edges.append([0] * N)
# エッジ情報を取得
# 全エッジを格納
# 注意: 標準入力は1-indexedだがここでは0-indexedに直す
for _ in range(M):
a, b, c = map(int, input().split())
nodes[a - 1].pay[b - 1] = c
nodes[b - 1].pay[a - 1] = c
edges[a - 1][b - 1] = 1
edges[b - 1][a - 1] = 1
# 出発ノードを0からN-1まで変化させる
for i in range(N):
##### DEBUG
# print('start node: {}'.format(i))
nodes[i].prev = i # 出発点の最良親を自分自身に
nodes[i].paid = 0 # 出発点のコストは0
nodes[i].done = True # 出発点は確定済み
n_done = 1 # 確定ノード数を1に
while n_done < N: # 全部確定するまで続行
to_conf_ix = -1 # 次に確定されるべきノード番号
to_conf_paid = 10**9 # そのコスト
for node in nodes:
# 確定ノードすべてに対して操作を行う
if node.done:
##### DEBUG
# print('confirmed parent: {}'.format(node.ix))
# 接続先を全列挙
for child in list(node.pay.keys()):
# その接続先が未確場合のみ進む定なら処理続行
if not nodes[child].done:
# その接続先の仮の最小コストと仮の親を更新
# まだ確定済みにはしない
newcost = node.paid + node.pay[child]
# 更新するための条件
flag = (nodes[child].paid < 0) or (newcost < nodes[child].paid)
##### DEBUG
# print('p{} -> c{}, prevcost={}, newcost={}'.format(node.ix, child, nodes[child].paid, newcost))
# 条件をみたせば接続先の情報を更新
# また次に確定されるノード候補の情報も更新
if flag:
nodes[child].paid = newcost
nodes[child].prev = node.ix
if newcost < to_conf_paid:
to_conf_paid = newcost
to_conf_ix = child
##### DEBUG
# print('to_conf: ix:{}, cost:{}'.format(to_conf_ix, to_conf_paid))
# 操作が完了したら現段階の候補ノードを確定させる
nodes[to_conf_ix].done = True
# 確定ノード数を1増やす
n_done += 1
##### DEBUG
# print('--- n_done: {} ---'.format(n_done))
# for j in range(N):
# print(nodes[j])
# print('------------------')
# 各ノードについてそれを親と連結するパスをedgeから削除
for j in range(N):
k = nodes[j].prev
edges[j][k], edges[k][j] = 0, 0
# 全ノードのpaid,prevをリセット
for j in range(N):
nodes[j].paid, nodes[j].prev = -1, -1
nodes[j].done = False
# 最後にedgesに残っているエッジの本数を出力
# print(int(np.sum(edges)//2)) # NumPy
ans = 0
for i in range(N):
ans += sum(edges[i])
print(ans // 2)
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s458656973 | Accepted | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | def main():
def dijkstra_back(s, t):
prev = [s] * n
d = [float("inf")] * n
used = [False] * n
d[s] = 0
while True:
v = -1
for i in range(n):
if (not used[i]) and (v == -1):
v = i
elif (not used[i]) and d[i] < d[v]:
v = i
if v == -1:
break
used[v] = True
for i in range(n):
if d[i] > d[v] + cost[v][i]:
d[i] = d[v] + cost[v][i]
prev[i] = v
path = [t]
while prev[t] != s:
path.append(prev[t])
prev[t] = prev[prev[t]]
path.append(s)
path = path[::-1]
return path
n, m = map(int, input().split())
route = [tuple(map(int, input().split())) for _ in range(m)]
INF = float("inf")
cost = [[INF for i in range(n)] for i in range(n)]
for i in route:
cost[i[0] - 1][i[1] - 1] = i[2]
cost[i[1] - 1][i[0] - 1] = i[2]
used_ways = set([])
for i in range(n):
for j in range(n):
if i < j:
way = dijkstra_back(i, j)
for k in range(len(way) - 1):
used_ways.add(tuple(sorted([way[k], way[k + 1]])))
route_set = set([])
for i in route:
route_set.add(tuple(sorted([i[0] - 1, i[1] - 1])))
print(len(route_set - used_ways))
if __name__ == "__main__":
main()
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the number of the edges in the graph that are not contained in any
shortest path between any pair of different vertices.
* * * | s827938268 | Runtime Error | p03837 | The input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M | N, M = map(int, input().split())
ABC = []
for i in range(M):
abc = tuple(map(int, input().split()))
ABC.append(abc)
# print(N, M, ABC)
max_len = 0
for abc in ABC:
max_len += abc[2]
def sub(a, b, d, d_min, ABC, path):
# print('sub', a, b, d, d_min, ABC, path)
for abc in ABC:
# print('sub', abc)
if abc[0] == a:
n_a = abc[1]
tmp_d = d + abc[2]
if tmp_d > d_min:
# print('exceed', d, d_min)
continue
if n_a == b:
path.append(n_a)
# print('found', tmp_d, path)
return tmp_d
tmp = [x for x in path]
tmp.append(n_a)
tmp_d = sub(n_a, b, tmp_d, d_min, ABC, tmp)
if tmp_d > d_min:
# print('exceed2', tmp_d, d_min)
continue
if abc[1] == a:
n_a = abc[0]
tmp_d = d + abc[2]
if tmp_d > d_min:
# print('exceed', tmp_d, d_min)
continue
if n_a == b:
path.append(n_a)
# print('found', tmp_d, path)
return tmp_d
tmp = [x for x in path]
tmp.append(n_a)
tmp_d = sub(n_a, b, tmp_d, d_min, ABC, tmp)
if tmp_d > d_min:
# print('exceed2', tmp_d, d_min)
continue
# print('not found')
path = []
return max_len
def shortest(a, b, ABC):
d_min = max_len
ans = []
for abc in ABC:
# print('shortest', a, b, abc)
if abc[0] == a:
n_a = abc[1]
d = abc[2]
path = [a, n_a]
if n_a == b and d <= d_min:
d_min = d
ans = [path]
continue
d = sub(n_a, b, d, d_min, ABC, path)
if d <= d_min:
# print('shortest, found', d, path)
d_min = d
ans = [path]
if d == d_min:
ans.append(path)
if abc[1] == a:
n_a = abc[0]
d = abc[2]
path = [a, n_a]
if n_a == b and d <= d_min:
d_min = d
ans = [path]
continue
d = sub(n_a, b, d, d_min, ABC, path)
if d < d_min:
# print('shortest, found', d, path)
d_min = d
ans = [path]
if d == d_min:
ans.append(path)
return ans
# print(shortest(1, 2, ABC))
# print(shortest(1, 3, ABC))
# print(shortest(2, 3, ABC))
s_paths = set()
for i in range(N):
for j in range(i + 1, N):
paths = shortest(i + 1, j + 1, ABC)
# print(i, j, paths)
for path in paths:
# print(path)
for k in range(len(path) - 1):
l = min(path[k], path[k + 1])
r = max(path[k], path[k + 1])
s_paths.add((l, r))
print(len(ABC) - len(s_paths))
| Statement
You are given an undirected connected weighted graph with N vertices and M
edges that contains neither self-loops nor double edges.
The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of
c_i.
Here, a _self-loop_ is an edge where a_i = b_i (1≤i≤M), and _double edges_ are
two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).
A _connected graph_ is a graph where there is a path between every pair of
different vertices.
Find the number of the edges that are not contained in any shortest path
between any pair of different vertices. | [{"input": "3 3\n 1 2 1\n 1 3 1\n 2 3 3", "output": "1\n \n\nIn the given graph, the shortest paths between all pairs of different vertices\nare as follows:\n\n * The shortest path from vertex 1 to vertex 2 is: vertex 1 \u2192 vertex 2, with the length of 1.\n * The shortest path from vertex 1 to vertex 3 is: vertex 1 \u2192 vertex 3, with the length of 1.\n * The shortest path from vertex 2 to vertex 1 is: vertex 2 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 2 to vertex 3 is: vertex 2 \u2192 vertex 1 \u2192 vertex 3, with the length of 2.\n * The shortest path from vertex 3 to vertex 1 is: vertex 3 \u2192 vertex 1, with the length of 1.\n * The shortest path from vertex 3 to vertex 2 is: vertex 3 \u2192 vertex 1 \u2192 vertex 2, with the length of 2.\n\nThus, the only edge that is not contained in any shortest path, is the edge of\nlength 3 connecting vertex 2 and vertex 3, hence the output should be 1.\n\n* * *"}, {"input": "3 2\n 1 2 1\n 2 3 1", "output": "0\n \n\nEvery edge is contained in some shortest path between some pair of different\nvertices."}] |
Print the maximum number of integers that Snuke can circle.
* * * | s067565302 | Wrong Answer | p04022 | The input is given from Standard Input in the following format:
N
s_1
:
s_N | """
Rを立法数とする
a * R と a**2 * R は片方だけ取れる
→Rを取り除いて後はDP
どうやって立法数を取り除く?
10**3.3まで試し割り?→5secだから間に合うかなぁ
"""
N = int(input())
mul3s = []
i = 2
while i**3 <= 10**10:
mul3s.append(i**3)
i += 1
div3 = []
dic = {}
div2 = []
for i in range(N):
s = int(input())
for j in mul3s:
while s % j == 0:
s //= j
if s < j:
break
if s == 1:
div3.append(s)
elif s not in dic:
dic[s] = 1
div2.append(s)
else:
dic[s] += 1
div2.sort()
pdic = {}
dpdic = {}
for i in div2:
if (int(i**0.5) ** 2 == i and int(i**0.5) not in dic) or int(i**0.5) ** 2 != i:
dpdic[i] = [dic[i]]
pdic[i] = i
else:
dpdic[pdic[int(i**0.5)]].append(dic[i])
pdic[i] = pdic[int(i**0.5)]
# print (dpdic)
ans = min(1, len(div3))
for nlis in dpdic:
dp = [0] * 2 # 0=前の奴を使ってない 1=使った
for i in dpdic[nlis]:
ndp = [0] * 2
ndp[0] = max(dp[0], dp[1])
ndp[1] = dp[0] + i
dp = ndp
ans += max(dp)
print(ans)
| Statement
Snuke got positive integers s_1,...,s_N from his mother, as a birthday
present. There may be duplicate elements.
He will circle some of these N integers. Since he dislikes cubic numbers, he
wants to ensure that if both s_i and s_j (i ≠ j) are circled, the product
s_is_j is _not_ cubic. For example, when s_1=1,s_2=1,s_3=2,s_4=4, it is not
possible to circle both s_1 and s_2 at the same time. It is not possible to
circle both s_3 and s_4 at the same time, either.
Find the maximum number of integers that Snuke can circle. | [{"input": "8\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8", "output": "6\n \n\nSnuke can circle 1,2,3,5,6,7.\n\n* * *"}, {"input": "6\n 2\n 4\n 8\n 16\n 32\n 64", "output": "3\n \n\n* * *"}, {"input": "10\n 1\n 10\n 100\n 1000000007\n 10000000000\n 1000000009\n 999999999\n 999\n 999\n 999", "output": "9"}] |
Print the maximum number of integers that Snuke can circle.
* * * | s118322090 | Wrong Answer | p04022 | The input is given from Standard Input in the following format:
N
s_1
:
s_N | def get_sieve_of_eratosthenes_new(n):
import math
if not isinstance(n, int):
raise TypeError("n is int type.")
if n < 2:
raise ValueError("n is more than 2")
prime = []
limit = math.sqrt(n)
data = [i + 1 for i in range(1, n)]
while True:
p = data[0]
if limit <= p:
return prime + data
prime.append(p)
data = [e for e in data if e % p != 0]
prime = get_sieve_of_eratosthenes_new(2160)
def ind(b, n):
res = 0
while n % b == 0:
res += 1
n //= b
return res
import sys
input = sys.stdin.readline
N = int(input())
dic = {}
inverse = {}
for i in range(N):
s = int(input())
S = s**2
for p in prime:
a = ind(p, s)
s //= p ** (a - a % 3)
S //= p ** (2 * a - (2 * a) % 3)
if s not in dic:
dic[s] = 0
inverse[s] = 0
dic[s] += 1
inverse[s] = S
one = 0
double = 0
for i in dic:
if i != 1:
if inverse[i] in dic:
double += max(dic[i], dic[inverse[i]])
else:
one += dic[i]
double //= 2
ans = one + double
if 1 in dic:
ans += 1
print(ans)
| Statement
Snuke got positive integers s_1,...,s_N from his mother, as a birthday
present. There may be duplicate elements.
He will circle some of these N integers. Since he dislikes cubic numbers, he
wants to ensure that if both s_i and s_j (i ≠ j) are circled, the product
s_is_j is _not_ cubic. For example, when s_1=1,s_2=1,s_3=2,s_4=4, it is not
possible to circle both s_1 and s_2 at the same time. It is not possible to
circle both s_3 and s_4 at the same time, either.
Find the maximum number of integers that Snuke can circle. | [{"input": "8\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8", "output": "6\n \n\nSnuke can circle 1,2,3,5,6,7.\n\n* * *"}, {"input": "6\n 2\n 4\n 8\n 16\n 32\n 64", "output": "3\n \n\n* * *"}, {"input": "10\n 1\n 10\n 100\n 1000000007\n 10000000000\n 1000000009\n 999999999\n 999\n 999\n 999", "output": "9"}] |
Print the maximum number of integers that Snuke can circle.
* * * | s701186765 | Wrong Answer | p04022 | The input is given from Standard Input in the following format:
N
s_1
:
s_N | def eratosthenes(n):
isp = [True] * (n + 1)
for i in range(2, n):
if i * i > n:
break
if isp[i]:
for i in range(i * 2, n + 1, i):
isp[i] = False
return [i for i in range(2, n + 1) if isp[i]]
MAX = 10**10 + 10
MAX2 = int(MAX ** (1 / 2))
MAX3 = int(MAX ** (1 / 3))
prime = eratosthenes(MAX3)
cubic = [i**3 for i in range(MAX2)]
def normalize(n):
for p in prime:
while n % cubic[p] == 0:
n //= cubic[p]
return n
def main():
N = int(input())
A = [int(input()) for _ in range(N)]
res = 0
mp = dict()
for j, i in enumerate(A):
i_norm = normalize(i)
if i_norm == 1:
res += 1
else:
if i_norm in mp:
mp[i_norm] += 1
else:
mp[i_norm] = 1
if res > 0:
res = 1
st = set()
for k, v in mp.items():
if k in st:
continue
st.add(k)
k_rev = normalize(k**2)
if k_rev in mp:
res += max(v, mp[k_rev])
st.add(k_rev)
else:
res += v
print(res)
if __name__ == "__main__":
main()
| Statement
Snuke got positive integers s_1,...,s_N from his mother, as a birthday
present. There may be duplicate elements.
He will circle some of these N integers. Since he dislikes cubic numbers, he
wants to ensure that if both s_i and s_j (i ≠ j) are circled, the product
s_is_j is _not_ cubic. For example, when s_1=1,s_2=1,s_3=2,s_4=4, it is not
possible to circle both s_1 and s_2 at the same time. It is not possible to
circle both s_3 and s_4 at the same time, either.
Find the maximum number of integers that Snuke can circle. | [{"input": "8\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8", "output": "6\n \n\nSnuke can circle 1,2,3,5,6,7.\n\n* * *"}, {"input": "6\n 2\n 4\n 8\n 16\n 32\n 64", "output": "3\n \n\n* * *"}, {"input": "10\n 1\n 10\n 100\n 1000000007\n 10000000000\n 1000000009\n 999999999\n 999\n 999\n 999", "output": "9"}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s122241735 | Runtime Error | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | # ABC179-D Leaping Tak
goalN, shugosuK = map(int, input().strip().split(" "))
# print(goalN, shugosuK)
shugo = []
wa = []
for i in range(shugosuK):
shugo = list(map(int, input().strip().split(" ")))
# print('shugo', shugo)
wa = wa + shugo
# print('wa', wa)
# wa = set(wa)
# print(wa)
wa = list(set(wa))
# print(wa)
l = len(wa)
def dfs(pos, cnt):
for i in range(l):
newpos = pos + wa[i]
if newpos == goalN:
pos = newpos
cnt += 1
return cnt
elif newpos > goalN:
pos = newpos
return cnt
elif newpos < goalN:
pos = newpos
dfs(pos, cnt)
cnt = dfs(1, 0)
cnt = cnt % 998244353
print(cnt)
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s105162456 | Accepted | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | n, k = map(int, input().split())
l = [list(map(int, input().split())) for i in range(k)]
x = [0] * (n + 1)
x[0] = 1
l.sort()
t = 0
for i in range(1, n + 1):
for j in range(k):
if i - l[j][1] > 0:
t += x[i - l[j][0]] - x[i - l[j][1] - 1]
elif i - l[j][0] >= 0:
t += x[i - l[j][0]]
t = t % 998244353
x[i] = t
print(x[n - 1])
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s050181106 | Runtime Error | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | def dfs(q, here, result):
# print('q,here1: ', q, here, result)
if len(q) == 0:
print(result % 998244353)
return result
for i in num:
# print('i, here: ', i, here)
if i + here <= n:
q.append(i + here)
else:
break
# print('q,here2,result: ', q, here, result)
here = q.pop()
if here == n:
result += 1
dfs(q, here, result)
from collections import deque
n, k = (int(each) for each in input().split())
lr = []
global result
global num
global q
result = 0
num = []
for each in range(k):
lr = [int(each) for each in input().split()]
for i in range(lr[0], lr[1] + 1):
num.append(i)
q = deque([1])
dfs(q, 1, result)
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s208312931 | Runtime Error | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | N = int(input())
ans = 0
for i in range(1, N + 1):
for j in range(1, N + 1):
if i * j <= N - 1:
ans += 1
else:
break
print(ans)
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s873181011 | Runtime Error | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | n = int(input())
count = 0
for i in range(1, 1000):
print(i)
for j in range(1, 1000):
print(j)
if (i * j) >= n:
count += j - 1
break
print(count)
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s235706844 | Accepted | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | n, k = map(int,input().split())
lrl = []
for _ in range(k):
lrl.append(list(map(int,input().split())))
N = 2 * n
# N: 処理する区間の長さ
data0 = [0]*(N+1)
data1 = [0]*(N+1)
mod = 998244353
# 区間[l, r)に x を加算
def _add(data, k, x):
while k <= N:
x %= mod
data[k] += x
data[k] %= mod
k += k & -k
def add(l, r, x):
_add(data0, l, -x*(l-1)%mod)
_add(data0, r, x*(r-1)%mod)
_add(data1, l, x)
_add(data1, r, -x)
# 区間[l, r)の和を求める
def _get(data, k):
s = 0
while k:
s += data[k]
s %= mod
k -= k & -k
return s
def query(l, r):
return _get(data1, r-1) * (r-1) + _get(data0, r-1) - _get(data1, l-1) * (l-1) - _get(data0, l-1)
add(1, 2, 1)
for i in range(n):
now = query(i+1, i+2)
for l, r in lrl:
add(l+i+1, r+i+2, now % mod)
print(query(n, n+1) % mod)
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s583638603 | Wrong Answer | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | import sys
INF = 1 << 60
MOD = 998244353
sys.setrecursionlimit(2147483647)
input = lambda: sys.stdin.readline().rstrip()
class SegmentTree(object):
def __init__(self, A, dot, unit):
n = 1 << (len(A) - 1).bit_length()
tree = [unit] * (2 * n)
for i, v in enumerate(A):
tree[i + n] = v
for i in range(n - 1, 0, -1):
tree[i] = dot(tree[i << 1], tree[i << 1 | 1])
self._n = n
self._tree = tree
self._dot = dot
self._unit = unit
def __getitem__(self, i):
return self._tree[i + self._n]
def update(self, i, v):
i += self._n
self._tree[i] = v
while i != 1:
i >>= 1
self._tree[i] = self._dot(self._tree[i << 1], self._tree[i << 1 | 1])
def add(self, i, v):
self.update(i, self[i] + v)
def sum(self, l, r):
l += self._n
r += self._n
l_val = r_val = self._unit
while l < r:
if l & 1:
l_val = self._dot(l_val, self._tree[l])
l += 1
if r & 1:
r -= 1
r_val = self._dot(self._tree[r], r_val)
l >>= 1
r >>= 1
return self._dot(l_val, r_val)
def resolve():
n, k = map(int, input().split())
tree = SegmentTree([0] * n, lambda x, y: (x + y) % MOD, 0)
tree.update(0, 1)
D = [tuple(map(int, input().split())) for _ in range(k)]
for i in range(1, n):
for l, r in D: # [i - r, i - l]
if i - l >= 0:
tree.add(i, tree.sum(i - r, i - l + 1))
print(tree[n - 1] % MOD)
resolve()
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s132828078 | Wrong Answer | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | n, k = input().split()
n = int(n)
k = min(int(k), 10)
s = []
for j in range(k):
ins = input().split()
s.append(int(ins[0]))
s.append(int(ins[1]))
s = list(set(s))
ans = [0] * (n + 1)
ans[1] = 1
m = 998244353
for j in range(2, n + 1):
for k in s:
if k >= j:
pass
else:
ans[j] = (ans[j] % m + ans[j - k] % m) % m
print(ans[-1] % m)
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s095996324 | Accepted | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | MOD = 998244353
class SegmentTree:
def __init__(self, a):
self.padding = 0
self.n = len(a)
self.N = 2 ** (self.n-1).bit_length()
self.seg_data = [self.padding]*(self.N-1) + a + [self.padding]*(self.N-self.n)
for i in range(2*self.N-2, 0, -2):
self.seg_data[(i-1)//2] = self.seg_data[i] + self.seg_data[i-1]
def __len__(self):
return self.n
def update(self, i, x):
idx = self.N - 1 + i
self.seg_data[idx] += x
self.seg_data[idx] %= MOD
while idx:
idx = (idx-1) // 2
self.seg_data[idx] = (self.seg_data[2*idx+1] + self.seg_data[2*idx+2]) % MOD
def query(self, i, j):
# [i, j)
if i == j:
return self.seg_data[self.N - 1 + i] % MOD
else:
idx1 = self.N - 1 + i
idx2 = self.N - 2 + j # 閉区間にする
result = self.padding
while idx1 < idx2 + 1:
if idx1&1 == 0: # idx1が偶数
result = (result + self.seg_data[idx1]) % MOD
if idx2&1 == 1: # idx2が奇数
result = (result + self.seg_data[idx2]) % MOD
idx2 -= 1
idx1 //= 2
idx2 = (idx2 - 1)//2
return result
N, K = map(int, input().split())
LR = [tuple(map(int, input().split())) for i in range(K)]
a = [0] * (N+1)
a[1] = 1
dp = SegmentTree(a)
for i in range(2, N+1):
for l, r in LR:
ll = max(0, i - l)
rr = max(0, i - r)
dp.update(i, dp.query(rr, ll+1))
print(dp.query(N, N+1)) | Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s022935718 | Accepted | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | import sys
input = sys.stdin.readline
N, K = map(int, input().split())
LR = [list(map(int, input().split())) for _ in range(K)]
P = 998244353
class SegmentTree:
def __init__(self, n, segfunc=min, ele=10**10):
self.ide_ele = ele
self.num = pow(2, (n - 1).bit_length())
self.seg = [self.ide_ele] * 2 * self.num
self.segfunc = segfunc
def init(self, init_val):
# set_val
for i in range(len(init_val)):
self.seg[i + self.num - 1] = init_val[i]
# built
for i in range(self.num - 2, -1, -1):
self.seg[i] = self.segfunc(self.seg[2 * i + 1], self.seg[2 * i + 2])
def update(self, k, x):
k += self.num - 1
self.seg[k] = x
while k:
k = (k - 1) // 2
self.seg[k] = self.segfunc(self.seg[k * 2 + 1], self.seg[k * 2 + 2])
def query(self, p, q):
if q <= p:
return self.ide_ele
p += self.num - 1
q += self.num - 2
res = self.ide_ele
while q - p > 1:
if p & 1 == 0:
res = self.segfunc(res, self.seg[p])
if q & 1 == 1:
res = self.segfunc(res, self.seg[q])
q -= 1
p = p // 2
q = (q - 1) // 2
if p == q:
res = self.segfunc(res, self.seg[p])
else:
res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
return res
dp = SegmentTree(N, segfunc=lambda x, y: x + y % P, ele=0)
dp.update(0, 1)
for i in range(1, N):
tmp = 0
for l, r in LR:
tmp = (tmp + dp.query(max(0, i - r), max(0, i - l + 1))) % P
dp.update(i, tmp)
print(dp.seg[N - 1 + dp.num - 1])
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s085529293 | Accepted | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
def solve():
MOD = 998244353
def makeBIT(numEle):
numPow2 = 2 ** (numEle-1).bit_length()
data = [0] * (numPow2+1)
return data, numPow2
def setInit(As):
for iB, A in enumerate(As, 1):
data[iB] = A
for iB in range(1, numPow2):
i = iB + (iB & -iB)
data[i] += data[iB]
def addValue(iA, A):
iB = iA + 1
while iB <= numPow2:
data[iB] += A
iB += iB & -iB
def getSum(iA):
iB = iA + 1
ans = 0
while iB > 0:
ans += data[iB]
iB -= iB & -iB
return ans
def getRangeSum(iFr, iTo):
return getSum(iTo) - getSum(iFr-1)
N, K = map(int, input().split())
LRs = [tuple(map(int, input().split())) for _ in range(K)]
data, numPow2 = makeBIT(N)
addValue(0, 1)
for i in range(1, N):
v = 0
for L, R in LRs:
x, y = i-R, i-L
if y < 0:
continue
if x < 0:
x = 0
v += getRangeSum(x, y) % MOD
v %= MOD
addValue(i, v)
ans = getRangeSum(N-1, N-1) % MOD
print(ans)
solve()
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s127998794 | Wrong Answer | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | N, K = map(int, input().split(" "))
a = []
d = []
e = []
for k in range(K):
l, r = map(int, input().split(" "))
d.append(l)
e.append(r)
d.sort()
e.sort()
for k in range(K):
a += list(range(d[k], e[k] + 1))
a.sort()
b = [0 for i in range(a[-1] - 1)]
b.append(1)
for i in range(N - 1 - a[0]):
b.append(0)
for j in a:
b[-1] += b[-j - 1]
for i in range(a[0]):
b.append(0)
for j in a:
b[-1] += b[-j - 1]
print(b[-1] % 998244353)
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo
998244353.
* * * | s061184792 | Accepted | p02549 | Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K | import sys
readline = sys.stdin.readline
import sys
readline = sys.stdin.readline
MOD = 998244353
def frac(limit):
frac = [1] * limit
for i in range(2, limit):
frac[i] = i * frac[i - 1] % MOD
fraci = [None] * limit
fraci[-1] = pow(frac[-1], MOD - 2, MOD)
for i in range(-2, -limit - 1, -1):
fraci[i] = fraci[i + 1] * (limit + i + 1) % MOD
return frac, fraci
frac, fraci = frac(1341398)
pr = 3
LS = 20
class NTT:
def __init__(self):
self.N0 = 1 << LS
omega = pow(pr, (MOD - 1) // self.N0, MOD)
omegainv = pow(omega, MOD - 2, MOD)
self.w = [0] * (self.N0 // 2)
self.winv = [0] * (self.N0 // 2)
self.w[0] = 1
self.winv[0] = 1
for i in range(1, self.N0 // 2):
self.w[i] = (self.w[i - 1] * omega) % MOD
self.winv[i] = (self.winv[i - 1] * omegainv) % MOD
used = set()
for i in range(self.N0 // 2):
if i in used:
continue
j = 0
for k in range(LS - 1):
j |= (i >> k & 1) << (LS - 2 - k)
used.add(j)
self.w[i], self.w[j] = self.w[j], self.w[i]
self.winv[i], self.winv[j] = self.winv[j], self.winv[i]
def _fft(self, A):
M = len(A)
bn = 1
hbs = M >> 1
while hbs:
for j in range(hbs):
A[j], A[j + hbs] = A[j] + A[j + hbs], A[j] - A[j + hbs]
if A[j] > MOD:
A[j] -= MOD
if A[j + hbs] < 0:
A[j + hbs] += MOD
for bi in range(1, bn):
wi = self.w[bi]
for j in range(bi * hbs * 2, bi * hbs * 2 + hbs):
A[j], A[j + hbs] = (A[j] + wi * A[j + hbs]) % MOD, (
A[j] - wi * A[j + hbs]
) % MOD
bn <<= 1
hbs >>= 1
def _ifft(self, A):
M = len(A)
bn = M >> 1
hbs = 1
while bn:
for j in range(hbs):
A[j], A[j + hbs] = A[j] + A[j + hbs], A[j] - A[j + hbs]
if A[j] > MOD:
A[j] -= MOD
if A[j + hbs] < 0:
A[j + hbs] += MOD
for bi in range(1, bn):
winvi = self.winv[bi]
for j in range(bi * hbs * 2, bi * hbs * 2 + hbs):
A[j], A[j + hbs] = (A[j] + A[j + hbs]) % MOD, winvi * (
A[j] - A[j + hbs]
) % MOD
bn >>= 1
hbs <<= 1
def convolve(self, A, B):
LA = len(A)
LB = len(B)
LC = LA + LB - 1
M = 1 << (LC - 1).bit_length()
A += [0] * (M - LA)
B += [0] * (M - LB)
self._fft(A)
self._fft(B)
C = [0] * M
for i in range(M):
C[i] = A[i] * B[i] % MOD
self._ifft(C)
minv = pow(M, MOD - 2, MOD)
for i in range(LC):
C[i] = C[i] * minv % MOD
return C[:LC]
return C
def inverse(self, A):
LA = len(A)
dep = (LA - 1).bit_length()
M = 1 << dep
A += [0] * (M - LA)
g = [pow(A[0], MOD - 2, MOD)]
for n in range(dep):
dl = 1 << (n + 1)
f = A[:dl]
fg = self.convolve(f, g[:])[:dl]
fgg = self.convolve(fg, g[:])[:dl]
ng = [None] * dl
for i in range(dl // 2):
ng[i] = (2 * g[i] - fgg[i]) % MOD
for i in range(dl // 2, dl):
ng[i] = MOD - fgg[i]
g = ng[:]
return g[:LA]
def integral(self, A):
A = [1] + [A[i] * fraci[i + 2] % MOD for i in range(len(A))]
N, K = map(int, readline().split())
A = [0] * (N + 2)
for _ in range(K):
l, r = map(int, readline().split())
A[l] += 1
A[r + 1] -= 1
for i in range(1, N + 1):
A[i] += A[i - 1]
A = A[:-1]
A[0] -= 1
A = [-a % MOD for a in A]
NN = NTT()
print(NN.inverse(A[:])[N - 1] % MOD)
| Statement
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to
right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach
Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-
intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the
union of these K segments. Here, the segment [l, r] denotes the set consisting
of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353. | [{"input": "5 2\n 1 1\n 3 4", "output": "4\n \n\nThe set S is the union of the segment [1, 1] and the segment [3, 4], therefore\nS = \\\\{ 1, 3, 4 \\\\} holds.\n\nThere are 4 possible ways to get to Cell 5:\n\n * 1 \\to 2 \\to 3 \\to 4 \\to 5,\n * 1 \\to 2 \\to 5,\n * 1 \\to 4 \\to 5 and\n * 1 \\to 5.\n\n* * *"}, {"input": "5 2\n 3 3\n 5 5", "output": "0\n \n\nBecause S = \\\\{ 3, 5 \\\\} holds, you cannot reach to Cell 5. Print 0.\n\n* * *"}, {"input": "5 1\n 1 2", "output": "5\n \n\n* * *"}, {"input": "60 3\n 5 8\n 1 3\n 10 15", "output": "221823067\n \n\nNote that you have to print the answer modulo 998244353."}] |
Print the minimum number of seconds required to achieve the objective.
* * * | s835672228 | Wrong Answer | p03358 | Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N-1} y_{N-1}
c_1c_2..c_N | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
data = read().split()
m = map(int, data[:-1])
XY = zip(m, m)
C = [0] + [1 * (x == ord("W")) for x in data[-1]]
graph = [set() for _ in range(N + 1)]
for x, y in XY:
graph[x].add(y)
graph[y].add(x)
deg = [len(x) for x in graph]
b_leaf = [i for i in range(N + 1) if deg[i] == 1 and not C[i]]
while b_leaf:
x = b_leaf.pop()
for y in graph[x]:
graph[y].remove(x)
deg[y] -= 1
if deg[y] == 1 and not C[y]:
b_leaf.append(y)
deg[x] = 0
graph[x].clear()
V = set(i for i, E in enumerate(graph) if E)
if len(V) <= 2:
print(len(V))
exit()
root = None
for v in V:
if deg[v] > 1:
root = v
break
parent = [0] * (N + 1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
"""
・Euler tourの状態から、パスをひとつ除く
・葉と葉を結ぶとしてよい。通ると2コスト安くなる点がある
"""
for i in range(N + 1):
C[i] ^= 1 & deg[i]
cost_full = sum(deg) + sum(C)
# C[i] == 1 となる i を最もたくさん含むパスを探す
opt = 0
dp = [0] * (N + 1)
for v in order[::-1]:
if deg[v] == 1:
continue
arr = sorted((dp[w] for w in graph[v] if w != parent[v]), reverse=True) + [0]
x = arr[0] + arr[1] + C[v]
if opt < x:
opt = x
dp[v] = arr[0] + C[v]
answer = cost_full - 2 * opt
print(answer)
| Statement
There is a tree with N vertices numbered 1 through N. The i-th edge connects
Vertex x_i and y_i. Each vertex is painted white or black. The initial color
of Vertex i is represented by a letter c_i. c_i = `W` represents the vertex is
white; c_i = `B` represents the vertex is black.
A cat will walk along this tree. More specifically, she performs one of the
following in one second repeatedly:
* Choose a vertex that is adjacent to the vertex where she is currently, and move to that vertex. Then, invert the color of the destination vertex.
* Invert the color of the vertex where she is currently.
The cat's objective is to paint all the vertices black. She may start and end
performing actions at any vertex. At least how many seconds does it takes for
the cat to achieve her objective? | [{"input": "5\n 1 2\n 2 3\n 2 4\n 4 5\n WBBWW", "output": "5\n \n\nThe objective can be achieved in five seconds, for example, as follows:\n\n * Start at Vertex 1. Change the color of Vertex 1 to black.\n * Move to Vertex 2, then change the color of Vertex 2 to white.\n * Change the color of Vertex 2 to black.\n * Move to Vertex 4, then change the color of Vertex 4 to black.\n * Move to Vertex 5, then change the color of Vertex 5 to black.\n\n* * *"}, {"input": "6\n 3 1\n 4 5\n 2 6\n 6 1\n 3 4\n WWBWBB", "output": "7\n \n\n* * *"}, {"input": "1\n B", "output": "0\n \n\n* * *"}, {"input": "20\n 2 19\n 5 13\n 6 4\n 15 6\n 12 19\n 13 19\n 3 11\n 8 3\n 3 20\n 16 13\n 7 14\n 3 17\n 7 8\n 10 20\n 11 9\n 8 18\n 8 2\n 10 1\n 6 13\n WBWBWBBWWWBBWWBBBBBW", "output": "21"}] |
Print the minimum number of seconds required to achieve the objective.
* * * | s689394433 | Wrong Answer | p03358 | Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N-1} y_{N-1}
c_1c_2..c_N | input = __import__("sys").stdin.readline
MIS = lambda: map(int, input().split())
n = int(input())
adj = [set() for i in range(n + 1)]
white = [False]
for i in range(n - 1):
a, b = MIS()
adj[a].add(b)
adj[b].add(a)
s = input().rstrip()
for i in range(n):
white.append(s[i] == "W")
# Corner cases
if sum(white) <= 1:
print(sum(white))
exit()
# Remove black leaves
stack = [i for i in range(1, n + 1) if len(adj[i]) == 1 and not white[i]]
while stack:
p = stack.pop()
pa = min(adj[p])
adj[pa].remove(p)
adj[p].clear()
if len(adj[pa]) == 1 and not white[pa]:
stack.append(pa)
# Simulate Euler tour
root = 1
while not adj[root]:
root += 1
tadj = [[] for i in range(n + 1)]
vis = [False] * (n + 1)
vis[root] = True
stack = [root]
while stack:
p = stack.pop()
for q in adj[p]:
if vis[q]:
continue
vis[q] = True
tadj[p].append(q)
stack.append(q)
for i in range(1, n + 1):
if adj[i] and len(tadj[i]) % 2 == 0:
white[i] = not white[i]
white[root] = not white[root]
# Diameter
def bfs(v):
stack = [v]
dist = [-1] * (n + 1)
dist[v] = white[v]
while stack:
p = stack.pop()
for q in adj[p]:
if dist[q] != -1:
continue
dist[q] = dist[p] + white[q]
stack.append(q)
return dist
numedge = sum(map(len, adj))
d1 = bfs(root)
u = d1.index(max(d1))
d2 = bfs(u)
diam = max(d2)
print(numedge - diam)
| Statement
There is a tree with N vertices numbered 1 through N. The i-th edge connects
Vertex x_i and y_i. Each vertex is painted white or black. The initial color
of Vertex i is represented by a letter c_i. c_i = `W` represents the vertex is
white; c_i = `B` represents the vertex is black.
A cat will walk along this tree. More specifically, she performs one of the
following in one second repeatedly:
* Choose a vertex that is adjacent to the vertex where she is currently, and move to that vertex. Then, invert the color of the destination vertex.
* Invert the color of the vertex where she is currently.
The cat's objective is to paint all the vertices black. She may start and end
performing actions at any vertex. At least how many seconds does it takes for
the cat to achieve her objective? | [{"input": "5\n 1 2\n 2 3\n 2 4\n 4 5\n WBBWW", "output": "5\n \n\nThe objective can be achieved in five seconds, for example, as follows:\n\n * Start at Vertex 1. Change the color of Vertex 1 to black.\n * Move to Vertex 2, then change the color of Vertex 2 to white.\n * Change the color of Vertex 2 to black.\n * Move to Vertex 4, then change the color of Vertex 4 to black.\n * Move to Vertex 5, then change the color of Vertex 5 to black.\n\n* * *"}, {"input": "6\n 3 1\n 4 5\n 2 6\n 6 1\n 3 4\n WWBWBB", "output": "7\n \n\n* * *"}, {"input": "1\n B", "output": "0\n \n\n* * *"}, {"input": "20\n 2 19\n 5 13\n 6 4\n 15 6\n 12 19\n 13 19\n 3 11\n 8 3\n 3 20\n 16 13\n 7 14\n 3 17\n 7 8\n 10 20\n 11 9\n 8 18\n 8 2\n 10 1\n 6 13\n WBWBWBBWWWBBWWBBBBBW", "output": "21"}] |
Print the number of possible candidates of the value of Nukes's integer.
* * * | s668132130 | Wrong Answer | p03708 | The input is given from Standard Input in the following format:
A
B | a = input()
b = input()
a = int(a)
b = int(b)
print(a - b)
| Statement
Nukes has an integer that can be represented as the bitwise OR of one or more
integers between A and B (inclusive). How many possible candidates of the
value of Nukes's integer there are? | [{"input": "7\n 9", "output": "4\n \n\nIn this case, A=7 and B=9. There are four integers that can be represented as\nthe bitwise OR of a non-empty subset of {7, 8, 9}: 7, 8, 9 and 15.\n\n* * *"}, {"input": "65\n 98", "output": "63\n \n\n* * *"}, {"input": "271828182845904523\n 314159265358979323", "output": "68833183630578410"}] |
Print the number of possible candidates of the value of Nukes's integer.
* * * | s180655330 | Wrong Answer | p03708 | The input is given from Standard Input in the following format:
A
B | a, b = int(input()), int(input())
print(a + 1)
| Statement
Nukes has an integer that can be represented as the bitwise OR of one or more
integers between A and B (inclusive). How many possible candidates of the
value of Nukes's integer there are? | [{"input": "7\n 9", "output": "4\n \n\nIn this case, A=7 and B=9. There are four integers that can be represented as\nthe bitwise OR of a non-empty subset of {7, 8, 9}: 7, 8, 9 and 15.\n\n* * *"}, {"input": "65\n 98", "output": "63\n \n\n* * *"}, {"input": "271828182845904523\n 314159265358979323", "output": "68833183630578410"}] |
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on
Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If
there are multiple ways to achieve the maximum score, any of them will be
accepted.
* * * | s103895844 | Accepted | p03026 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N | # m-solutions2019D - Maximum Sum of Minimum
def bfs(start: int) -> None:
q = [start]
nodes[start] = C.pop()
while q:
v = q.pop(0)
for u in T[v]:
if not nodes[u]:
nodes[u] = C.pop()
q.append(u)
def main():
# adjacent edges should have close numbers as much as possible -> sort, bfs
global T, C, nodes
N, *ABC = map(int, open(0).read().split())
AB, C = ABC[:-N], ABC[-N:]
C.sort()
T = [[] for _ in range(N + 1)]
for v, u in zip(*[iter(AB)] * 2):
T[v].append(u), T[u].append(v)
score, nodes = sum(C) - C[-1], [0] * (N + 1) # max of C will not be used
for i, t in enumerate(T[1:], 1):
if len(t) == 1:
start = i # start from any node with degree 1
break
bfs(start)
print(score)
print(*nodes[1:])
if __name__ == "__main__":
main()
| Statement
You are given a tree with N vertices 1,2,\ldots,N, and positive integers
c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects
Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our _score_
as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on
one vertex in T, and show one way to achieve it. If an integer occurs multiple
times in c_1,c_2,\ldots,c_N, we must use it that number of times. | [{"input": "5\n 1 2\n 2 3\n 3 4\n 4 5\n 1 2 3 4 5", "output": "10\n 1 2 3 4 5\n \n\nIf we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written\non the four edges will be 1,2,3,4, for the score of 10. This is the maximum\npossible score.\n\n* * *"}, {"input": "5\n 1 2\n 1 3\n 1 4\n 1 5\n 3141 59 26 53 59", "output": "197\n 59 26 3141 59 53\n \n\nc_1,c_2,\\ldots,c_N may not be pairwise distinct."}] |
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on
Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If
there are multiple ways to achieve the maximum score, any of them will be
accepted.
* * * | s772320408 | Wrong Answer | p03026 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N | # ナイーブに書く
N = int(input())
conn = [[0, 0] for _ in range(N)] # 加算していくので、list内包表記で定義
edge = []
write = [0] * N
score = [0] * (N - 1)
# edgeの受け取り
for i in range(N - 1):
conn[i][0] = i
a, b = map(int, input().split())
edge.append((a - 1, b - 1))
conn[a - 1][1] += 1
conn[b - 1][1] += 1
conn[N - 1][0] += N - 1
# 整数の格納、降順ソート
num = list(map(int, input().split()))
num.sort(reverse=True)
# 接続数で降順ソート
conn.sort(key=lambda x: x[1], reverse=True)
# 接続数の多い順に値を格納
for i, c in enumerate(conn):
write[c[0]] = num[i]
# スコア計算
for i, (a, b) in enumerate(edge):
score[i] = min(write[a], write[b])
# 結果の出力
print(sum(score))
print(" ".join([str(i) for i in write]))
| Statement
You are given a tree with N vertices 1,2,\ldots,N, and positive integers
c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects
Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our _score_
as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on
one vertex in T, and show one way to achieve it. If an integer occurs multiple
times in c_1,c_2,\ldots,c_N, we must use it that number of times. | [{"input": "5\n 1 2\n 2 3\n 3 4\n 4 5\n 1 2 3 4 5", "output": "10\n 1 2 3 4 5\n \n\nIf we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written\non the four edges will be 1,2,3,4, for the score of 10. This is the maximum\npossible score.\n\n* * *"}, {"input": "5\n 1 2\n 1 3\n 1 4\n 1 5\n 3141 59 26 53 59", "output": "197\n 59 26 3141 59 53\n \n\nc_1,c_2,\\ldots,c_N may not be pairwise distinct."}] |
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on
Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If
there are multiple ways to achieve the maximum score, any of them will be
accepted.
* * * | s744966431 | Accepted | p03026 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N | # maximum sum of minimum
n = int(input())
node = {i: [] for i in range(n + 1)}
visited = [False for i in range(n + 1)]
# 尋ねたことがあるかどうか確認するためのリスト
first = 0
for _ in range(n - 1):
a, b = map(int, input().split())
node[a].append(b)
node[b].append(a)
if _ == 0:
first += a
dictionary = [0 for i in range(n + 1)]
# 答を格納するためのリスト
clist = list(map(int, input().split()))
clist = sorted(clist, reverse=True)
counter = 0
dictionary[first] = clist[0]
K = sum(clist[1:])
from collections import deque
d = deque()
e = deque()
d.append(first)
visited[first] = True
while d:
for some in d:
for point in node[some]:
if visited[point] == False:
# まだ訪れたことのない頂点にあった場合
counter += 1
visited[point] = True
dictionary[point] = clist[counter]
e.append(point)
else:
pass
d = e
e = deque()
print(K)
print(*dictionary[1:])
| Statement
You are given a tree with N vertices 1,2,\ldots,N, and positive integers
c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects
Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our _score_
as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on
one vertex in T, and show one way to achieve it. If an integer occurs multiple
times in c_1,c_2,\ldots,c_N, we must use it that number of times. | [{"input": "5\n 1 2\n 2 3\n 3 4\n 4 5\n 1 2 3 4 5", "output": "10\n 1 2 3 4 5\n \n\nIf we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written\non the four edges will be 1,2,3,4, for the score of 10. This is the maximum\npossible score.\n\n* * *"}, {"input": "5\n 1 2\n 1 3\n 1 4\n 1 5\n 3141 59 26 53 59", "output": "197\n 59 26 3141 59 53\n \n\nc_1,c_2,\\ldots,c_N may not be pairwise distinct."}] |
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on
Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If
there are multiple ways to achieve the maximum score, any of them will be
accepted.
* * * | s093693359 | Wrong Answer | p03026 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N | N = int(input())
if N == 1:
C1, C2 = map(int, input().split())
print(min(C1, C2))
print(str(C1) + " " + str(C2))
quit()
AB = [list(map(int, input().split())) for i in range(N - 1)]
C = list(map(int, input().split()))
T = [[i, 0] for i in range(N)]
for a, b in AB:
T[a - 1][1] += 1
T[b - 1][1] += 1
T = sorted(T, key=lambda x: x[1])
C = sorted(C)
ans_d = sorted([[C[i], T[i][0]] for i in range(N)], key=lambda x: x[1])
ans_d = [str(a[0]) for a in ans_d]
M = 0
for a, b in AB:
M += min(int(ans_d[a - 1]), int(ans_d[b - 1]))
print(M)
print(" ".join(ans_d))
| Statement
You are given a tree with N vertices 1,2,\ldots,N, and positive integers
c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects
Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our _score_
as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on
one vertex in T, and show one way to achieve it. If an integer occurs multiple
times in c_1,c_2,\ldots,c_N, we must use it that number of times. | [{"input": "5\n 1 2\n 2 3\n 3 4\n 4 5\n 1 2 3 4 5", "output": "10\n 1 2 3 4 5\n \n\nIf we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written\non the four edges will be 1,2,3,4, for the score of 10. This is the maximum\npossible score.\n\n* * *"}, {"input": "5\n 1 2\n 1 3\n 1 4\n 1 5\n 3141 59 26 53 59", "output": "197\n 59 26 3141 59 53\n \n\nc_1,c_2,\\ldots,c_N may not be pairwise distinct."}] |
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on
Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If
there are multiple ways to achieve the maximum score, any of them will be
accepted.
* * * | s374743719 | Wrong Answer | p03026 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N | n = int(input())
a = [[] for i in range(n + 1)]
ans = [0] * (n)
for i in range(1, n):
A = list(map(int, input().split()))
a[A[0]].append([A[1], i])
d = list(map(int, input().split()))
d.sort(reverse=True)
ans[0] = d[0]
d.pop(0)
ans0 = sum(d)
for i in range(1, n + 1):
for j in range(len(a[i])):
ans[a[i][j][1]] = d[0]
d.pop(0)
print(ans0)
print(*ans)
| Statement
You are given a tree with N vertices 1,2,\ldots,N, and positive integers
c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects
Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our _score_
as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on
one vertex in T, and show one way to achieve it. If an integer occurs multiple
times in c_1,c_2,\ldots,c_N, we must use it that number of times. | [{"input": "5\n 1 2\n 2 3\n 3 4\n 4 5\n 1 2 3 4 5", "output": "10\n 1 2 3 4 5\n \n\nIf we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written\non the four edges will be 1,2,3,4, for the score of 10. This is the maximum\npossible score.\n\n* * *"}, {"input": "5\n 1 2\n 1 3\n 1 4\n 1 5\n 3141 59 26 53 59", "output": "197\n 59 26 3141 59 53\n \n\nc_1,c_2,\\ldots,c_N may not be pairwise distinct."}] |
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on
Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If
there are multiple ways to achieve the maximum score, any of them will be
accepted.
* * * | s633898079 | Wrong Answer | p03026 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N | n = int(input())
edge = [list(map(int, input().split())) for _ in range(n - 1)]
c = sorted(map(int, input().split()))
count = dict(zip([key for key in range(1, n + 1)], [0 for _ in range((n))]))
for v, u in edge:
count[v] += 1
count[u] += 1
keys = [key for key, value in sorted(count.items(), key=lambda x: x[1])]
M = 0
w = dict(zip([key for key in range(1, n + 1)], [0 for _ in range((n))]))
for key, x in zip(keys, c):
w[key] = x
for u, v in edge:
M += min(w[u], w[v])
print(M)
for key in range(1, n + 1):
print(w[key], end=" ")
| Statement
You are given a tree with N vertices 1,2,\ldots,N, and positive integers
c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects
Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our _score_
as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on
one vertex in T, and show one way to achieve it. If an integer occurs multiple
times in c_1,c_2,\ldots,c_N, we must use it that number of times. | [{"input": "5\n 1 2\n 2 3\n 3 4\n 4 5\n 1 2 3 4 5", "output": "10\n 1 2 3 4 5\n \n\nIf we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written\non the four edges will be 1,2,3,4, for the score of 10. This is the maximum\npossible score.\n\n* * *"}, {"input": "5\n 1 2\n 1 3\n 1 4\n 1 5\n 3141 59 26 53 59", "output": "197\n 59 26 3141 59 53\n \n\nc_1,c_2,\\ldots,c_N may not be pairwise distinct."}] |
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on
Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If
there are multiple ways to achieve the maximum score, any of them will be
accepted.
* * * | s165407913 | Wrong Answer | p03026 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N | a = 1
for i in range(10000**2):
a = a + 1
| Statement
You are given a tree with N vertices 1,2,\ldots,N, and positive integers
c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects
Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our _score_
as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on
one vertex in T, and show one way to achieve it. If an integer occurs multiple
times in c_1,c_2,\ldots,c_N, we must use it that number of times. | [{"input": "5\n 1 2\n 2 3\n 3 4\n 4 5\n 1 2 3 4 5", "output": "10\n 1 2 3 4 5\n \n\nIf we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written\non the four edges will be 1,2,3,4, for the score of 10. This is the maximum\npossible score.\n\n* * *"}, {"input": "5\n 1 2\n 1 3\n 1 4\n 1 5\n 3141 59 26 53 59", "output": "197\n 59 26 3141 59 53\n \n\nc_1,c_2,\\ldots,c_N may not be pairwise distinct."}] |
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on
Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If
there are multiple ways to achieve the maximum score, any of them will be
accepted.
* * * | s371355005 | Accepted | p03026 | Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N | def sol(_inp=input):
n = int(_inp())
tree = {i + 1: set() for i in range(n)}
assigned = [0 for _ in range(n)]
for _ in range(n - 1):
i, j = map(int, _inp().split())
tree[i].add(j)
tree[j].add(i)
cs = sorted(list(map(int, _inp().split())))
tree_orig = {i: tree[i].copy() for i in tree}
for c in cs[:-1]:
for v in tree:
if len(tree[v]) == 1:
assigned[v - 1] = c
w = list(tree[v])[0]
tree[v] = set()
tree[w].remove(v)
break
else:
assigned[w - 1] = cs[-1]
res = (
sum(
min(assigned[v - 1], assigned[w - 1])
for v in tree_orig
for w in tree_orig[v]
)
// 2
)
return "{}\n{}".format(res, " ".join(str(c) for c in assigned))
print(sol())
| Statement
You are given a tree with N vertices 1,2,\ldots,N, and positive integers
c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects
Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our _score_
as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on
one vertex in T, and show one way to achieve it. If an integer occurs multiple
times in c_1,c_2,\ldots,c_N, we must use it that number of times. | [{"input": "5\n 1 2\n 2 3\n 3 4\n 4 5\n 1 2 3 4 5", "output": "10\n 1 2 3 4 5\n \n\nIf we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written\non the four edges will be 1,2,3,4, for the score of 10. This is the maximum\npossible score.\n\n* * *"}, {"input": "5\n 1 2\n 1 3\n 1 4\n 1 5\n 3141 59 26 53 59", "output": "197\n 59 26 3141 59 53\n \n\nc_1,c_2,\\ldots,c_N may not be pairwise distinct."}] |
Print Q lines. The i-th line (1≤i≤Q) should contain the response to the i-th
query.
* * * | s093847455 | Accepted | p03476 | Input is given from Standard Input in the following format:
Q
l_1 r_1
:
l_Q r_Q | import sys
## io
IS = lambda: sys.stdin.readline().rstrip()
II = lambda: int(IS())
MII = lambda: list(map(int, IS().split()))
MIIZ = lambda: list(map(lambda x: x - 1, MII()))
## dp
INIT_VAL = 0
MD2 = lambda d1, d2: [[INIT_VAL] * d2 for _ in range(d1)]
MD3 = lambda d1, d2, d3: [MD2(d2, d3) for _ in range(d1)]
## math
DIVC = lambda x, y: -(-x // y)
DIVF = lambda x, y: x // y
from itertools import accumulate as acc
class PrimeOptimizer:
def __init__(self, MAX_NUM=10**3):
"""MAX_NUM以下の素数テーブルを生成する。
生成した素数テーブルはprime_factorizationで使用する。
"""
is_prime = [True] * MAX_NUM
is_prime[0] = False
is_prime[1] = False
primes = []
for i in range(MAX_NUM):
if is_prime[i]:
primes.append(i)
for j in range(2 * i, MAX_NUM, i):
is_prime[j] = False
self.primes = primes
def prime_factorization(self, x):
"""xを素因数分解する。
分解先の素数はself.primesを利用する。
@param x (int): 分解対象の正整数
@return res (dict): key = 素数、value = 素数の数で構成される辞書
"""
res = {}
for prime in self.primes:
while x % prime == 0:
if not prime in res:
res[prime] = 0
res[prime] += 1
x //= prime
if x > 1:
res[x] = 1
return res
def main():
q = II()
lr = [MII() for _ in range(q)]
pm = PrimeOptimizer(MAX_NUM=10**5)
prims = set(pm.primes)
like_2017 = [0] * 10**5
for n in range(1, 10**5):
if n in prims and (n + 1) // 2 in prims:
like_2017[n] = 1
acc_like_2017 = list(acc(like_2017))
for l, r in lr:
print(acc_like_2017[r] - acc_like_2017[l - 1])
if __name__ == "__main__":
main()
| Statement
We say that a odd number N is _similar to 2017_ when both N and (N+1)/2 are
prime.
You are given Q queries.
In the i-th query, given two odd numbers l_i and r_i, find the number of odd
numbers x similar to 2017 such that l_i ≤ x ≤ r_i. | [{"input": "1\n 3 7", "output": "2\n \n\n * 3 is similar to 2017, since both 3 and (3+1)/2=2 are prime.\n * 5 is similar to 2017, since both 5 and (5+1)/2=3 are prime.\n * 7 is not similar to 2017, since (7+1)/2=4 is not prime, although 7 is prime.\n\nThus, the response to the first query should be 2.\n\n* * *"}, {"input": "4\n 13 13\n 7 11\n 7 11\n 2017 2017", "output": "1\n 0\n 0\n 1\n \n\nNote that 2017 is also similar to 2017.\n\n* * *"}, {"input": "6\n 1 53\n 13 91\n 37 55\n 19 51\n 73 91\n 13 49", "output": "4\n 4\n 1\n 1\n 1\n 2"}] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.