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 |
|---|---|---|---|---|---|---|---|
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s201660367 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | for | Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s821290172 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | print("Yes" if (input() % 500) < input() else "No")
| Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s899105268 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | x, a, b = [int(input()) for i in range(3)]
print((x - a) % b)
| Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s597095691 | Wrong Answer | p03433 | Input is given from Standard Input in the following format:
N
A | print(["Yes", "No"][int(input()) % 100 > int(input())])
| Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s682532056 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | print(["No","Yes"][((int(input())-int(input())))%500==0] | Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s587370158 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | N=int(input())
A=int(input())
if N % 500 <= A:
print("Yes")
else:
print("No") | Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s963678268 | Wrong Answer | p03433 | Input is given from Standard Input in the following format:
N
A | print("Yes" if int(input()) % 500 < int(input()) else "No")
| Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s029537459 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | #-*-cording:utf-8-*-
N = int(input())
A = input().split()
A.sort()
A.reverse()
a=list(map(int,A))
Alice = a[1::2]
Bob = a[0::2]
allA=sum(Alice)
allB=sum(Bob)
Ans=allA-allB
print(Ans)
~ | Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s347830224 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | # -*- coding: utf-8 -*-
# 整数の入力
n = int(input())
a = int(input())
# スペース区切りの整数の入力
# b, c = map(int, input().split())
# 文字列の入力
# s = input()
# # 出力
# print("{} {}".format(a+b+c, s))
if n < 500:
if n > a:
print('Yes')
else:
print('No')
else:
amari = n%500
if amari =< a:
print('Yes')
else:
print('No') | Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s838651980 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | N = int(input()) # 支払い金学
A = int(input()) # 1円の枚数
range_A = range(A)
flag = False
for a in range_A:
if (N - a) % 500 == 0:
flag = True
if flag: print("Yes")
print("No") | Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s689876968 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | n = int(input())
a = int(input())
if (n%500>=0 and n%500=<1000):
print('Yes')
else:
print('No') | Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s128464802 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | n = input()
a = input()
if n == a || n%500<=a:
print('Yes')
else:
print('No')
| Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s259393829 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | N=int(input())
A=int(input())
b=N//500
c=N-500b
if A<=c:
print('Yes')
else:
print('No')
| Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s611282705 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | n = map(int, input())
a = map(int, input())
if n%500 < a:
print('YES')
else
print('NO') | Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s475919365 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | a,n=map(int,input().split())
amari=n%500
if amari=<a:
print('Yes')
else:
print('No')
| Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print
`Yes`; otherwise, print `No`.
* * * | s150833164 | Runtime Error | p03433 | Input is given from Standard Input in the following format:
N
A | n = int(input())
a = int(input())
m = n mod 500
if m <= a:
print('Yes')
else:
print('No')
| Statement
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins. | [{"input": "2018\n 218", "output": "Yes\n \n\nWe can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer\nis `Yes`.\n\n* * *"}, {"input": "2763\n 0", "output": "No\n \n\nWhen we have no 1-yen coins, we can only pay a multiple of 500 yen using only\n500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.\n\n* * *"}, {"input": "37\n 514", "output": "Yes"}] |
Print the cube of x in a line. | s852487703 | Accepted | p02388 | An integer x is given in a line. | A = int(input())
B = A * A * A
print(B)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s512978349 | Runtime Error | p02388 | An integer x is given in a line. | kotae = input()
print(kotae * kotae * kotae)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s093740082 | Runtime Error | p02388 | An integer x is given in a line. | a, b = map(int, input().split())
print(a * b, 2 * (a + b))
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s983891356 | Runtime Error | p02388 | An integer x is given in a line. | Arr = []
Arr = input.split()
print(Arr[0] * Arr[1])
print(2 * Arr[0] + 2 * Arr[1])
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s406804723 | Runtime Error | p02388 | An integer x is given in a line. | int("x") ** 3
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s322584303 | Runtime Error | p02388 | An integer x is given in a line. | print(int(input) ** 3)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s776595829 | Runtime Error | p02388 | An integer x is given in a line. | cube = input()
print(cube**3)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s589801194 | Runtime Error | p02388 | An integer x is given in a line. | print(int(input()) ** int(input()))
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s034342370 | Runtime Error | p02388 | An integer x is given in a line. | N = input()
N = N * N * N
print(N)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s232270891 | Runtime Error | p02388 | An integer x is given in a line. | print(input() * input() * input())
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s739645339 | Accepted | p02388 | An integer x is given in a line. | hoge = int(input())
print(hoge * hoge * hoge)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s350283247 | Wrong Answer | p02388 | An integer x is given in a line. | print(int(input("x???????????\?????????????????????")) ** 3)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s349861811 | Wrong Answer | p02388 | An integer x is given in a line. | import sys
numbers = []
max = 0
for line in sys.stdin:
numbers.append(int(line))
for i in range(0, len(numbers)):
for j in range(i, len(numbers)):
if numbers[j] - numbers[i] > max:
max = numbers[j] - numbers[i]
print(max)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s339647438 | Wrong Answer | p02388 | An integer x is given in a line. | def jack(x):
y = x**3
return y
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s943106528 | Wrong Answer | p02388 | An integer x is given in a line. | for x in range(1, 101, 3):
print(x)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s346825800 | Accepted | p02388 | An integer x is given in a line. | print(eval(input()) ** 3)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s669648968 | Wrong Answer | p02388 | An integer x is given in a line. | print(1)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s804566577 | Wrong Answer | p02388 | An integer x is given in a line. | 2 * 2 * 2
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s184744642 | Accepted | p02388 | An integer x is given in a line. | inp = int(input())
print(inp**3)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s337147673 | Accepted | p02388 | An integer x is given in a line. | r = input()
print(int(r) ** 3)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s388660126 | Accepted | p02388 | An integer x is given in a line. | t = int(input())
s = t**3
print(s)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s869288570 | Accepted | p02388 | An integer x is given in a line. | input_num = int(input())
print(input_num**3)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s267296068 | Wrong Answer | p02388 | An integer x is given in a line. | print(int(input()) ** 2)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s835147038 | Accepted | p02388 | An integer x is given in a line. | print(int(input().strip()) ** 3)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s759935070 | Wrong Answer | p02388 | An integer x is given in a line. | x = input("Please Enter Number")
print(2 * 2 * 2)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s019674987 | Wrong Answer | p02388 | An integer x is given in a line. | x = int(input("1??\???100??\????????´??°?????\?????????????????????: "))
num = x**3
print(num, end="\n")
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s113852607 | Wrong Answer | p02388 | An integer x is given in a line. | a = input("x")
b = int(a)
c = b**3
print(c)
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the cube of x in a line. | s783806836 | Wrong Answer | p02388 | An integer x is given in a line. | print(int(input()))
| X Cubic
Write a program which calculates the cube of a given integer x. | [{"input": "2", "output": "8"}, {"input": "3", "output": "27"}] |
Print the minimum total cost to dismantle the object.
* * * | s312371051 | Accepted | p03960 | The input is given from Standard Input in the following format:
H W
c_{1,1}c_{1,2}..c_{1,W}
c_{2,1}c_{2,2}..c_{2,W}
:
c_{H,1}c_{H,2}..c_{H,W} | import sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x + "\n")
h, w = list(map(int, input().split()))
c = [None] * h
for i in range(h):
c[i] = input()
# def sub(i):
# c0 = c[i]
# c1 = c[i+1]
# dp = [[None]*(h+1) for _ in range(h+1)]
# for i in range(h+1):
# dp[i][0] = 0
# dp[0][i] = 0
# val = [None]*(2*h+1) # c0がc1よりi-h高いときの衝突数の累積和
# for i in range(h):
# # c1がh, c0がi
# l = []
# v = 0
# for j in range(i):
# if c1[h-i+j]==c0[j]:
# v += 1
# l.append(v)
# val[i] = l
# for i in range(h, -1, -1):
# # c0がh, c1がi
# l = []
# v = 0
# for j in range(i):
# if c0[h-i+j]==c1[j]:
# v += 1
# l.append(v)
# val[h+(h-i)] = l
# for i in range(1, h+1):
# for j in range(1, h+1):
# dp[i][j] = min(dp[i+1][j]+val[(i+1)-j+h][i], dp[i][j+1]+val[i-(j+1)+h][i-1])
# return dp[h][h]
ans = 0
for i in range(w - 1):
c0 = [c[j][i] for j in range(h)]
c1 = [c[j][i + 1] for j in range(h)]
dp = [[None] * (h + 1) for _ in range(h + 1)]
for i in range(h + 1):
dp[i][0] = 0
dp[0][i] = 0
val = [None] * (2 * h + 1) # c0がc1よりi-h高いときの衝突数の累積和
for i in range(h):
# c1がh, c0がi
l = []
v = 0
for j in range(i):
if c1[h - i + j] == c0[j]:
v += 1
l.append(v)
val[i] = l
for i in range(h, -1, -1):
# c0がh, c1がi
l = []
v = 0
for j in range(i):
if c0[h - i + j] == c1[j]:
v += 1
l.append(v)
val[h + (h - i)] = l
for i in range(1, h + 1):
for j in range(1, h + 1):
cost = val[(i) - j + h][min(i, j) - 1]
dp[i][j] = min(dp[i - 1][j] + cost, dp[i][j - 1] + cost)
ans += dp[h][h]
# return dp[h][h]
# ans += sub(i)
print(ans)
| Statement
Mr. Takahashi has in his room an art object with H rows and W columns, made up
of H \times W blocks. Each block has a color represented by a lowercase
English letter (`a`-`z`). The color of the block at the i-th row and j-th
column is c_{i,j}.
Mr. Takahashi would like to dismantle the object, finding it a bit kitschy for
his tastes. The dismantling is processed by repeating the following operation:
* Choose one of the W columns and push down that column one row. The block at the bottom of that column disappears.
Each time the operation is performed, a cost is incurred. Since blocks of the
same color have a property to draw each other together, the cost of the
operation is the number of the pairs of blocks (p, q) such that:
* The block p is in the selected column.
* The two blocks p and q are horizontally adjacent (before pushing down the column).
* The two blocks p and q have the same color.
Mr. Takahashi dismantles the object by repeating the operation H \times W
times to get rid of all the blocks. Compute the minimum total cost to
dismantle the object. | [{"input": "2 3\n rrr\n brg", "output": "2\n \n\nFor example, the total cost of 2 can be achieved by performing the operation\nas follows and this is the minimum value.\n\n\n\n* * *"}, {"input": "6 3\n xya\n xya\n ayz\n ayz\n xaz\n xaz", "output": "0\n \n\nThe total cost of 0 can be achieved by first pushing down all blocks of the\nmiddle column, then all of the left column, and all of the right column.\n\n* * *"}, {"input": "4 2\n ay\n xa\n xy\n ay", "output": "0\n \n\nThe total cost of 0 can be achieved by the following operations:\n\n * pushing down the right column one row;\n * pushing down the left column one row;\n * pushing down all of the right column;\n * and pushing down all of the left column.\n\n* * *"}, {"input": "5 5\n aaaaa\n abbba\n ababa\n abbba\n aaaaa", "output": "24\n \n\n* * *"}, {"input": "7 10\n xxxxxxxxxx\n ccccxxffff\n cxxcxxfxxx\n cxxxxxffff\n cxxcxxfxxx\n ccccxxfxxx\n xxxxxxxxxx", "output": "130"}] |
Print the minimum total cost to dismantle the object.
* * * | s808347273 | Accepted | p03960 | The input is given from Standard Input in the following format:
H W
c_{1,1}c_{1,2}..c_{1,W}
c_{2,1}c_{2,2}..c_{2,W}
:
c_{H,1}c_{H,2}..c_{H,W} | def solve(k):
dp = [[0] * (h + 1) for i in range(h + 1)]
for i in range(h):
for diff in range(h - i):
dp[i + 1][i + 1 + diff] = dp[i][i + diff] + (s[i + diff][k] == s[i][k + 1])
dp[i + 1 + diff][i + 1] = dp[i + diff][i] + (s[i][k] == s[i + diff][k + 1])
dq = [[INF] * (h + 1) for i in range(h + 1)]
dq[0][0] = 0
for i in range(h):
dq[i + 1][0] = dq[i][0] + dp[h - i][h]
dq[0][i + 1] = dq[0][i] + dp[h][h - i]
for i in range(h):
for j in range(h):
dq[i + 1][j + 1] = min(
dq[i + 1][j] + dp[h - (i + 1)][h - j],
dq[i][j + 1] + dp[h - i][h - (j + 1)],
)
return dq[h][h]
h, w = map(int, input().split())
s = [input() for i in range(h)]
INF = 10**5
OFFSET = 500
ans = 0
for i in range(w - 1):
ans += solve(i)
print(ans)
| Statement
Mr. Takahashi has in his room an art object with H rows and W columns, made up
of H \times W blocks. Each block has a color represented by a lowercase
English letter (`a`-`z`). The color of the block at the i-th row and j-th
column is c_{i,j}.
Mr. Takahashi would like to dismantle the object, finding it a bit kitschy for
his tastes. The dismantling is processed by repeating the following operation:
* Choose one of the W columns and push down that column one row. The block at the bottom of that column disappears.
Each time the operation is performed, a cost is incurred. Since blocks of the
same color have a property to draw each other together, the cost of the
operation is the number of the pairs of blocks (p, q) such that:
* The block p is in the selected column.
* The two blocks p and q are horizontally adjacent (before pushing down the column).
* The two blocks p and q have the same color.
Mr. Takahashi dismantles the object by repeating the operation H \times W
times to get rid of all the blocks. Compute the minimum total cost to
dismantle the object. | [{"input": "2 3\n rrr\n brg", "output": "2\n \n\nFor example, the total cost of 2 can be achieved by performing the operation\nas follows and this is the minimum value.\n\n\n\n* * *"}, {"input": "6 3\n xya\n xya\n ayz\n ayz\n xaz\n xaz", "output": "0\n \n\nThe total cost of 0 can be achieved by first pushing down all blocks of the\nmiddle column, then all of the left column, and all of the right column.\n\n* * *"}, {"input": "4 2\n ay\n xa\n xy\n ay", "output": "0\n \n\nThe total cost of 0 can be achieved by the following operations:\n\n * pushing down the right column one row;\n * pushing down the left column one row;\n * pushing down all of the right column;\n * and pushing down all of the left column.\n\n* * *"}, {"input": "5 5\n aaaaa\n abbba\n ababa\n abbba\n aaaaa", "output": "24\n \n\n* * *"}, {"input": "7 10\n xxxxxxxxxx\n ccccxxffff\n cxxcxxfxxx\n cxxxxxffff\n cxxcxxfxxx\n ccccxxfxxx\n xxxxxxxxxx", "output": "130"}] |
Print the minimum total cost to dismantle the object.
* * * | s976209127 | Wrong Answer | p03960 | The input is given from Standard Input in the following format:
H W
c_{1,1}c_{1,2}..c_{1,W}
c_{2,1}c_{2,2}..c_{2,W}
:
c_{H,1}c_{H,2}..c_{H,W} | from collections import Counter
N, K = list(map(int, input().split()))
ls = [input() for j in range(N)]
cnt = [[0 for i in range(25)] for i in range(N)]
al = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"w",
"x",
"y",
"z",
]
cost = 0
for j in range(N):
for i in range(25):
Cnt = Counter(ls[j])
cnt[j][i] = Cnt[al[i]]
for j in range(N):
for i in range(25):
if cnt[j][i] != 0 and cnt[j][i] != 1:
cost += cnt[j][i]
print(cost - 1)
| Statement
Mr. Takahashi has in his room an art object with H rows and W columns, made up
of H \times W blocks. Each block has a color represented by a lowercase
English letter (`a`-`z`). The color of the block at the i-th row and j-th
column is c_{i,j}.
Mr. Takahashi would like to dismantle the object, finding it a bit kitschy for
his tastes. The dismantling is processed by repeating the following operation:
* Choose one of the W columns and push down that column one row. The block at the bottom of that column disappears.
Each time the operation is performed, a cost is incurred. Since blocks of the
same color have a property to draw each other together, the cost of the
operation is the number of the pairs of blocks (p, q) such that:
* The block p is in the selected column.
* The two blocks p and q are horizontally adjacent (before pushing down the column).
* The two blocks p and q have the same color.
Mr. Takahashi dismantles the object by repeating the operation H \times W
times to get rid of all the blocks. Compute the minimum total cost to
dismantle the object. | [{"input": "2 3\n rrr\n brg", "output": "2\n \n\nFor example, the total cost of 2 can be achieved by performing the operation\nas follows and this is the minimum value.\n\n\n\n* * *"}, {"input": "6 3\n xya\n xya\n ayz\n ayz\n xaz\n xaz", "output": "0\n \n\nThe total cost of 0 can be achieved by first pushing down all blocks of the\nmiddle column, then all of the left column, and all of the right column.\n\n* * *"}, {"input": "4 2\n ay\n xa\n xy\n ay", "output": "0\n \n\nThe total cost of 0 can be achieved by the following operations:\n\n * pushing down the right column one row;\n * pushing down the left column one row;\n * pushing down all of the right column;\n * and pushing down all of the left column.\n\n* * *"}, {"input": "5 5\n aaaaa\n abbba\n ababa\n abbba\n aaaaa", "output": "24\n \n\n* * *"}, {"input": "7 10\n xxxxxxxxxx\n ccccxxffff\n cxxcxxfxxx\n cxxxxxffff\n cxxcxxfxxx\n ccccxxfxxx\n xxxxxxxxxx", "output": "130"}] |
Print the minimum total cost to dismantle the object.
* * * | s640471861 | Wrong Answer | p03960 | The input is given from Standard Input in the following format:
H W
c_{1,1}c_{1,2}..c_{1,W}
c_{2,1}c_{2,2}..c_{2,W}
:
c_{H,1}c_{H,2}..c_{H,W} | import sys
H, W = list(map(int, input().split()))
arr = []
count = 0
if W == 1:
print(0)
sys.exit()
if W == 2:
for i in range(H):
a, b = list(input())
if a == b:
count += 1
print(count)
sys.exit()
if W == 3:
for i in range(H):
a, b, c = list(input())
if a == b:
count += 1
if b == c:
count += 1
print(count)
sys.exit()
| Statement
Mr. Takahashi has in his room an art object with H rows and W columns, made up
of H \times W blocks. Each block has a color represented by a lowercase
English letter (`a`-`z`). The color of the block at the i-th row and j-th
column is c_{i,j}.
Mr. Takahashi would like to dismantle the object, finding it a bit kitschy for
his tastes. The dismantling is processed by repeating the following operation:
* Choose one of the W columns and push down that column one row. The block at the bottom of that column disappears.
Each time the operation is performed, a cost is incurred. Since blocks of the
same color have a property to draw each other together, the cost of the
operation is the number of the pairs of blocks (p, q) such that:
* The block p is in the selected column.
* The two blocks p and q are horizontally adjacent (before pushing down the column).
* The two blocks p and q have the same color.
Mr. Takahashi dismantles the object by repeating the operation H \times W
times to get rid of all the blocks. Compute the minimum total cost to
dismantle the object. | [{"input": "2 3\n rrr\n brg", "output": "2\n \n\nFor example, the total cost of 2 can be achieved by performing the operation\nas follows and this is the minimum value.\n\n\n\n* * *"}, {"input": "6 3\n xya\n xya\n ayz\n ayz\n xaz\n xaz", "output": "0\n \n\nThe total cost of 0 can be achieved by first pushing down all blocks of the\nmiddle column, then all of the left column, and all of the right column.\n\n* * *"}, {"input": "4 2\n ay\n xa\n xy\n ay", "output": "0\n \n\nThe total cost of 0 can be achieved by the following operations:\n\n * pushing down the right column one row;\n * pushing down the left column one row;\n * pushing down all of the right column;\n * and pushing down all of the left column.\n\n* * *"}, {"input": "5 5\n aaaaa\n abbba\n ababa\n abbba\n aaaaa", "output": "24\n \n\n* * *"}, {"input": "7 10\n xxxxxxxxxx\n ccccxxffff\n cxxcxxfxxx\n cxxxxxffff\n cxxcxxfxxx\n ccccxxfxxx\n xxxxxxxxxx", "output": "130"}] |
Print the minimum total cost to dismantle the object.
* * * | s553371148 | Runtime Error | p03960 | The input is given from Standard Input in the following format:
H W
c_{1,1}c_{1,2}..c_{1,W}
c_{2,1}c_{2,2}..c_{2,W}
:
c_{H,1}c_{H,2}..c_{H,W} | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
import numpy as np
"""
それぞれの隣接2列ごとに、可能な摩擦の最小値を実現する → 小問題に分割。
"""
buffer = sys.stdin.buffer
H,W = map(int,buffer.readline().split())
C = np.frombuffer(buffer.read(),dtype='S1').reshape(H,-1)[:,:W].T
dp_1 = np.zeros((W-1,H+H+1,H+1),dtype=np.int64)
for r in range(H):
dp_1[:,r+2:r+H+2,r+1] = (C[:-1] == C[1:,r][:,None])
(C[:-1][:,:] == C[1:][:,r][])
INF = 10**18
# R-L+H -> min cost
dp = np.full((W-1,H+H+1),INF,dtype=np.int64)
dp[:,H] = 0
for n in range(1,H+H+1):
# n個目を置く
prev = dp
dp = np.full((W-1,H+H+1),INF,dtype=np.int64)
dp[:,1:] = np.minimum(dp[:,1:],prev[:,:-1])
dp[:,:-1] = np.minimum(dp[:,:-1],prev[:,1:])
dp += dp_1[:,:,n]
answer = dp[:,H].sum()
print(answer) | Statement
Mr. Takahashi has in his room an art object with H rows and W columns, made up
of H \times W blocks. Each block has a color represented by a lowercase
English letter (`a`-`z`). The color of the block at the i-th row and j-th
column is c_{i,j}.
Mr. Takahashi would like to dismantle the object, finding it a bit kitschy for
his tastes. The dismantling is processed by repeating the following operation:
* Choose one of the W columns and push down that column one row. The block at the bottom of that column disappears.
Each time the operation is performed, a cost is incurred. Since blocks of the
same color have a property to draw each other together, the cost of the
operation is the number of the pairs of blocks (p, q) such that:
* The block p is in the selected column.
* The two blocks p and q are horizontally adjacent (before pushing down the column).
* The two blocks p and q have the same color.
Mr. Takahashi dismantles the object by repeating the operation H \times W
times to get rid of all the blocks. Compute the minimum total cost to
dismantle the object. | [{"input": "2 3\n rrr\n brg", "output": "2\n \n\nFor example, the total cost of 2 can be achieved by performing the operation\nas follows and this is the minimum value.\n\n\n\n* * *"}, {"input": "6 3\n xya\n xya\n ayz\n ayz\n xaz\n xaz", "output": "0\n \n\nThe total cost of 0 can be achieved by first pushing down all blocks of the\nmiddle column, then all of the left column, and all of the right column.\n\n* * *"}, {"input": "4 2\n ay\n xa\n xy\n ay", "output": "0\n \n\nThe total cost of 0 can be achieved by the following operations:\n\n * pushing down the right column one row;\n * pushing down the left column one row;\n * pushing down all of the right column;\n * and pushing down all of the left column.\n\n* * *"}, {"input": "5 5\n aaaaa\n abbba\n ababa\n abbba\n aaaaa", "output": "24\n \n\n* * *"}, {"input": "7 10\n xxxxxxxxxx\n ccccxxffff\n cxxcxxfxxx\n cxxxxxffff\n cxxcxxfxxx\n ccccxxfxxx\n xxxxxxxxxx", "output": "130"}] |
Print the minimum total cost to dismantle the object.
* * * | s342420927 | Accepted | p03960 | The input is given from Standard Input in the following format:
H W
c_{1,1}c_{1,2}..c_{1,W}
c_{2,1}c_{2,2}..c_{2,W}
:
c_{H,1}c_{H,2}..c_{H,W} | import itertools
h, w = map(int, input().split())
c = [list(map(ord, input())) for i in range(h)]
c = list(itertools.chain.from_iterable(c))
INF = 10**9
h2 = (h + 1) * (h + 1)
ans = 0
dq = [0] * h2
for wi in range(w - 1):
for diff in range(h + 1):
cnt1 = 0
cnt2 = 0
for i in range(h - diff):
cnt1 += c[i * w + wi] == c[(i + diff) * w + wi + 1]
cnt2 += c[(i + diff) * w + wi] == c[i * w + wi + 1]
dq[diff * (h + 1)] = cnt1
dq[diff] = cnt2
for i in range(h - diff - 1):
cnt1 -= c[(h - i - 1 - diff) * w + wi] == c[(h - i - 1) * w + wi + 1]
dq[(i + 1 + diff) * (h + 1) + i + 1] = cnt1
cnt2 -= c[(h - i - 1 - diff) * w + wi + 1] == c[(h - i - 1) * w + wi]
dq[(i + 1) * (h + 1) + i + 1 + diff] = cnt2
dp = [INF] * h2
dp[0] = 0
for i in range(h + 1):
for j in range(h + 1):
if i + 1 < h + 1:
dp[(i + 1) * (h + 1) + j] = min(
dp[i * (h + 1) + j] + dq[i * (h + 1) + j], dp[(i + 1) * (h + 1) + j]
)
if j + 1 < h + 1:
dp[i * (h + 1) + j + 1] = min(
dp[i * (h + 1) + j] + dq[i * (h + 1) + j], dp[i * (h + 1) + j + 1]
)
ans += dp[-1]
print(ans)
| Statement
Mr. Takahashi has in his room an art object with H rows and W columns, made up
of H \times W blocks. Each block has a color represented by a lowercase
English letter (`a`-`z`). The color of the block at the i-th row and j-th
column is c_{i,j}.
Mr. Takahashi would like to dismantle the object, finding it a bit kitschy for
his tastes. The dismantling is processed by repeating the following operation:
* Choose one of the W columns and push down that column one row. The block at the bottom of that column disappears.
Each time the operation is performed, a cost is incurred. Since blocks of the
same color have a property to draw each other together, the cost of the
operation is the number of the pairs of blocks (p, q) such that:
* The block p is in the selected column.
* The two blocks p and q are horizontally adjacent (before pushing down the column).
* The two blocks p and q have the same color.
Mr. Takahashi dismantles the object by repeating the operation H \times W
times to get rid of all the blocks. Compute the minimum total cost to
dismantle the object. | [{"input": "2 3\n rrr\n brg", "output": "2\n \n\nFor example, the total cost of 2 can be achieved by performing the operation\nas follows and this is the minimum value.\n\n\n\n* * *"}, {"input": "6 3\n xya\n xya\n ayz\n ayz\n xaz\n xaz", "output": "0\n \n\nThe total cost of 0 can be achieved by first pushing down all blocks of the\nmiddle column, then all of the left column, and all of the right column.\n\n* * *"}, {"input": "4 2\n ay\n xa\n xy\n ay", "output": "0\n \n\nThe total cost of 0 can be achieved by the following operations:\n\n * pushing down the right column one row;\n * pushing down the left column one row;\n * pushing down all of the right column;\n * and pushing down all of the left column.\n\n* * *"}, {"input": "5 5\n aaaaa\n abbba\n ababa\n abbba\n aaaaa", "output": "24\n \n\n* * *"}, {"input": "7 10\n xxxxxxxxxx\n ccccxxffff\n cxxcxxfxxx\n cxxxxxffff\n cxxcxxfxxx\n ccccxxfxxx\n xxxxxxxxxx", "output": "130"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s322449089 | Accepted | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
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 math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
from operator import mul
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 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
# 組合せnCr
def combinations_count(n, r):
if n < r:
return 0
r = min(r, n - r)
numer = reduce(mul, range(n, n - r, -1), 1)
denom = reduce(mul, range(1, r + 1), 1)
return numer // denom
# 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)
# 素数判定
def is_prime(n):
if n <= 1:
return False
p = 2
while True:
if p**2 > n:
break
if n % p == 0:
return False
p += 1
return True
# 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
def make_divisors(n):
lower_divisors, upper_divisors = [], []
i = 1
while i * i <= n:
if n % i == 0:
lower_divisors.append(i)
if i != n // i:
upper_divisors.append(n // i)
i += 1
return lower_divisors + upper_divisors[::-1]
# ここから書き始める
n, m, r = map(int, input().split())
cities = list(map(int, input().split()))
a = [0 for i in range(m)]
b = [0 for i in range(m)]
c = [0 for i in range(m)]
for i in range(m):
a[i], b[i], c[i] = map(int, input().split())
a[i] -= 1
b[i] -= 1
d = [[INF for j in range(n)] for i in range(n)]
for i in range(m):
d[a[i]][b[i]] = c[i]
d[b[i]][a[i]] = c[i]
for i in range(n):
d[i][i] = 0
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])
ans = INF
for i in permutations(cities):
total = 0
for j in range(1, r):
total += d[i[j] - 1][i[j - 1] - 1]
ans = min(ans, total)
print(ans)
| Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s508549493 | Runtime Error | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | import sys
input = sys.stdin.readline
def main():
import itertools
def warshall_floyd(D, n):
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])
N, M, R = map(int, input().split())
r = list(map(int, input().split()))
D = [[float('inf')]*N for _ in range(N)]
for i in range(N):
D[i][i] = 0
for _ in range(M):
a, b, c = map(int, input().split())
D[a-1][b-1] = c
D[b-1][a-1] = c
warshall_floyd(D, N)
ans = float('inf')
for P in itertools.permutations(r):
cost = 0
for i in range(R-1):
cost += D[P[i]-1][P[i+1]-1]
ans = min(ans, cost)
print(ans)
if __name__ == '__main__':
main() | Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s286025044 | Runtime Error | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | import math
from itertools import permutations
import numpy as np
#from scipy.sparse import*
def warshall_floyd(d):
#d[i][j]: iからjへの最短距離
n=len(d[0])
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
N,M,R=[int(x) for x in input().split()]
r=[int(x)-1 for x in input().split()]
#route_list=[[10*9]*N for i in range(N)]
route_list = np.full((N,N)10*8,dtype=np.int)
for i in range(M):
a,b,c=[int(x) for x in input().split()]
route_list[a-1][b-1]=c
route_list[b-1][a-1]=c
wa_list=warshall_floyd(route_list)
ans=10**9
for perm in permutations(r):
#print(perm)
cur = sum(wa_list[v][u] for v, u in zip(perm, perm[1:]))
ans = min(ans, cur)
print(ans) | Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s653145237 | Runtime Error | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | #!/usr/bin/env python
# ワーシャルフロイド+全探索
import numpy as np
import itertools
def main():
N, M, R = map(int, input().split())
rs = [int(a)-1 for a in input().split())]
inf = float('inf')
cost = [[inf]*N for _ in range(N)]
# グラフ作る
for i in range(N):
cost[i][i] = 0
for _ in range(M):
a, b, c = map(int, input().split())
cost[a][b] = c
cost[b][a] = c
# ワーシャルフロイドで全頂点間距離算出
for k in range(N):
for i in range(N):
for j in range(N):
if cost[i][k]+cost[k][j] < cost[i][j]:
cost[i][j] = cost[i][k] + cost[k][j]
# 組み合わせ全探索
ans = inf
for route in itertools.permutations(rs):
d = 0
for i in range(R-1):
d += cost[route[i]][route[i+1]]
if d > ans:
break
ans = min(ans, d)
print(int(ans))
if __name__=='__main__':
main() | Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s275199685 | Runtime Error | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | import itertools
def warshall_floyd(d):
len_d = len(d)
for k in range(len_d):
for i in range(len_d):
for j in range(len_d):
if d[i][j] < d[i][k] + d[k][j]:
d[i][j] = d[i][k] + d[k][j]
return d
def main():
n, m, r = map(int, input().split())
list_r = list(map(int, input().split()))
list_cand = list(itertools.permutations(list_r))
dist = [[float("inf") if i != j else 0 for j in range(n)] for i in range(n)]
for i in range(m):
a, b, c = map(int, input().split())
dist[a-1][b-1] = c
dist[b-1][a-1] = c
min_dist = warshall_floyd(dist)
result = 10**100
for one_cand in list_cand:
temp = 0
for i in range(r-1)
temp += min_dist[one_cand[i]-1][one_cand[i+1]-1]
if temp < result:
result = temp
print(result)
if __name__ == "__main__":
main() | Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s229574849 | Runtime Error | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | import math
from itertools import permutations
import numpy as np
#from scipy.sparse import*
def warshall_floyd(d):
#d[i][j]: iからjへの最短距離
n=len(d[0])
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
N,M,R=[int(x) for x in input().split()]
r=[int(x)-1 for x in input().split()]
#route_list=[[10*9]*N for i in range(N)]
route_list = np.full((N,N)10*8,dtype=np.int)
for i in range(M):
a,b,c=[int(x) for x in input().split()]
route_list[a-1][b-1]=c
route_list[b-1][a-1]=c
wa_list=warshall_floyd(route_list)
ans=10**9
for perm in permutations(r):
#print(perm)
cur = sum(wa_list[v][u] for v, u in zip(perm, perm[1:]))
ans = min(ans, cur)
print(ans) | Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s388169908 | Runtime Error | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | import java.util.*;
public class Main {
static boolean[] used;
static int[] r;
static int[][] d;
static int INF = Integer.MAX_VALUE/2, R;
static long ans = INF;
static void dfs(int now, long cost, int cnt) {
if(cnt == R) {
ans = Math.min(ans, cost);
return;
}
for(int i : r)
if(!used[i]) {
used[i] = true;
dfs(i, cost + d[now][i], cnt + 1);
used[i] = false;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
R = sc.nextInt();
r = new int[R];
used = new boolean[N];
d = new int[N][N];
Arrays.setAll(r, i -> sc.nextInt()-1);
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
if(i != j)
d[i][j] = INF;
for(int i = 0; i < M; i++) {
int A = sc.nextInt()-1;
int B = sc.nextInt()-1;
int C = sc.nextInt();
d[A][B] = C;
d[B][A] = C;
}
for(int k = 0; k < N; k++)
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
d[i][j] = Math.min(d[i][j], d[i][k] + d[j][k]);
for(int i : r) {
used[i] = true;
dfs(i, 0, 1);
used[i] = false;
}
System.out.println(ans);
}
} | Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s982669244 | Runtime Error | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | --F1 No73.py Bot (90,0) (Py Outl FlyC WS Undo-Tree AC) 8:51PM 1.27 -------------
# d[i][i] < 0 なら、グラフは負のサイクルを持つ
for k in range(self.N):
for i in range(self.N):
for j in range(self.N):
self.d[i][j] = min(self.d[i][j],
self.d[i][k] + self.d[k][j])
hasNegativeCycle = False
for i in range(self.N):
if self.d[i][i] < 0:
hasNegativeCycle = True
break
for i in range(self.N):
self.d[i][i] = 0
return hasNegativeCycle, self.d
N, M, R = map(int, input().split())
r = list(map(int, input().split()))
A = [0] * M
B = [0] * M
C = [0] * M
for i in range(M):
A[i], B[i], C[i] = map(int, input().split())
graph = WarshallFloyd(N)
for a, b, c in zip(A, B, C):
graph.add(a - 1, b - 1, c)
hasNegativeCycle, d = graph.WarshallFloyd_search()
ans = float("inf")
for temp in list(permutations(r)):
cand = 0
for i in range(R - 1):
fr = temp[i] - 1
to = temp[i + 1] - 1
cand += d[fr][to]
ans = min(ans, cand)
print(ans) | Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s915313897 | Runtime Error | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | from itertools import permutations
def input_list() :
return list(map(int, input().split()))
n, m ,r = input_list()
road = input_list()
road = [x-1 for x in road]
d = [[float('inf')] * n for i in range(n)]
for i in range(n) :
d[i][i] = 0
for i in range(m) :
a, b, c = input_list()
a -= 1
b -= 1
d[a][b] = c
d[b][a] = c
for k in range(n) :
for i in range(n) :
for j in range(n) :
dist = d[i][k]+d[k][j]
if d[i][j] > dist :
d[i][j] = dist
ans = float('inf')
for p in permutations(road) :
dist = 0
for i in range(r-1) :
dist += d[p[i]][p[i+1]]
if ans > dist :
ans = dist
print(ans) | Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s831147698 | Runtime Error | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | from itertools import permutations
inf=10**10
n, m, r1 = map(int, input().split())
r=list(map(int, input().split()))
abc=[list(map(int, input().split())) for _ in range(m)]
d=[[inf]*n for i in range(n)]
for i in range(n):
d[i][i]=0
for ai, bi, ci in abc:
d[ai-1][bi-1]=ci
d[bi-1][ai-1]=ci
for k in range(n):
for i in range(n):
for j in range(i, n):
d[i][j]=min(d[i][j], d[i][k]+d[k][j])
d[j][i]=d[i][j]
p=list(permutations(r))
ans=inf
for pi in p:
res=0
for i in range(r1-1)
res+=d[pi[i]-1][pi[I+1]-1]
ans=min(ans, res)
print(ans) | Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s401023322 | Wrong Answer | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | import heapq
N, M, R = map(int, input().split())
class Route:
def __init__(self, B, C):
self.next = points[B]
self.distance = C
class Point:
def __init__(self, id):
self.id = id
self.neighbors = []
self.clear()
def clear(self):
self.distances = [-1] * 2
def set(self, cur):
self.distances[cur.srcid] = cur.distance
return self.isWent(0) and self.isWent(1)
def isWent(self, n):
return self.distances[n] >= 0
def addNeighbor(self, B, C):
self.neighbors.append(Route(B, C))
def optimize(self):
self.neighbors = sorted(self.neighbors, key=lambda obj: obj.distance)
class MeetInfo:
def __init__(self):
self.clear()
def clear(self):
self.distance = -1
def isMet(self):
return self.distance >= 0
class Cursor:
def __init__(self, ri, pt, meetinfo, dist=0):
self.srcid = ri
self.point = pt
self.cur_route = 0
self.distance = dist
self.meetinfo = meetinfo
if self.point.set(self):
meetinfo.distance = self.point.distances[0] + self.point.distances[1]
def cost(self):
while self.cur_route < len(self.point.neighbors):
rt = self.point.neighbors[self.cur_route]
if not rt.next.isWent(self.srcid):
break
self.cur_route += 1
else:
return None
return self.distance + rt.distance
def progress(self):
nextrt = self.point.neighbors[self.cur_route]
addcursor(
Cursor(
self.srcid, nextrt.next, self.meetinfo, self.distance + nextrt.distance
)
)
self.cur_route += 1
addcursor(self)
def __lt__(self, other):
return True
points = [Point(i) for i in range(N + 1)]
in_r = [ri for ri in map(int, input().split())]
for A, B, C in (map(int, input().split()) for _ in range(M)):
points[A].addNeighbor(B, C)
points[B].addNeighbor(A, C)
for x in points:
x.optimize()
def addcursor(cur):
c = cur.cost()
if not c is None:
heapq.heappush(hq, (c, cur))
def getRs(rs=None, cnt=-1, ret=None):
if rs is None:
rs = [False] * R
ret = []
cnt = R
if cnt <= 0:
yield ret
return
cnt -= 1
for i in range(R):
if not rs[i]:
rs[i] = True
ret.append(i)
yield from getRs(rs, cnt, ret)
ret.pop()
rs[i] = False
Rmatrix = [[-1 for _ in range(R)] for _ in range(R)]
for i in range(R):
for j in range(R):
if i >= j:
continue
meetinfo = MeetInfo()
for x in points:
x.clear()
rs = [
Cursor(i, points[ri], meetinfo) for i, ri in enumerate((in_r[i], in_r[j]))
]
hq = []
for ri in rs:
addcursor(ri)
while not meetinfo.isMet():
cost, cursor = heapq.heappop(hq)
cursor.progress()
Rmatrix[i][j] = meetinfo.distance
Rmatrix[j][i] = meetinfo.distance
M = 10**9
for r in getRs():
w = 0
for i in range(R - 1):
w += Rmatrix[r[i]][r[i + 1]]
M = min(M, w)
print(M)
| Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s534504142 | Wrong Answer | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | #!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI():
return [int(x) for x in sys.stdin.readline().split()]
def I():
return int(sys.stdin.readline())
def LS():
return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == "\n":
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
# A
def A():
n, m = LI()
a = LIR(n)
ans = 0
for i in range(2):
for j in range(2):
for k in range(2):
a.sort(
key=lambda x: (-1) ** i * x[0] + (-1) ** j * x[1] + (-1) ** k * x[2]
)
p = [0, 0, 0]
for l in range(m):
p[0] += a[l][0]
p[1] += a[l][1]
p[2] += a[l][2]
p = abs(p[0]) + abs(p[1]) + abs(p[2])
if p > ans:
ans = p
print(ans)
return
# B
def B():
def root(x):
if x == par[x]:
return x
par[x] = root(par[x])
return par[x]
def unite(x, y, su):
x = root(x)
y = root(y)
su += comb_2(s[x]) + comb_2(s[y])
if rank[x] < rank[y]:
s[y] += s[x]
su -= comb_2(s[y])
par[x] = y
else:
s[x] += s[y]
su -= comb_2(s[x])
par[y] = x
if rank[x] == rank[y]:
rank[x] += 1
return su
def comb_2(a):
return a * (a - 1) // 2
n, m = LI()
v = LIR(m)
par = [i for i in range(n)]
rank = [0] * n
s = [1] * n
su = comb_2(n)
ans = [su]
for a, b in v[:0:-1]:
a -= 1
b -= 1
if root(a) != root(b):
su = unite(a, b, su)
ans.append(su)
for i in ans[::-1]:
print(i)
return
# C
def C():
def root(x):
if par[x] == x:
return par[x]
r = root(par[x])
d[x] += d[par[x]]
par[x] = r
return par[x]
def weight(x):
root(x)
return d[x]
def unite(x, y, w):
w += weight(x)
w -= weight(y)
x = root(x)
y = root(y)
if rank[x] < rank[y]:
par[x] = y
d[x] = -w
else:
par[y] = x
d[y] = w
if rank[x] == rank[y]:
rank[x] += 1
n, m = LI()
par = [i for i in range(n)]
rank = [0] * n
d = [0] * n
for i in range(m):
l, r, w = LI()
l -= 1
r -= 1
if root(l) != root(r):
unite(l, r, w)
else:
if weight(r) - weight(l) != w:
print("No")
return
print("Yes")
return
# D
def D():
h, w = LI()
n = I()
a = LI()
ans = [0] * h * w
p = 0
for i in range(n):
for j in range(a[i]):
ans[p + j] = i + 1
p += a[i]
for i in range(h):
s = ans[i * w : (i + 1) * w]
if i % 2:
print(*s[::-1])
else:
print(*s)
return
# E
def E():
n, k = LI()
s = [int(x) for x in input()]
f = [0] * n
j = 0
su = 1
p = s[0]
for i in range(1, n):
if s[i] != p:
f[j] = su
j += 1
su = 1
p = s[i]
else:
su += 1
f[j] = su
f.append(0)
if s[0]:
m = sum(f[: 2 * k + 1])
ans = m
for i in range(2 * k + 1, n):
m -= f[i - 2 * k - 1]
if not i % 2:
m += f[i - 1]
m += f[i]
ans = max(m, ans)
else:
m = sum(f[: 2 * k])
ans = m
for i in range(2 * k, n):
m -= f[i - 2 * k]
if not i % 2:
m += f[i]
m += f[i + 1]
ans = max(m, ans)
print(ans)
return
# F
def F():
n = I()
a = LI()
s = [0, 0, 0]
for i in a:
if i % 4 == 0:
s[0] += 1
elif i % 2 == 0:
s[1] += 1
else:
s[2] += 1
a = [0]
while 1:
if s[2]:
if a[-1] == 2:
print("No")
return
s[2] -= 1
a.append(2)
if s[0]:
s[0] -= 1
a.append(0)
elif s[1]:
if a[-1] == 2:
print("No")
else:
print("Yes")
return
else:
print("Yes")
return
return
# G
def G():
n, m, l = LI()
r = LI()
for i in range(l):
r[i] -= 1
d = [[float("inf")] * n for i in range(n)]
for i in range(n):
d[i][i] = 0
for i in range(m):
a, b, c = LI()
a -= 1
b -= 1
d[a][b] = c
d[b][a] = c
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])
m = 1 << l
dp = [[float("inf")] * l for i in range(m)]
for i in range(l):
dp[1 << i][i] = 0
for i in range(l):
x = r[i]
for b in range(m):
if not b & (1 << i):
continue
for j in range(l):
if b & (1 << j):
continue
nb = b | (1 << j)
y = r[j]
res = dp[b][i] + d[x][y]
if res < dp[nb][j]:
dp[nb][j] = res
print(min(dp[m - 1]))
return
# H
def H():
return
# I
def I_():
return
# Solve
if __name__ == "__main__":
G()
| Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s628783434 | Wrong Answer | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | from subprocess import call
call(
(
"pypy3",
"-c",
"""N,M,R=map(int,input().split())
r=list(map(int,input().split()))
A=[list(map(int,input().split())) for i in range(M)]
d=[[float("inf")]*N for i in range(N)]
for a,b,c in A:
d[a-1][b-1]=c
d[b-1][a-1]=c
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])
import itertools
ans=10**5*8
for i in itertools.permutations(range(R),R):
D=0
for j in range(R-1):
D+=d[r[i[j]]-1][r[i[j+1]]-1]
ans=min(D,ans)
print(ans)
""",
)
)
| Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the distance traveled by road if Joisino visits the towns in the order
that minimizes it.
* * * | s631164395 | Wrong Answer | p03608 | Input is given from Standard Input in the following format:
N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M | import scipy.sparse as S
import itertools as i
m = lambda: map(int, input().split())
N, M, _ = m()
R = m()
G = S.dok_matrix((N, N))
G.update((lambda x: ((next(x) - 1, next(x) - 1), next(x)))(m()) for _ in range(M))
G = S.csgraph.floyd_warshall(G.tocsr(), directed=0)
print(min(sum(G[a - 1, b - 1] for a, b in zip(p[1:], p)) for p in i.permutations(R)))
| Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town A_i and B_i and has a length of C_i.
Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in
this order).
She will fly to the first town she visits, and fly back from the last town she
visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by
road, what will that distance be? | [{"input": "3 3 3\n 1 2 3\n 1 2 1\n 2 3 1\n 3 1 4", "output": "2\n \n\nFor example, if she visits the towns in the order of 1, 2, 3, the distance\ntraveled will be 2, which is the minimum possible.\n\n* * *"}, {"input": "3 3 2\n 1 3\n 2 3 2\n 1 3 6\n 1 2 2", "output": "4\n \n\nThe shortest distance between Towns 1 and 3 is 4. Thus, whether she visits\nTown 1 or 3 first, the distance traveled will be 4.\n\n* * *"}, {"input": "4 6 3\n 2 3 4\n 1 2 4\n 2 3 3\n 4 3 1\n 1 4 1\n 4 2 2\n 3 1 6", "output": "3"}] |
Print the previous permutation, the given sequence and the next permutation in
the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a
space character. Note that if there is no permutation, print nothing in the
corresponding line. | s554897407 | Accepted | p02449 | A sequence is given in the following format.
$n$
$a_0 \; a_1 \; ... \; a_{n-1}$ | # AOJ ITP2_5_C: Permutation
# Python3 2018.6.24 bal4u
def next_permutation(a):
# if list has less than two elements, has no next permutation.
if len(a) < 2:
return False
# step 1: find max i for a[i] > a[i+1]
i = len(a) - 2
while i >= 0 and a[i] >= a[i + 1]:
i -= 1
if i < 0:
return False
j = i + 1
# step 2: find max k for a[k] > a[i]
k = len(a) - 1
while a[i] >= a[k]:
k -= 1
# step 3: swap a[i] and a[k]
(a[i], a[k]) = (a[k], a[i])
# step 4: reverse a[j:]
a[j:] = a[: j - 1 : -1]
return True
def prev_permutation(a):
# if list has less than two elements, has no prev permutation.
if len(a) < 2:
return False
# step 1: find max i for a[i] < a[i+1]
i = len(a) - 2
while i >= 0 and a[i] <= a[i + 1]:
i -= 1
if i < 0:
return False
j = i + 1
# step 2: find max k for a[k] < a[i]
k = len(a) - 1
while a[i] <= a[k]:
k -= 1
# step 3: swap a[i] and a[k]
(a[i], a[k]) = (a[k], a[i])
# step 4: reverse a[j:]
a[j:] = a[: j - 1 : -1]
return True
n = int(input())
a = list(map(int, input().split()))
n, p = list(a), list(a)
if prev_permutation(p):
print(*p)
print(*a)
if next_permutation(n):
print(*n)
| Permutation
For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous
permutation and the next permutation in lexicographic order. | [{"input": "3\n 2 1 3", "output": "1 3 2\n 2 1 3\n 2 3 1"}, {"input": "3\n 3 2 1", "output": "3 1 2\n 3 2 1"}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s009667610 | Wrong Answer | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | def main(N, a):
return 2
| Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s782234539 | Runtime Error | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | n = int(input())
a = [int(x) for x in input().split()]
def calc():
dp=[]
for i in range(n):
dp.append([0]*n)
for i in range(n):
dp[i][i] = a[i]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
dp[i][j] = max(a[i] - dp[i + 1][j], a[j] - dp[i][j - 1])
return dp
print(calc()[0][n - 1]) | Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s191337855 | Wrong Answer | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | # https://atcoder.jp/contests/dp/tasks/dp_l
n = int(input())
a = [0] + list(map(int, input().split())) + [0]
i = 1
j = n
if n == 1:
print(n, " 0")
res = [0, 0]
turn = 1
while i <= j:
turn = (turn + 1) % 2
if (a[i] - a[i + 1]) > a[j] - a[j - 1]:
res[turn] = res[turn] + a[i]
a[i] = 0
i = i + 1
else:
res[turn] = res[turn] + a[j]
a[j] = 0
j = j - 1
print(res[0], res[1])
| Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s364513793 | Runtime Error | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | N=int(input())
a = list(map(int, input().split()))
dp=[[0 for i in range(N+1)] for j in range(N+1)]
for i in range(1,N+1):
dp[i][i]=a[i-1]
for j in range(1,N+1):
for i in reversed(range(1,N+1)):
if i>j:
continue
if i==j:
dp[i][j]=a[i-1]
if i<j:
dp[i][j]=max(a[i-1]-dp[i+1][j],a[j-1]-dp[i][j-1])
print(dp[1][N] | Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s919903805 | Accepted | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | # -*- coding: utf-8 -*-
#############
# Libraries #
#############
import sys
input = sys.stdin.readline
import math
# from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache
#############
# Constants #
#############
MOD = 10**9 + 7
INF = float("inf")
AZ = "abcdefghijklmnopqrstuvwxyz"
#############
# Functions #
#############
######INPUT######
def I():
return int(input().strip())
def S():
return input().strip()
def IL():
return list(map(int, input().split()))
def SL():
return list(map(str, input().split()))
def ILs(n):
return list(int(input()) for _ in range(n))
def SLs(n):
return list(input().strip() for _ in range(n))
def ILL(n):
return [list(map(int, input().split())) for _ in range(n)]
def SLL(n):
return [list(map(str, input().split())) for _ in range(n)]
######OUTPUT######
def P(arg):
print(arg)
return
def Y():
print("Yes")
return
def N():
print("No")
return
def E():
exit()
def PE(arg):
print(arg)
exit()
def YE():
print("Yes")
exit()
def NE():
print("No")
exit()
#####Shorten#####
def DD(arg):
return defaultdict(arg)
#####Inverse#####
def inv(n):
return pow(n, MOD - 2, MOD)
######Combination######
kaijo_memo = []
def kaijo(n):
if len(kaijo_memo) > n:
return kaijo_memo[n]
if len(kaijo_memo) == 0:
kaijo_memo.append(1)
while len(kaijo_memo) <= n:
kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
return kaijo_memo[n]
gyaku_kaijo_memo = []
def gyaku_kaijo(n):
if len(gyaku_kaijo_memo) > n:
return gyaku_kaijo_memo[n]
if len(gyaku_kaijo_memo) == 0:
gyaku_kaijo_memo.append(1)
while len(gyaku_kaijo_memo) <= n:
gyaku_kaijo_memo.append(
gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo), MOD - 2, MOD) % MOD
)
return gyaku_kaijo_memo[n]
def nCr(n, r):
if n == r:
return 1
if n < r or r < 0:
return 0
ret = 1
ret = ret * kaijo(n) % MOD
ret = ret * gyaku_kaijo(r) % MOD
ret = ret * gyaku_kaijo(n - r) % MOD
return ret
######Factorization######
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-(n**0.5) // 1)) + 1):
if temp % i == 0:
cnt = 0
while temp % i == 0:
cnt += 1
temp //= i
arr.append([i, cnt])
if temp != 1:
arr.append([temp, 1])
if arr == []:
arr.append([n, 1])
return arr
#####MakeDivisors######
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n // i)
return divisors
#####MakePrimes######
def make_primes(N):
max = int(math.sqrt(N))
seachList = [i for i in range(2, N + 1)]
primeNum = []
while seachList[0] <= max:
primeNum.append(seachList[0])
tmp = seachList[0]
seachList = [i for i in seachList if i % tmp != 0]
primeNum.extend(seachList)
return primeNum
#####GCD#####
def gcd(a, b):
while b:
a, b = b, a % b
return a
#####LCM#####
def lcm(a, b):
return a * b // gcd(a, b)
#####BitCount#####
def count_bit(n):
count = 0
while n:
n &= n - 1
count += 1
return count
#####ChangeBase#####
def base_10_to_n(X, n):
if X // n:
return base_10_to_n(X // n, n) + [X % n]
return [X % n]
def base_n_to_10(X, n):
return sum(int(str(X)[-i - 1]) * n**i for i in range(len(str(X))))
def base_10_to_n_without_0(X, n):
X -= 1
if X // n:
return base_10_to_n_without_0(X // n, n) + [X % n]
return [X % n]
#####IntLog#####
def int_log(n, a):
count = 0
while n >= a:
n //= a
count += 1
return count
#############
# Main Code #
#############
N = I()
A = IL()
prev = [a * (1 if N % 2 else -1) for a in A]
phase = N
while phase > 1:
phase -= 1
now = []
for i in range(phase):
if phase % 2:
now.append(max(prev[i] + A[i + N - phase], prev[i + 1] + A[i]))
else:
now.append(min(prev[i] - A[i + N - phase], prev[i + 1] - A[i]))
prev = now[:]
print(prev[0])
| Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s139077845 | Runtime Error | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | N = input()
a = input.split()
if N<1:
return None
#check who plays last
currentTaro = ((N%2)==1)
#initilise best-scores list for last player with one element
bestScores = [(el if currentTaro else -el) for el in a]
bestScores = [(el,el) for el in bestScores]
for i in range(1,N):
#alternate player
currentTaro = not currentTaro
newBestScores=[]
for j in range(N):
#get best score if number removed from left
bestLeftScore=None
if j>=i:
leftScoresAfterRemoval=(bestScores[j-1][0],bestScores[j-i][1])
bestLeftScore= min(leftScoresAfterRemoval)+a[j] if currentTaro else max(leftScoresAfterRemoval)-a[j]
#get best score if number removed from right
bestRightScore=None
if j<=N-1-i:
rightScoresAfterRemoval=(bestScores[j+1][1],bestScores[j+i][0])
bestRightScore= min(rightScoresAfterRemoval)+a[j] if currentTaro else max(rightScoresAfterRemoval)-a[j]
#add to newBestScores
newBestScores.append((bestLeftScore,bestRightScore))
bestScores=newBestScores
#return best score
result = max(bestScores[0][1],bestScores[-1][0])
print(result) | Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s217805938 | Accepted | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | N, *A = map(int, open(0).read().split())
r = range
S = [0] * -~N
for l in r(N):
S = [
(
max(S[i + 1] + A[i], S[i] + A[i + l])
if (l ^ N) & 1
else min(S[i + 1] - A[i], S[i] - A[i + l])
)
for i in r(N - l)
]
print(S[0])
| Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s861303797 | Runtime Error | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | import subprocess as sp
import sys
code = r"""
n=int(input())
a=[int(j) for j in input().split()]
dp=[[0]*(n+1) for i in range(n+1)]
for i in range(n)[::-1]:
for j in range(i,n):
if (n+i-j-1)%2==0:
dp[i][j]=max(dp[i+1][j]+a[i],dp[i][j-1]+a[j])
else:
dp[i][j]=min(dp[i+1][j]-a[i],dp[i][j-1]-a[j])
print(dp[0][n-1])
"""
with open("A.py", "w") as f:
f.write(code)
sp.Popen(["pypy", "-std=pypy", "-O2", "A.py"]).communicate()
sp.Popen(["./a.out"], stdin=sys.stdin, stdout=sys.stdout).communicate()
| Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s170121787 | Runtime Error | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | n = int(input())
a = list(map(int, input().split()))
d = {}
def k(a):
return ",".join(map(str, a))
def dp(a):
ka = k(a)
if ka in d:
return [d[ka][0], d[ka][1]]
if len(a) == 1:
d[ka] = [a[0], []]
return a[0], []
elif len(a) == 2:
d[ka] = [max(a), [min(a)]]
return max(a), [min(a)]
else:
if a[0] - dp(a[1:])[0] > a[-1] - dp(a[:-1])[0]:
d[ka] = [a[0], a[1:]]
return a[0], a[1:]
else:
d[ka] = [a[-1], a[:-1]]
return a[-1], a[:-1]
x, y = 0, 0
while a != []:
x_, a = dp(a)
x += x_
if a == []:
break
y_, a = dp(a)
y += y_
print(x - y)
| Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the resulting value of X - Y, assuming that the two players play
optimally.
* * * | s876197989 | Accepted | p03171 | Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N | N = int(input())
arr = [int(i) for i in input().split()]
tot = sum(arr)
mem = [[0] * N for i in range(N)]
# updating bottom 2 rows
# mem[N-2][j]
# mem[N-1][N-1]
if N == 1:
print("%s" % arr[0])
else:
mem[N - 1][N - 1] = arr[N - 1]
mem[N - 2][N - 2] = arr[N - 2]
mem[N - 2][N - 1] = max(arr[N - 2], arr[N - 2])
# updating leftmost cols
mem[0][0] = arr[0]
mem[0][1] = max(arr[0], arr[1])
mem[1][1] = arr[1]
for i in range(N - 3, -1, -1):
for j in range(i, N):
if i == 0 and j <= 1 or i == 1 and j == 1:
continue
val1 = arr[i] + min(mem[i + 1][j - 1], mem[i + 2][j])
val2 = arr[j] + min(mem[i + 1][j - 1], mem[i][j - 2])
mem[i][j] = max(val1, val2)
# print(mem)
tmp = tot - mem[0][N - 1]
ans = mem[0][N - 1] - tmp
print("%s" % ans)
| Statement
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a
becomes empty, the two players perform the following operation alternately,
starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.
Let X and Y be Taro's and Jiro's total score at the end of the game,
respectively. Taro tries to maximize X - Y, while Jiro tries to minimize X -
Y.
Assuming that the two players play optimally, find the resulting value of X -
Y. | [{"input": "4\n 10 80 90 30", "output": "10\n \n\nThe game proceeds as follows when the two players play optimally (the element\nbeing removed is written bold):\n\n * Taro: (10, 80, 90, **30**) \u2192 (10, 80, 90)\n * Jiro: (10, 80, **90**) \u2192 (10, 80)\n * Taro: (10, **80**) \u2192 (10)\n * Jiro: (**10**) \u2192 ()\n\nHere, X = 30 + 80 = 110 and Y = 90 + 10 = 100.\n\n* * *"}, {"input": "3\n 10 100 10", "output": "-80\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (**10** , 100, 10) \u2192 (100, 10)\n * Jiro: (**100** , 10) \u2192 (10)\n * Taro: (**10**) \u2192 ()\n\nHere, X = 10 + 10 = 20 and Y = 100.\n\n* * *"}, {"input": "1\n 10", "output": "10\n \n\n* * *"}, {"input": "10\n 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1", "output": "4999999995\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "6\n 4 2 9 7 1 5", "output": "2\n \n\nThe game proceeds, for example, as follows when the two players play\noptimally:\n\n * Taro: (4, 2, 9, 7, 1, **5**) \u2192 (4, 2, 9, 7, 1)\n * Jiro: (**4** , 2, 9, 7, 1) \u2192 (2, 9, 7, 1)\n * Taro: (2, 9, 7, **1**) \u2192 (2, 9, 7)\n * Jiro: (2, 9, **7**) \u2192 (2, 9)\n * Taro: (2, **9**) \u2192 (2)\n * Jiro: (**2**) \u2192 ()\n\nHere, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13."}] |
Print the number of combinations in a line. | s597230843 | Runtime Error | p02330 | The input is given in the following format.
N K L R
a1 a2 ... aN | from itertools import combinations as C
N, K, L, R = map(int, input().split())
a = list(map(int, input().split()))
v = [i for i in range(N)]
ans = 0
for ii in list(C(v, K)):
tmp = 0
flag = True
for i in ii:
tmp += a[i]
if tmp > R:
flag = False
break
if flag and tmp >= L:
ans += 1
print(ans)
| Coin Combination Problem II
You have N coins each of which has a value ai. Find the number of combinations
that result when you choose K different coins in such a way that the total
value of the coins is greater than or equal to L and less than or equal to R. | [{"input": "2 2 1 9\n 5 1", "output": "1"}, {"input": "5 2 7 19\n 3 5 4 2 2", "output": "5"}] |
If we will have a bingo, print `Yes`; otherwise, print `No`.
* * * | s021863063 | Accepted | p02760 | Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N | board = [0, 0, 0, 0, 0, 0, 0, 0, 0]
board[0], board[1], board[2] = map(int, input().split())
board[3], board[4], board[5] = map(int, input().split())
board[6], board[7], board[8] = map(int, input().split())
for _ in range(int(input())):
x = int(input())
if x in board:
board[board.index(x)] = "X"
found = "No"
if board[0] == "X":
if board[1] == "X" and board[2] == "X":
found = "Yes"
elif board[4] == "X" and board[8] == "X":
found = "Yes"
elif board[3] == "X" and board[6] == "X":
found = "Yes"
if board[8] == "X":
if board[5] == "X" and board[2] == "X":
found = "Yes"
elif board[7] == "X" and board[6] == "X":
found = "Yes"
if board[4] == "X":
if board[1] == "X" and board[7] == "X":
found = "Yes"
elif board[3] == "X" and board[5] == "X":
found = "Yes"
elif board[2] == "X" and board[6] == "X":
found = "Yes"
print(found)
| Statement
We have a bingo card with a 3\times3 grid. The square at the i-th row from the
top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet
contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is,
the sheet will contain three marked numbers in a row, column, or diagonal. | [{"input": "84 97 66\n 79 89 11\n 61 59 7\n 7\n 89\n 7\n 87\n 79\n 24\n 84\n 30", "output": "Yes\n \n\nWe will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal\nfrom the top-left to the bottom-right.\n\n* * *"}, {"input": "41 7 46\n 26 89 2\n 78 92 8\n 5\n 6\n 45\n 16\n 57\n 17", "output": "No\n \n\nWe will mark nothing.\n\n* * *"}, {"input": "60 88 34\n 92 41 43\n 65 73 48\n 10\n 60\n 43\n 88\n 11\n 48\n 73\n 65\n 41\n 92\n 34", "output": "Yes\n \n\nWe will mark all the squares."}] |
If we will have a bingo, print `Yes`; otherwise, print `No`.
* * * | s373213883 | Wrong Answer | p02760 | Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N | from collections import OrderedDict
f_row_nums = list(input().split())
s_row_nums = list(input().split())
t_row_nums = list(input().split())
N = int(input())
chosen_nums = [input() for _ in range(N)]
f_dict = OrderedDict()
for key in f_row_nums:
print(key)
f_dict[key] = False
s_dict = OrderedDict()
for key in s_row_nums:
s_dict[key] = False
t_dict = OrderedDict()
for key in t_row_nums:
t_dict[key] = False
for num in chosen_nums:
if num in f_dict:
f_dict[num] = True
if num in s_dict:
s_dict[num] = True
if num in t_dict:
t_dict[num] = True
f_rows = list(f_dict.values())
s_rows = list(s_dict.values())
t_rows = list(t_dict.values())
f_cols = [f_rows[0], s_rows[0], t_rows[0]]
s_cols = [f_rows[1], s_rows[1], t_rows[1]]
t_cols = [f_rows[2], s_rows[2], t_rows[2]]
out = "No"
if (
all(f_rows)
or all(s_rows)
or all(t_rows)
or all(f_cols)
or all(s_cols)
or all(t_cols)
):
out = "Yes"
elif f_rows[0] and s_rows[1] and t_rows[2]:
out = "Yes"
elif f_rows[2] and s_rows[1] and t_rows[0]:
out = "Yes"
print(out)
| Statement
We have a bingo card with a 3\times3 grid. The square at the i-th row from the
top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet
contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is,
the sheet will contain three marked numbers in a row, column, or diagonal. | [{"input": "84 97 66\n 79 89 11\n 61 59 7\n 7\n 89\n 7\n 87\n 79\n 24\n 84\n 30", "output": "Yes\n \n\nWe will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal\nfrom the top-left to the bottom-right.\n\n* * *"}, {"input": "41 7 46\n 26 89 2\n 78 92 8\n 5\n 6\n 45\n 16\n 57\n 17", "output": "No\n \n\nWe will mark nothing.\n\n* * *"}, {"input": "60 88 34\n 92 41 43\n 65 73 48\n 10\n 60\n 43\n 88\n 11\n 48\n 73\n 65\n 41\n 92\n 34", "output": "Yes\n \n\nWe will mark all the squares."}] |
If we will have a bingo, print `Yes`; otherwise, print `No`.
* * * | s404995042 | Wrong Answer | p02760 | Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N | A = [list(map(int, input().split())) for i in range(3)]
b = [int(input()) for i in range(int(input()))]
X = [0] * 3
for i in range(3):
X[i] = [1 if i in b else 0 for i in A[i]]
R = [
*[sum(i) for i in X],
*[sum([x[i] for i in range(3)]) for x in X],
X[0][0] + X[1][1] + X[2][2],
X[0][2] + X[1][1] + X[2][0],
]
print("Yes" if 3 <= max(R) else "No")
| Statement
We have a bingo card with a 3\times3 grid. The square at the i-th row from the
top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet
contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is,
the sheet will contain three marked numbers in a row, column, or diagonal. | [{"input": "84 97 66\n 79 89 11\n 61 59 7\n 7\n 89\n 7\n 87\n 79\n 24\n 84\n 30", "output": "Yes\n \n\nWe will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal\nfrom the top-left to the bottom-right.\n\n* * *"}, {"input": "41 7 46\n 26 89 2\n 78 92 8\n 5\n 6\n 45\n 16\n 57\n 17", "output": "No\n \n\nWe will mark nothing.\n\n* * *"}, {"input": "60 88 34\n 92 41 43\n 65 73 48\n 10\n 60\n 43\n 88\n 11\n 48\n 73\n 65\n 41\n 92\n 34", "output": "Yes\n \n\nWe will mark all the squares."}] |
If we will have a bingo, print `Yes`; otherwise, print `No`.
* * * | s418164323 | Wrong Answer | p02760 | Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N | a11, a12, a13 = input().split()
a21, a22, a23 = input().split()
a31, a32, a33 = input().split()
lst = [a11, a12, a13, a21, a22, a23, a31, a32, a33]
bingo = []
n = int(input())
for i in range(n):
ai = input()
if ai in lst:
bingo.append(lst.index(ai))
if 4 in bingo:
if (0 and 8) in bingo:
print("Yes")
exit()
if (1 and 7) in bingo:
print("Yes")
exit()
if (2 and 6) in bingo:
print("Yes")
exit()
if (3 and 5) in bingo:
print("Yes")
exit()
if 0 in bingo:
if (1 and 2) in bingo:
print("Yes")
exit()
if (3 and 6) in bingo:
print("Yes")
exit()
if 8 in bingo:
if (2 and 5) in bingo:
print("Yes")
exit()
if (6 and 7) in bingo:
print("Yes")
exit()
print("No")
| Statement
We have a bingo card with a 3\times3 grid. The square at the i-th row from the
top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet
contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is,
the sheet will contain three marked numbers in a row, column, or diagonal. | [{"input": "84 97 66\n 79 89 11\n 61 59 7\n 7\n 89\n 7\n 87\n 79\n 24\n 84\n 30", "output": "Yes\n \n\nWe will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal\nfrom the top-left to the bottom-right.\n\n* * *"}, {"input": "41 7 46\n 26 89 2\n 78 92 8\n 5\n 6\n 45\n 16\n 57\n 17", "output": "No\n \n\nWe will mark nothing.\n\n* * *"}, {"input": "60 88 34\n 92 41 43\n 65 73 48\n 10\n 60\n 43\n 88\n 11\n 48\n 73\n 65\n 41\n 92\n 34", "output": "Yes\n \n\nWe will mark all the squares."}] |
If we will have a bingo, print `Yes`; otherwise, print `No`.
* * * | s706688794 | Accepted | p02760 | Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N | class Cell:
def __init__(self, x, y, num):
self.x = x
self.y = y
self.num = num
self.opened = False
def open(self) -> None:
self.opened = True
def punch(self, called_number: int) -> None:
if called_number == self.num:
self.open()
class Line:
"""タテ・ヨコ・ナナメいずれかのライン"""
def __init__(self, values):
self.values = values
def __post_init__(self):
# 気分で書いたけど、今回はなくても良いと思う
if len(self.values) != 3:
raise ValueError("今回は3つ以外ありえないよ〜")
def is_bingo(self) -> bool:
return all([c.opened for c in self.values])
class Cells:
"""Boardって概念もあると思うけど、単純にCellのコレクションでいく"""
def __init__(self, values):
self.values = values
def punch(self, called_numbers) -> None:
for called_number in called_numbers:
for cell in self.values:
cell.punch(called_number)
def has_one_more_bingo(self) -> bool:
# タテ
tate1 = Line([c for c in self.values if c.y == 1])
tate2 = Line([c for c in self.values if c.y == 2])
tate3 = Line([c for c in self.values if c.y == 3])
# ヨコ
yoko1 = Line([c for c in self.values if c.x == 1])
yoko2 = Line([c for c in self.values if c.x == 2])
yoko3 = Line([c for c in self.values if c.x == 3])
# ナナメ
# 左上から右下に向かってのナナメ(\)
diag1 = Line([c for c in self.values if c.x == c.y])
# 右上から左下に向かってのナナメ(/)
diag2 = Line(
[
c
for c in self.values
if (
((c.x, c.y) == (1, 3))
or ((c.x, c.y) == (2, 2))
or ((c.x, c.y) == (3, 1))
)
]
)
return any(
[
tate1.is_bingo(),
tate2.is_bingo(),
tate3.is_bingo(),
yoko1.is_bingo(),
yoko2.is_bingo(),
yoko3.is_bingo(),
diag1.is_bingo(),
diag2.is_bingo(),
]
)
@classmethod
def create(cls, A):
cells = []
for row, line in enumerate(A, start=1):
for col, num in enumerate(line, start=1):
cell = Cell(x=row, y=col, num=num)
cells.append(cell)
return Cells(cells)
def actual(n, A, B):
cells = Cells.create(A)
cells.punch(B)
if cells.has_one_more_bingo():
return "Yes"
return "No"
line1 = list(map(int, input().split()))
line2 = list(map(int, input().split()))
line3 = list(map(int, input().split()))
A = [line1, line2, line3]
n = int(input())
B = []
for _ in range(n):
b = int(input())
B.append(b)
print(actual(n, A, B))
| Statement
We have a bingo card with a 3\times3 grid. The square at the i-th row from the
top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet
contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is,
the sheet will contain three marked numbers in a row, column, or diagonal. | [{"input": "84 97 66\n 79 89 11\n 61 59 7\n 7\n 89\n 7\n 87\n 79\n 24\n 84\n 30", "output": "Yes\n \n\nWe will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal\nfrom the top-left to the bottom-right.\n\n* * *"}, {"input": "41 7 46\n 26 89 2\n 78 92 8\n 5\n 6\n 45\n 16\n 57\n 17", "output": "No\n \n\nWe will mark nothing.\n\n* * *"}, {"input": "60 88 34\n 92 41 43\n 65 73 48\n 10\n 60\n 43\n 88\n 11\n 48\n 73\n 65\n 41\n 92\n 34", "output": "Yes\n \n\nWe will mark all the squares."}] |
If we will have a bingo, print `Yes`; otherwise, print `No`.
* * * | s924755234 | Runtime Error | p02760 | Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N | a = input()
(n, m) = a.split(" ")
n = int(n)
m = int(m)
print(n)
| Statement
We have a bingo card with a 3\times3 grid. The square at the i-th row from the
top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet
contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is,
the sheet will contain three marked numbers in a row, column, or diagonal. | [{"input": "84 97 66\n 79 89 11\n 61 59 7\n 7\n 89\n 7\n 87\n 79\n 24\n 84\n 30", "output": "Yes\n \n\nWe will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal\nfrom the top-left to the bottom-right.\n\n* * *"}, {"input": "41 7 46\n 26 89 2\n 78 92 8\n 5\n 6\n 45\n 16\n 57\n 17", "output": "No\n \n\nWe will mark nothing.\n\n* * *"}, {"input": "60 88 34\n 92 41 43\n 65 73 48\n 10\n 60\n 43\n 88\n 11\n 48\n 73\n 65\n 41\n 92\n 34", "output": "Yes\n \n\nWe will mark all the squares."}] |
If we will have a bingo, print `Yes`; otherwise, print `No`.
* * * | s991460361 | Wrong Answer | p02760 | Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N | def row_sums(B):
return sum(B[0]) == 0 or sum(B[1]) == 0 or sum(B[2]) == 0
def diagonal_sum(M):
i, j = -1, -1
sums = 0
for _ in range(3):
i += 1
j += 1
sums += M[i][j]
return sums == 0
def column_sum(M):
columns = list(zip(*M))
return row_sums(columns)
has = [[int(x) for x in input().split()] for _ in range(3)]
calls = int(input())
for _ in range(calls):
current = int(input())
for i in range(3):
if current in has[i]:
has[i][has[i].index(current)] = 0
# print(has)
"""
if row_sums(has) or column_sum(has) or diagonal_sum(has):
print('Yes')
else:print('No')
"""
answer = "NO"
for i in range(3):
if has[i][0] == has[i][1] == has[i][2] == 0:
ans = "Yes"
if has[0][i] == has[1][i] == has[2][i] == 0:
ans = "Yes"
if has[0][0] == has[1][1] == has[2][2] == 0:
ans = "Yes"
if has[2][0] == has[1][1] == has[0][2] == 0:
ans = "Yes"
print(answer)
| Statement
We have a bingo card with a 3\times3 grid. The square at the i-th row from the
top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet
contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is,
the sheet will contain three marked numbers in a row, column, or diagonal. | [{"input": "84 97 66\n 79 89 11\n 61 59 7\n 7\n 89\n 7\n 87\n 79\n 24\n 84\n 30", "output": "Yes\n \n\nWe will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal\nfrom the top-left to the bottom-right.\n\n* * *"}, {"input": "41 7 46\n 26 89 2\n 78 92 8\n 5\n 6\n 45\n 16\n 57\n 17", "output": "No\n \n\nWe will mark nothing.\n\n* * *"}, {"input": "60 88 34\n 92 41 43\n 65 73 48\n 10\n 60\n 43\n 88\n 11\n 48\n 73\n 65\n 41\n 92\n 34", "output": "Yes\n \n\nWe will mark all the squares."}] |
If we will have a bingo, print `Yes`; otherwise, print `No`.
* * * | s341397323 | Wrong Answer | p02760 | Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N | s, a = "036,048,246,258,345,678,", open(0).read().split()
for i in a[9:]:
s = s.replace(str(a.index(i)), "")
print("NYoe s"[",," in s :: 2])
| Statement
We have a bingo card with a 3\times3 grid. The square at the i-th row from the
top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet
contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is,
the sheet will contain three marked numbers in a row, column, or diagonal. | [{"input": "84 97 66\n 79 89 11\n 61 59 7\n 7\n 89\n 7\n 87\n 79\n 24\n 84\n 30", "output": "Yes\n \n\nWe will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal\nfrom the top-left to the bottom-right.\n\n* * *"}, {"input": "41 7 46\n 26 89 2\n 78 92 8\n 5\n 6\n 45\n 16\n 57\n 17", "output": "No\n \n\nWe will mark nothing.\n\n* * *"}, {"input": "60 88 34\n 92 41 43\n 65 73 48\n 10\n 60\n 43\n 88\n 11\n 48\n 73\n 65\n 41\n 92\n 34", "output": "Yes\n \n\nWe will mark all the squares."}] |
Print the sorted sequence. Two contiguous elements of the sequence should be
separated by a space character. | s176164848 | Accepted | p02275 | The first line of the input includes an integer _n_ , the number of elements
in the sequence.
In the second line, _n_ elements of the sequence are given separated by spaces
characters. | N = int(input())
A = list(map(int, input().split()))
M = [0] * 10001
for a in A:
M[a] += 1
first = True
for i, m in enumerate(M):
if m > 0:
if first:
print(*([i] * m), end="")
first = False
else:
print(" ", end="")
print(*([i] * m), end="")
print()
| Counting Sort
Counting sort can be used for sorting elements in an array which each of the n
input elements is an integer in the range 0 to k. The idea of counting sort is
to determine, for each input element x, the number of elements less than x as
C[x]. This information can be used to place element x directly into its
position in the output array B. This scheme must be modified to handle the
situation in which several elements have the same value. Please see the
following pseudocode for the detail:
Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1
Write a program which sorts elements of given array ascending order based on
the counting sort. | [{"input": "7\n 2 5 1 3 2 3 0", "output": "0 1 2 2 3 3 5"}] |
Print the sorted sequence. Two contiguous elements of the sequence should be
separated by a space character. | s543027106 | Accepted | p02275 | The first line of the input includes an integer _n_ , the number of elements
in the sequence.
In the second line, _n_ elements of the sequence are given separated by spaces
characters. | # https: // onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/6/ALDS1_6_A
# 要素のmaxであるkさえわかっていればO(n+k)でソートできる高速なソート。天才かと思った。
# ソートしたい配列の数字をidxに対応させて、count 配列を作成. count配列を累積和。それがidxに対応しているというびっくり方法。
# ! 0 based-indexにするために、本とは違う実装
n = int(input())
A = list(map(int, input().split()))
A.sort()
print(*A)
| Counting Sort
Counting sort can be used for sorting elements in an array which each of the n
input elements is an integer in the range 0 to k. The idea of counting sort is
to determine, for each input element x, the number of elements less than x as
C[x]. This information can be used to place element x directly into its
position in the output array B. This scheme must be modified to handle the
situation in which several elements have the same value. Please see the
following pseudocode for the detail:
Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1
Write a program which sorts elements of given array ascending order based on
the counting sort. | [{"input": "7\n 2 5 1 3 2 3 0", "output": "0 1 2 2 3 3 5"}] |
Print the sorted sequence. Two contiguous elements of the sequence should be
separated by a space character. | s139153977 | Accepted | p02275 | The first line of the input includes an integer _n_ , the number of elements
in the sequence.
In the second line, _n_ elements of the sequence are given separated by spaces
characters. | N = int(input())
L = list(map(int, input().split()))
L_temp = L
A_N = 100010
counter = [0] * A_N
for l in L_temp:
counter[l] += 1
for c_idx in range(1, len(counter)):
counter[c_idx] += counter[c_idx - 1]
# print(counter)
L_sort = [0] * len(L_temp)
for l in L_temp[::-1]:
L_sort[counter[l] - 1] = l
# print(l,counter[l],L_sort)
counter[l] -= 1
print(" ".join(map(str, L_sort)))
| Counting Sort
Counting sort can be used for sorting elements in an array which each of the n
input elements is an integer in the range 0 to k. The idea of counting sort is
to determine, for each input element x, the number of elements less than x as
C[x]. This information can be used to place element x directly into its
position in the output array B. This scheme must be modified to handle the
situation in which several elements have the same value. Please see the
following pseudocode for the detail:
Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1
Write a program which sorts elements of given array ascending order based on
the counting sort. | [{"input": "7\n 2 5 1 3 2 3 0", "output": "0 1 2 2 3 3 5"}] |
Print the count modulo (10^9+7).
* * * | s268968624 | Accepted | p02625 | Input is given from Standard Input in the following format:
N M | N, M = list(map(int, input().split()))
MOD = 10**9 + 7
class mod_pack:
def __init__(self, MOD, MAX):
self.MOD = MOD
self.MAX = MAX
self.fac, self.ifac = [1] * (MAX + 1), [1] * (MAX + 1)
for i in range(1, MAX + 1):
self.fac[i] = self.fac[i - 1] * i % MOD
self.ifac[i] = self.ifac[i - 1] * self.mpow(i, MOD - 2) % MOD
def mpow(self, x, n):
ans = 1
while n != 0:
if n & 1:
ans = ans * x % self.MOD
x = x * x % self.MOD
n = n >> 1
return ans
def mcomb(self, m, n):
if m == 0 and n == 0:
return 1
return (self.ifac[m - n] * self.ifac[n] % self.MOD) * self.fac[m] % self.MOD
def mperm(self, m, n):
if m < n:
return 0
return self.ifac[m - n] * self.fac[m] % MOD
mp = mod_pack(10**9 + 7, M)
tot = mp.mperm(M, N)
ans = 0
for k in range(1, N + 1):
# print(k, mp.mcomb(N, k), mp.mperm(M-k, N-k))
ans = (ans + (-1) ** (k - 1) * mp.mcomb(N, k) * mp.mperm(M - k, N - k)) % MOD
print((tot * (tot - ans)) % MOD)
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s973321107 | Accepted | p02625 | Input is given from Standard Input in the following format:
N M | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode("utf-8")
class CombMod:
def __init__(self, N, MOD=10**9 + 7):
N = N + 1
inv = [0] * N
fact = [0] * N
fact_inv = [0] * N
inv[0] = 0
inv[1] = 1
for n in range(2, N):
q, r = divmod(MOD, n)
inv[n] = inv[r] * (-q) % MOD
fact[0] = 1
for n in range(1, N):
fact[n] = n * fact[n - 1] % MOD
fact_inv[0] = 1
for n in range(1, N):
fact_inv[n] = fact_inv[n - 1] * inv[n] % MOD
self.fact = fact
self.fact_inv = fact_inv
self.inv = inv
def comb(self, n, r, mod=10**9 + 7):
return self.fact[n] * self.fact_inv[r] % mod * self.fact_inv[n - r] % mod
def perm(self, n, r, mod=10**9 + 7):
return self.fact[n] * self.fact_inv[n - r] % mod
def main():
N, M = in_nn()
mod = 10**9 + 7
c = CombMod(M)
ans = c.perm(M, N)
for k in range(1, N + 1):
ans -= (-1) ** (k - 1 % 2) * c.comb(N, k) * c.perm(M - k, N - k)
ans %= mod
ans *= c.perm(M, N)
ans %= mod
print(ans)
if __name__ == "__main__":
main()
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s193781758 | Accepted | p02625 | Input is given from Standard Input in the following format:
N M | n, m = map(int, input().split())
mod = pow(10, 9) + 7
x = 0
y = m - n + 1
u, v = n, 1
c, p = 1, 1
for i in range(n, 0, -1):
if i % 2 == 1:
x += (c * p) % mod
else:
x -= (c * p) % mod
x %= mod
p *= y
p %= mod
y += 1
c = (c * u * pow(v, mod - 2, mod)) % mod
u -= 1
v += 1
p = 1
for i in range(n):
p *= m - i
p %= mod
ans = (pow(p, 2, mod) - (p * x)) % mod
print(ans)
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s792420710 | Runtime Error | p02625 | Input is given from Standard Input in the following format:
N M | N = int(input())
print(sum((N // i) * (N // i + 1) // 2) * i for i in range(1, N + 1))
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s658470538 | Accepted | p02625 | Input is given from Standard Input in the following format:
N M | import sys
def input():
return sys.stdin.readline().strip()
def list2d(a, b, c):
return [[c] * b for i in range(a)]
def list3d(a, b, c, d):
return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e):
return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1):
return int(-(-x // y))
def INT():
return int(input())
def MAP():
return map(int, input().split())
def LIST(N=None):
return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes():
print("Yes")
def No():
print("No")
def YES():
print("YES")
def NO():
print("NO")
sys.setrecursionlimit(10**9)
INF = 10**19
MOD = 10**9 + 7
EPS = 10**-10
class ModTools:
"""階乗・逆元用のテーブルを構築する"""
def __init__(self, MAX, MOD):
# nCrならn、nHrならn+rまで作る
MAX += 1
self.MAX = MAX
self.MOD = MOD
# 階乗テーブル
factorial = [1] * MAX
factorial[0] = factorial[1] = 1
for i in range(2, MAX):
factorial[i] = factorial[i - 1] * i % MOD
# 階乗の逆元テーブル
inverse = [1] * MAX
# powに第三引数入れると冪乗のmod付計算を高速にやってくれる
inverse[MAX - 1] = pow(factorial[MAX - 1], MOD - 2, MOD)
for i in range(MAX - 2, -1, -1):
# 最後から戻っていくこのループならMAX回powするより処理が速い
inverse[i] = inverse[i + 1] * (i + 1) % MOD
self.fact = factorial
self.inv = inverse
def nCr(self, n, r):
"""組み合わせ"""
if n < r:
return 0
# 10C7 = 10C3
r = min(r, n - r)
# 分子の計算
numerator = self.fact[n]
# 分母の計算
denominator = self.inv[r] * self.inv[n - r] % self.MOD
return numerator * denominator % self.MOD
def nHr(self, n, r):
"""重複組み合わせ"""
# r個選ぶところにN-1個の仕切りを入れる
return self.nCr(r + n - 1, r)
def nPr(self, n, r):
"""順列"""
if n < r:
return 0
return self.fact[n] * self.inv[n - r] % self.MOD
N, M = MAP()
mt = ModTools(M + 1, MOD)
acnt = mt.nPr(M, N)
bcnt = 0
for i in range(N + 1):
bcnt += mt.nCr(N, i) * mt.nPr(M - i, N - i) * (-1) ** i
bcnt %= MOD
ans = acnt * bcnt % MOD
print(ans)
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s419618427 | Runtime Error | p02625 | Input is given from Standard Input in the following format:
N M | N, M, K = (int(s) for s in input().rstrip().split())
A = [int(s) for s in input().rstrip().split()]
B = [int(s) for s in input().rstrip().split()]
i, j = (0, 0)
sum, count = (0, 0)
while sum < K:
if (i < N) and (j < M):
if A[i] <= B[j]:
sum += A[i]
i += 1
count += 1
else:
sum += B[j]
j += 1
count += 1
elif i < N:
sum += A[i]
i += 1
count += 1
elif j < M:
sum += B[j]
j += 1
count += 1
else:
break
if sum > K:
count -= 1
print(count)
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s067441800 | Accepted | p02625 | Input is given from Standard Input in the following format:
N M | def main():
N, M = map(int, input().split())
P = 10**9 + 7
# 全部:mPn ** 2通り
# A:mPn通り
mPn = M
for i in range(M - N + 1, M):
mPn = mPn * i % P
"""
#Bのダメなパターン:固定したAに対して、∑(k=1...N)(-1)**(k)*nCk*(m-k)P(n-k)
# 少なくとも1つがAと同じ
# Aと同じ箇所の取り方:nC1
# N-1個の数の組み合わせ:(m-1)(m-2)...(m-n+1) = (m-1)P(n-1)
# 少なくとも2つがAと同じ
# Aと同じ箇所の取り方:nC2
# N-2個の数の組み合わせ:(m-2)(m-3)...(m-n+1) = (m-2)P(n-2)
"""
num_b = 0
nCk = 1
m_kPn_k = mPn
for k in range(1, N + 1):
nCk = nCk * (N - k + 1) * pow(k, P - 2, P) % P
m_kPn_k = m_kPn_k * pow(M - k + 1, P - 2, P) % P
num_b = (num_b + ((-1) ** (k - 1)) * nCk * m_kPn_k) % P
print((mPn**2 - mPn * num_b) % P)
main()
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s065531636 | Accepted | p02625 | Input is given from Standard Input in the following format:
N M | M = 10**9 + 7
n, m = map(int, input().split())
F = [1]
for i in range(1, m + 1):
F += [i * F[-1] % M]
c = lambda n, r: F[n] * pow(F[r] * F[n - r], M - 2, M) % M
p = lambda n, r: F[n] * pow(F[n - r], M - 2, M) % M
a = 0
for k in range(n + 1):
a += (-1) ** k * c(n, k) * p(m, k) * p(m - k, n - k) ** 2 % M
print(a % M)
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s594871830 | Accepted | p02625 | Input is given from Standard Input in the following format:
N M | class Mod:
def __init__(self, mod, n_max):
"""
イニシャライザ
予め 1~nの階乗と階乗の逆元を計算しておく
:param mod: 法
:param n_max: nの最大値(100,000で約1秒)
"""
self.mod = mod
self.n_max = n_max
self.facts = [1, 1]
self.inverses = [None, 1]
self.fact_inverses = [1, 1]
for i in range(2, self.n_max + 1):
self.facts.append(self.facts[i - 1] * i % self.mod)
# self.inverses.append(mod_inverse(i, self.mod))
self.inverses.append(
self.mod - self.inverses[self.mod % i] * (self.mod // i) % self.mod
)
self.fact_inverses.append(
self.fact_inverses[i - 1] * self.inverses[i] % self.mod
)
def combination(self, n, k):
if k > n:
raise ValueError
elif k == n:
return 1
elif k == 0:
return 1
denominator = self.fact_inverses[k] * self.fact_inverses[n - k] % self.mod
return self.facts[n] * denominator % self.mod
def permutation(self, n, r):
return self.facts[n] * self.fact_inverses[n - r] % self.mod
N, M = map(int, input().split(" "))
MOD = 10**9 + 7
m = Mod(MOD, M)
mPn = m.permutation(M, N)
b = mPn
x = mPn
for k in range(1, N + 1):
dup = m.permutation(M - k, N - k) * m.combination(N, k) % MOD
if k % 2 == 1:
b -= dup
else:
b += dup
b %= MOD
print(mPn * b % MOD)
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s280680987 | Accepted | p02625 | Input is given from Standard Input in the following format:
N M | # ABC172-E NEQ
"""
玉:各要素(1~m)(区別あり)
箱:配列の格納場所(1~n)(区別あり)
条件:全射かつ、任意のiにおいてAi != Biとなるような2つの組み合わせ
問題の余事象は
Ai = Biとなるような要素の選び方
となる。
全事象(mCn ^2)からこれを引けば良いので、
包除原理を用いて、
A0 = B0となる場合
A1 = B1となる場合…
を数え上げる。
0~n個までの重複要素について、
-1^i *(n箱からi個選んで重複させる*その時のm個の整数からの選び方はmPi)*残りのn-i個はm-i個から任意に選ぶ(m-iPn-i)^2
を実装する
n箱からi箇所選ぶのは区別しなくて良いが、(その選び方に区別は無いため)
それ以外の、その場所にどの数字を入れるかはちゃんと区別しないといけないため順列になり、
また、残りの箇所もAとBの配列それぞれについて(ここが^2)整数を区別して(順列)自由に選べることに注意。
"""
import sys
readline = sys.stdin.buffer.readline
def even(n):
return 1 if n % 2 == 0 else 0
mod = 10**9 + 7
n, m = map(int, readline().split())
def pow(n, p, mod=mod): # 繰り返し二乗法(nのp乗)
res = 1
while p > 0:
if p % 2 == 0:
n = n**2 % mod
p //= 2
else:
res = res * n % mod
p -= 1
return res % mod
def factrial_memo(n=10**6, mod=mod):
fact = [1, 1]
for i in range(2, n + 1):
fact.append((fact[-1] * i) % mod)
return fact
fact = factrial_memo()
def permutation(n, r): # nPr
return fact[n] * pow(fact[n - r], mod - 2) % mod
def combination(n, r): # nCr
return permutation(n, r) * pow(fact[r], mod - 2) % mod
# return fact[n]*pow(fact[n-r],mod-2)*pow(fact[r],mod-2)
def homogeneous(n, r): # nHr
return combination(n + r - 1, r) % mod
# return fact[n+m-1]*pow(fact[n-1],mod-2)*pow(fact[r],mod-2)
ans = 0
for i in range(n + 1):
# print(combination(n,i)*permutation(m,i)*pow(permutation(m-i,n-i),2)%mod)
ans += (
pow(-1, i)
* combination(n, i)
* permutation(m, i)
* pow(permutation(m - i, n - i), 2)
% mod
)
ans %= mod
print(ans)
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s858297386 | Accepted | p02625 | Input is given from Standard Input in the following format:
N M | M=10**9+7
n,m=map(int,input().split())
F=[1]
for i in range(1,m+1): F+=[i*F[-1]%M]
a=0
for k in range(n+1):
a+=(-1)**k*F[m-k]*pow(F[k]*F[n-k],-1,M)%M
print(a*F[n]*F[m]*pow(F[m-n]**2,-1,M)%M) | Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
Print the count modulo (10^9+7).
* * * | s892935036 | Wrong Answer | p02625 | Input is given from Standard Input in the following format:
N M | import sys
from math import comb
# DEBUG = True
DEBUG = False
if DEBUG:
f = open("202006_5th/E_input.txt")
else:
f = sys.stdin
N, M = map(int, f.readline().split())
mod = (10**9) + 7
print((comb(M, N) ** 2 * N) % mod)
f.close()
| Statement
Count the pairs of length-N sequences consisting of integers between 1 and M
(inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy
all of the following conditions:
* A_i \neq B_i, for every i such that 1\leq i\leq N.
* A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7). | [{"input": "2 2", "output": "2\n \n\nA_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.\n\n* * *"}, {"input": "2 3", "output": "18\n \n\n* * *"}, {"input": "141421 356237", "output": "881613484"}] |
If it is possible that Shik only uses right and down moves, print `Possible`.
Otherwise, print `Impossible`.
* * * | s430733953 | Accepted | p03937 | The input is given from Standard Input in the following format:
H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW} | # coding: utf-8
# Your code here!
# coding: utf-8
from fractions import gcd
from functools import reduce
import sys
sys.setrecursionlimit(200000000)
from inspect import currentframe
# my functions here!
# 標準エラー出力
def printargs2err(*args):
names = {id(v): k for k, v in currentframe().f_back.f_locals.items()}
print(
", ".join(names.get(id(arg), "???") + " : " + repr(arg) for arg in args),
file=sys.stderr,
)
def debug(x):
print(x, file=sys.stderr)
def printglobals():
for symbol, value in globals().items():
print('symbol="%s"、value=%s' % (symbol, value), file=sys.stderr)
def printlocals():
for symbol, value in locals().items():
print('symbol="%s"、value=%s' % (symbol, value), file=sys.stderr)
# 入力(後でいじる)
def pin(type=int):
return map(type, input().split())
# 繰り返し自乗法だよ
# これはnのp乗をmで割ったあまりをだすよ
def modular_w_binary_method(n, m, p):
ans = 1 if n > 0 else 0
while p > 0:
if p % 2 == 1:
ans = (ans * n) % m
n = (n**2) % m
p //= 2
return ans
# mod上でのaの逆元を出すよ
"""
フェルマーの小定理より a**(p)%p==a isTrue
これを利用すれば a**(p-2)%p==a**(-1) isTrue
元と逆元とをかけてpで割れば1が余るよ!
"""
def modular_inverse(a, prime):
return modular_w_binary_method(a, prime, prime - 2)
# 逆元を使うと容易に頑張れるc
def conbination(n, a, mod=10**9 + 7):
# cはイラない
res = 1
for s in range(a):
res = (res * (n - s) * (modular_inverse(s + 1, mod))) % mod
return res
# 操作から作れるものの組み合わせは何個かー>同じものでも違う方法で構成できるかから考える方法もある
"""
"""
# solution:
# input
H, W = pin()
h = 0
for i in range(H):
t = list(input())
for j in t:
if j == "#":
h += 1
# print(h)
print(["Impossible", "Possible"][h == (H + W - 1)])
# print(m)
# print(["No","Yes"][cond])
# print([["NA","YYMM"],["MMYY","AMBIGUOUS"]][cMMYY][cYYMM])
"""
#printデバッグ消した?
#前の問題の結果見てないのに次の問題に行くの?
"""
"""
お前カッコ閉じるの忘れてるだろ
"""
| Statement
We have a grid of H rows and W columns. Initially, there is a stone in the top
left cell. Shik is trying to move the stone to the bottom right cell. In each
step, he can move the stone one cell to its left, up, right, or down (if such
cell exists). It is possible that the stone visits a cell multiple times
(including the bottom right and the top left cell).
You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq
W). After Shik completes all moving actions, a_{ij} is `#` if the stone had
ever located at the i-th row and the j-th column during the process of moving.
Otherwise, a_{ij} is `.`. Please determine whether it is possible that Shik
only uses right and down moves in all steps. | [{"input": "4 5\n ##...\n .##..\n ..##.\n ...##", "output": "Possible\n \n\nThe matrix can be generated by a 7-move sequence: right, down, right, down,\nright, down, and right.\n\n* * *"}, {"input": "5 3\n ###\n ..#\n ###\n #..\n ###", "output": "Impossible\n \n\n* * *"}, {"input": "4 5\n ##...\n .###.\n .###.\n ...##", "output": "Impossible"}] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.