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 the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`. * * *
s585146747
Runtime Error
p02841
Input is given from Standard Input in the following format: M_1 D_1 M_2 D_2
x = int(input()) k = x // 100 print(1) if 100 * k <= x and x <= 105 * k else print(0)
Statement In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month.
[{"input": "11 16\n 11 17", "output": "0\n \n\nNovember 16 is not the last day of a month.\n\n* * *"}, {"input": "11 30\n 12 1", "output": "1\n \n\nNovember 30 is the last day of November."}]
If the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`. * * *
s402130333
Runtime Error
p02841
Input is given from Standard Input in the following format: M_1 D_1 M_2 D_2
print(1 - input()[:2] in input())
Statement In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month.
[{"input": "11 16\n 11 17", "output": "0\n \n\nNovember 16 is not the last day of a month.\n\n* * *"}, {"input": "11 30\n 12 1", "output": "1\n \n\nNovember 30 is the last day of November."}]
If the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`. * * *
s077164044
Runtime Error
p02841
Input is given from Standard Input in the following format: M_1 D_1 M_2 D_2
N = float(input()) x = N / 1.08 x = int(x) print(x)
Statement In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month.
[{"input": "11 16\n 11 17", "output": "0\n \n\nNovember 16 is not the last day of a month.\n\n* * *"}, {"input": "11 30\n 12 1", "output": "1\n \n\nNovember 30 is the last day of November."}]
If the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`. * * *
s077868684
Runtime Error
p02841
Input is given from Standard Input in the following format: M_1 D_1 M_2 D_2
x = int(input()) ans = 0 for i in range(1000): if i * 100 <= x <= 105 * i: ans = 1 print(ans)
Statement In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month.
[{"input": "11 16\n 11 17", "output": "0\n \n\nNovember 16 is not the last day of a month.\n\n* * *"}, {"input": "11 30\n 12 1", "output": "1\n \n\nNovember 30 is the last day of November."}]
If the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`. * * *
s851541919
Runtime Error
p02841
Input is given from Standard Input in the following format: M_1 D_1 M_2 D_2
a, b, c, d = map(int, input().split()), map(int, input().split()) print("0" if a == c else "1")
Statement In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month.
[{"input": "11 16\n 11 17", "output": "0\n \n\nNovember 16 is not the last day of a month.\n\n* * *"}, {"input": "11 30\n 12 1", "output": "1\n \n\nNovember 30 is the last day of November."}]
If the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`. * * *
s038579938
Runtime Error
p02841
Input is given from Standard Input in the following format: M_1 D_1 M_2 D_2
print(1 if int(input().split()[2]) == 1 else 0)
Statement In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month.
[{"input": "11 16\n 11 17", "output": "0\n \n\nNovember 16 is not the last day of a month.\n\n* * *"}, {"input": "11 30\n 12 1", "output": "1\n \n\nNovember 30 is the last day of November."}]
If the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`. * * *
s114361493
Wrong Answer
p02841
Input is given from Standard Input in the following format: M_1 D_1 M_2 D_2
a = input() b = input() month_a = int(a.split(" ")[0]) day_a = int(a.split(" ")[1]) month_b = int(b.split(" ")[0]) day_b = int(b.split(" ")[1]) last_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if month_a - month_b == 0 and day_b - day_a == 1: val = 1 elif month_b - month_a == 1 and day_a == last_day[month_a - 1] and day_b == 1: val = 1 else: val = 0 print(val)
Statement In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month.
[{"input": "11 16\n 11 17", "output": "0\n \n\nNovember 16 is not the last day of a month.\n\n* * *"}, {"input": "11 30\n 12 1", "output": "1\n \n\nNovember 30 is the last day of November."}]
If the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`. * * *
s484709137
Runtime Error
p02841
Input is given from Standard Input in the following format: M_1 D_1 M_2 D_2
N = int(input()) S = str(input()) numbers = [] cnt = 0 for i in range(0, len(S), 1): for j in range(i + 1, len(S), 1): for k in range(j + 1, len(S), 1): number = (S[i], S[j], S[k]) numbers.append(number) print(len(set(numbers)))
Statement In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month.
[{"input": "11 16\n 11 17", "output": "0\n \n\nNovember 16 is not the last day of a month.\n\n* * *"}, {"input": "11 30\n 12 1", "output": "1\n \n\nNovember 30 is the last day of November."}]
If the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`. * * *
s965982584
Runtime Error
p02841
Input is given from Standard Input in the following format: M_1 D_1 M_2 D_2
# coding:utf-8 import math X = int(input()) if X < 100: print("0") exit() c = 0 x2 = X % 100 for i in range(100000): x = 0 if x2 / 5 > 1: x = math.floor(x2 / 5) x2 -= 5 * x five = 5 * x elif x2 / 4 >= 1: x = math.floor(x2 / 4) x2 -= 4 * x four = 4 * x elif x2 / 3 >= 1: x = math.floor(x2 / 3) x2 -= 3 * x three = 3 * x elif x2 / 2 >= 1: x = math.floor(x2 / 2) x2 -= 2 * x two = 2 * x elif x2 / 1 == 1: x = math.floor(x2 / 1) x2 -= 1 * x one = 1 * x c += x if x2 == 0: break if c == 0 or X >= c * 100: print("1") else: print("0")
Statement In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month.
[{"input": "11 16\n 11 17", "output": "0\n \n\nNovember 16 is not the last day of a month.\n\n* * *"}, {"input": "11 30\n 12 1", "output": "1\n \n\nNovember 30 is the last day of November."}]
Print the number of integers i that satisfy the condition. * * *
s479071390
Wrong Answer
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
print(1)
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
Print the number of integers i that satisfy the condition. * * *
s571878836
Runtime Error
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
a, b = map(int, input().split()) if a == 0 or b == 0 or (a < 0 and b > 0): print(0) elif b < 0 and (b - a) % 2 == 0: print("Negative") else: print("Positive")
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
Print the number of integers i that satisfy the condition. * * *
s078201154
Runtime Error
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
fast_list = list(map(int, input().split())) correct_answer_count = 0 bat_answer_count = 0 for i in range(1, fast_list[0] + 1): for j in range(1, i + 1): if not (fast_list[1][i] <= fast_list[1][j]): bat_answer_count += 1 if bat_answer_count == 0: correct_answer_count += 1 print(correct_answer_count)
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
Print the number of integers i that satisfy the condition. * * *
s315469949
Wrong Answer
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
N = int(input()) P = list(map(int, input().split())) # count = 0 # for i in range(N): # for n in range(i + 1): # if P[n] < P[i]: # break # if i == n: # count += 1 # print(count)
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
Print the number of integers i that satisfy the condition. * * *
s775010588
Accepted
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
n = int(input()) p = [int(s) for s in input().split()] mp = 200000 ct = 0 for x in range(n): if p[x] <= mp: mp = p[x] ct += 1 print(ct)
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
Print the number of integers i that satisfy the condition. * * *
s743787017
Accepted
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
a = int(input()) array = list(map(int, input().strip().split())) out = 0 min_num = array[0] for i in array: min_num = min(min_num, i) out = out + 1 if i == min_num else out print(out)
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
Print the number of integers i that satisfy the condition. * * *
s104647163
Runtime Error
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
"""C - Welcome to AtCoder 高橋君は AtCoder のコンテストに参加しています。 このコンテストでは、 N 問の問題が出題されます。 高橋君はコンテスト中に M回の提出を行いました。 i 回目の提出は pi番目の問題への提出であり、結果は Si (AC または WA) でした。 高橋君の正答数は、AC を 1回以上出した問題の数です。 高橋君のペナルティ数は、高橋君が AC を 1 回以上出した各問題において、初めて AC を出すまでに出した WA の数の総和です。 高橋君の正答数とペナルティ数を答えてください。 入力 入力は以下の形式で標準入力から与えられる。 N M p1 S1 : pM SM 2 5 1 WA 1 AC 2 WA 2 AC 2 WA > 2 2 100000 3 7777 AC 7777 AC 7777 AC > 1 0 6 0 > 0 0 """ import numpy as np N, M = map(int, input().split()) AC = np.array([0] * N) # 正解を入れる箱 WA = np.array([0] * N) # 不正解を入れる箱 for _ in range(M): p, S = input().split() if AC[int(p) - 1] == 0 and S == "WA": # まだ「正解が出てない & 不正解」 WA[int(p) - 1] += 1 # なら不正解の箱に+1 else: AC[int(p) - 1] = 1 # それ以外は正解の箱に1 print( sum(AC), sum(WA * AC) ) # ただし不正解の箱は最後まで正解が出なかった問題はペナルティ無しにする必要があるので、正解の箱の中身と掛け合わせて消しておく。
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
Print the number of integers i that satisfy the condition. * * *
s877747610
Wrong Answer
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
n = int(input()) nn = [x for x in range(n)] p = list(map(int, input().split())) check = [] for i in nn: for j in range(0, i + 1): if p[i] == n: check.append(i) continue else: if p[i] > p[j]: check.append(i) continue print(n - len(set(check)))
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
Print the number of integers i that satisfy the condition. * * *
s767533625
Wrong Answer
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
n = int(input()) i = list(map(int, input().split())) l = [[0, 0]] * n for k in range(len(i)): l[k] = [i[k], k] l.sort(reverse=True) p = n + 1 a = 0 for k in range(len(i)): if l[k][1] < p: p = l[k][1] a += 1 print(str(a))
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
Print the number of integers i that satisfy the condition. * * *
s574721055
Wrong Answer
p02791
Input is given from Standard Input in the following format: N P_1 ... P_N
n = int(input()) plis = list(map(int, input().split())) m = plis[0] p = n ctr = 0 for i in range(1, m + 1): if i in plis[:p]: ctr += 1 p = plis.index(i) print(ctr)
Statement Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j.
[{"input": "5\n 4 2 5 1 3", "output": "3\n \n\ni=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j\nholds for j = 1. \nSimilarly, i=5 does not satisfy the condition, either. Thus, there are three\nintegers that satisfy the condition.\n\n* * *"}, {"input": "4\n 4 3 2 1", "output": "4\n \n\nAll integers i (1 \\leq i \\leq N) satisfy the condition.\n\n* * *"}, {"input": "6\n 1 2 3 4 5 6", "output": "1\n \n\nOnly i=1 satisfies the condition.\n\n* * *"}, {"input": "8\n 5 7 4 2 6 8 1 3", "output": "4\n \n\n* * *"}, {"input": "1\n 1", "output": "1"}]
* Print the number of good sub-grid. If there are no solution exists, print `0`.
s880738170
Runtime Error
p03929
The input is given from standard input in the following format. > $n \quad k$
a = input() b = input() print(a + b)
Statement Snuke has a very long calendar. It has a grid with $n$ rows and $7$ columns. One day, he noticed that calendar has a following regularity. * The cell at the $i$-th row and $j$-th column contains the integer $7i+j-7$. A good sub-grid is a $3 \times 3$ sub-grid and the sum of integers in this sub-grid mod $11$ is $k$. How many good sub-grid are there? Write a program and help him.
[{"input": "7 7", "output": "2\n \n\nIn this case, the calendar likes this matrix. \n| Sun. | Mon. | Tue. | Wed. | Thu. | Fri. | Sat. \n---|---|---|---|---|---|---|--- \nWeek 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 \nWeek 2 | 8 | 9 | 10 | 11 | 12 | 13 | 14 \nWeek 3 | 15 | 16 | 17 | 18 | 19 | 20 | 21 \nWeek 4 | 22 | 23 | 24 | 25 | 26 | 27 | 28 \nWeek 5 | 29 | 30 | 31 | 32 | 33 | 34 | 35 \nWeek 6 | 36 | 37 | 38 | 39 | 40 | 41 | 42 \nWeek 7 | 43 | 44 | 45 | 46 | 47 | 48 | 49 \n \nThe cell at $i$-th row and $j$-th column is denoted $(i, j)$. \n\n * If upper-left is $(1, 5)$, the sum of integers is $5+6+7+12+13+14+19+20+21=117$.\n * If upper-left is $(3, 2)$, the sum of integers is $16+17+18+23+24+25+30+31+32=216$.\n\nTherefore, there are 2 good sub-grids."}, {"input": "6 0", "output": "2\n \n\nIf upper-left is $(1, 3)$ or $(4, 4)$, it is a good sub-grid."}]
* Print the number of good sub-grid. If there are no solution exists, print `0`.
s688397736
Accepted
p03929
The input is given from standard input in the following format. > $n \quad k$
n, k = map(int, input().split()) d = [11, 16, 10, 25, 9, 24, 19, 13, 18, 12, 17] e = 7 * (n - 1) r = (e - d[k] - 1) // 77 print(5 * r + len([x for x in range(d[k] + 77 * r, e, 11) if x % 7 > 1]))
Statement Snuke has a very long calendar. It has a grid with $n$ rows and $7$ columns. One day, he noticed that calendar has a following regularity. * The cell at the $i$-th row and $j$-th column contains the integer $7i+j-7$. A good sub-grid is a $3 \times 3$ sub-grid and the sum of integers in this sub-grid mod $11$ is $k$. How many good sub-grid are there? Write a program and help him.
[{"input": "7 7", "output": "2\n \n\nIn this case, the calendar likes this matrix. \n| Sun. | Mon. | Tue. | Wed. | Thu. | Fri. | Sat. \n---|---|---|---|---|---|---|--- \nWeek 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 \nWeek 2 | 8 | 9 | 10 | 11 | 12 | 13 | 14 \nWeek 3 | 15 | 16 | 17 | 18 | 19 | 20 | 21 \nWeek 4 | 22 | 23 | 24 | 25 | 26 | 27 | 28 \nWeek 5 | 29 | 30 | 31 | 32 | 33 | 34 | 35 \nWeek 6 | 36 | 37 | 38 | 39 | 40 | 41 | 42 \nWeek 7 | 43 | 44 | 45 | 46 | 47 | 48 | 49 \n \nThe cell at $i$-th row and $j$-th column is denoted $(i, j)$. \n\n * If upper-left is $(1, 5)$, the sum of integers is $5+6+7+12+13+14+19+20+21=117$.\n * If upper-left is $(3, 2)$, the sum of integers is $16+17+18+23+24+25+30+31+32=216$.\n\nTherefore, there are 2 good sub-grids."}, {"input": "6 0", "output": "2\n \n\nIf upper-left is $(1, 3)$ or $(4, 4)$, it is a good sub-grid."}]
Print Taro's maximum possible total score. * * *
s981536824
Runtime Error
p03180
Input is given from Standard Input in the following format: N a_{1, 1} \ldots a_{1, N} : a_{N, 1} \ldots a_{N, N}
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 16; const int MAXL = (1 << 16) + 10; const ll NEG = -1e18; vector<int> grafo[MAXL]; ll valor[MAXL],dp[MAXL],mat[MAXN][MAXN]; int vis[MAXL],N; void brute(int pos,int bitmask,int submask){ if(pos == N){ if(__builtin_popcount(submask) == 0) return; grafo[bitmask].push_back(submask); return; } brute(pos+1,bitmask,submask); brute(pos+1, bitmask | (1 << pos), submask ); brute(pos+1, bitmask | (1 << pos), submask | (1 << pos) ); } void calcula(){ for(int bitmask = 1;bitmask < (1 << N);bitmask++){ for(int i = 0;i<N;i++){ if(!(bitmask & (1 << i))) continue; for(int j = i+1;j<N;j++){ if(!(bitmask & (1 << j))) continue; valor[bitmask] += mat[i][j]; } } } } ll solve(int bitmask){ if(bitmask == 0) return 0; if(vis[bitmask]) return dp[bitmask]; vis[bitmask] = 1; ll best = NEG; for(int submask : grafo[bitmask]){ best = max(best, solve(bitmask ^ submask) + valor[submask] ); } return dp[bitmask] = best; } int main(){ cin >> N; for(int i = 0;i<N;i++){ for(int j = 0;j<N;j++){ cin >> mat[i][j]; } } brute(0,0,0); calcula(); cout << solve((1 << N) - 1) << endl; return 0; }
Statement There are N rabbits, numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N). Taro is dividing the N rabbits into some number of groups. Here, each rabbit must belong to exactly one group. After grouping, for each i and j (1 \leq i < j \leq N), Taro earns a_{i, j} points if Rabbit i and j belong to the same group. Find Taro's maximum possible total score.
[{"input": "3\n 0 10 20\n 10 0 -100\n 20 -100 0", "output": "20\n \n\nThe rabbits should be divided as \\\\{1, 3\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "2\n 0 -10\n -10 0", "output": "0\n \n\nThe rabbits should be divided as \\\\{1\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "4\n 0 1000000000 1000000000 1000000000\n 1000000000 0 1000000000 1000000000\n 1000000000 1000000000 0 -1\n 1000000000 1000000000 -1 0", "output": "4999999999\n \n\nThe rabbits should be divided as \\\\{1, 2, 3, 4\\\\}. Note that the answer may\nnot fit into a 32-bit integer type.\n\n* * *"}, {"input": "16\n 0 5 -4 -5 -8 -4 7 2 -4 0 7 0 2 -3 7 7\n 5 0 8 -9 3 5 2 -7 2 -7 0 -1 -4 1 -1 9\n -4 8 0 -9 8 9 3 1 4 9 6 6 -6 1 8 9\n -5 -9 -9 0 -7 6 4 -1 9 -3 -5 0 1 2 -4 1\n -8 3 8 -7 0 -5 -9 9 1 -9 -6 -3 -8 3 4 3\n -4 5 9 6 -5 0 -6 1 -2 2 0 -5 -2 3 1 2\n 7 2 3 4 -9 -6 0 -2 -2 -9 -3 9 -2 9 2 -5\n 2 -7 1 -1 9 1 -2 0 -6 0 -6 6 4 -1 -7 8\n -4 2 4 9 1 -2 -2 -6 0 8 -6 -2 -4 8 7 7\n 0 -7 9 -3 -9 2 -9 0 8 0 0 1 -3 3 -6 -6\n 7 0 6 -5 -6 0 -3 -6 -6 0 0 5 7 -1 -5 3\n 0 -1 6 0 -3 -5 9 6 -2 1 5 0 -2 7 -8 0\n 2 -4 -6 1 -8 -2 -2 4 -4 -3 7 -2 0 -9 7 1\n -3 1 1 2 3 3 9 -1 8 3 -1 7 -9 0 -6 -8\n 7 -1 8 -4 4 1 2 -7 7 -6 -5 -8 7 -6 0 -9\n 7 9 9 1 3 2 -5 8 7 -6 3 0 1 -8 -9 0", "output": "132"}]
Print Taro's maximum possible total score. * * *
s590609257
Accepted
p03180
Input is given from Standard Input in the following format: N a_{1, 1} \ldots a_{1, N} : a_{N, 1} \ldots a_{N, N}
import sys input = sys.stdin.readline N = int(input()) MAT = [list(map(int, input().split())) for i in range(N)] POINT = [0] * (1 << N) for i in range(1, 1 << N): for j in range(16): if i & (1 << j) != 0: break ANS = POINT[i - (i & (1 << j))] for k in range(16): if i & (1 << k) != 0: ANS += MAT[k][j] POINT[i] = ANS DPLIST = [0] * ((1 << N) + 1) # 使った集合Sに対して,DP[S]でその総得点のmax. # Sを部分集合として含む全てのT(次に使うグループ)へ遷移.(これがO(3^n)) for i in range(1 << N): k = i while k < (1 << N): DPLIST[k] = max(DPLIST[k], DPLIST[i] + POINT[k - i]) k = (k + 1) | i print(DPLIST[(1 << N) - 1])
Statement There are N rabbits, numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N). Taro is dividing the N rabbits into some number of groups. Here, each rabbit must belong to exactly one group. After grouping, for each i and j (1 \leq i < j \leq N), Taro earns a_{i, j} points if Rabbit i and j belong to the same group. Find Taro's maximum possible total score.
[{"input": "3\n 0 10 20\n 10 0 -100\n 20 -100 0", "output": "20\n \n\nThe rabbits should be divided as \\\\{1, 3\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "2\n 0 -10\n -10 0", "output": "0\n \n\nThe rabbits should be divided as \\\\{1\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "4\n 0 1000000000 1000000000 1000000000\n 1000000000 0 1000000000 1000000000\n 1000000000 1000000000 0 -1\n 1000000000 1000000000 -1 0", "output": "4999999999\n \n\nThe rabbits should be divided as \\\\{1, 2, 3, 4\\\\}. Note that the answer may\nnot fit into a 32-bit integer type.\n\n* * *"}, {"input": "16\n 0 5 -4 -5 -8 -4 7 2 -4 0 7 0 2 -3 7 7\n 5 0 8 -9 3 5 2 -7 2 -7 0 -1 -4 1 -1 9\n -4 8 0 -9 8 9 3 1 4 9 6 6 -6 1 8 9\n -5 -9 -9 0 -7 6 4 -1 9 -3 -5 0 1 2 -4 1\n -8 3 8 -7 0 -5 -9 9 1 -9 -6 -3 -8 3 4 3\n -4 5 9 6 -5 0 -6 1 -2 2 0 -5 -2 3 1 2\n 7 2 3 4 -9 -6 0 -2 -2 -9 -3 9 -2 9 2 -5\n 2 -7 1 -1 9 1 -2 0 -6 0 -6 6 4 -1 -7 8\n -4 2 4 9 1 -2 -2 -6 0 8 -6 -2 -4 8 7 7\n 0 -7 9 -3 -9 2 -9 0 8 0 0 1 -3 3 -6 -6\n 7 0 6 -5 -6 0 -3 -6 -6 0 0 5 7 -1 -5 3\n 0 -1 6 0 -3 -5 9 6 -2 1 5 0 -2 7 -8 0\n 2 -4 -6 1 -8 -2 -2 4 -4 -3 7 -2 0 -9 7 1\n -3 1 1 2 3 3 9 -1 8 3 -1 7 -9 0 -6 -8\n 7 -1 8 -4 4 1 2 -7 7 -6 -5 -8 7 -6 0 -9\n 7 9 9 1 3 2 -5 8 7 -6 3 0 1 -8 -9 0", "output": "132"}]
Print Taro's maximum possible total score. * * *
s526164160
Accepted
p03180
Input is given from Standard Input in the following format: N a_{1, 1} \ldots a_{1, N} : a_{N, 1} \ldots a_{N, N}
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time, copy, functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9 + 7 dd = [(-1, 0), (0, 1), (1, 0), (0, -1)] ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): n = I() a = [LI() for _ in range(n)] m = 2**n b = [None] * m b[0] = 0 ii = [2**i for i in range(n + 1)] dd = {} for i in range(n): dd[ii[i]] = i c = 0 for i in range(1, m): if i >= ii[c + 1]: c += 1 t = i - ii[c] k = b[t] d = a[c] while t: u = t ^ t - 1 & t t ^= u k += d[dd[u]] b[i] = k d = b[:] c = 0 for i in range(1, m): if i >= ii[c + 1]: c += 1 k = d[i - ii[c]] t = i while t: u = d[t] + d[i ^ t] if k < u: k = u t = t - 1 & i d[i] = k # print('b',b) # print('d',d) return d[-1] print(main())
Statement There are N rabbits, numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N). Taro is dividing the N rabbits into some number of groups. Here, each rabbit must belong to exactly one group. After grouping, for each i and j (1 \leq i < j \leq N), Taro earns a_{i, j} points if Rabbit i and j belong to the same group. Find Taro's maximum possible total score.
[{"input": "3\n 0 10 20\n 10 0 -100\n 20 -100 0", "output": "20\n \n\nThe rabbits should be divided as \\\\{1, 3\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "2\n 0 -10\n -10 0", "output": "0\n \n\nThe rabbits should be divided as \\\\{1\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "4\n 0 1000000000 1000000000 1000000000\n 1000000000 0 1000000000 1000000000\n 1000000000 1000000000 0 -1\n 1000000000 1000000000 -1 0", "output": "4999999999\n \n\nThe rabbits should be divided as \\\\{1, 2, 3, 4\\\\}. Note that the answer may\nnot fit into a 32-bit integer type.\n\n* * *"}, {"input": "16\n 0 5 -4 -5 -8 -4 7 2 -4 0 7 0 2 -3 7 7\n 5 0 8 -9 3 5 2 -7 2 -7 0 -1 -4 1 -1 9\n -4 8 0 -9 8 9 3 1 4 9 6 6 -6 1 8 9\n -5 -9 -9 0 -7 6 4 -1 9 -3 -5 0 1 2 -4 1\n -8 3 8 -7 0 -5 -9 9 1 -9 -6 -3 -8 3 4 3\n -4 5 9 6 -5 0 -6 1 -2 2 0 -5 -2 3 1 2\n 7 2 3 4 -9 -6 0 -2 -2 -9 -3 9 -2 9 2 -5\n 2 -7 1 -1 9 1 -2 0 -6 0 -6 6 4 -1 -7 8\n -4 2 4 9 1 -2 -2 -6 0 8 -6 -2 -4 8 7 7\n 0 -7 9 -3 -9 2 -9 0 8 0 0 1 -3 3 -6 -6\n 7 0 6 -5 -6 0 -3 -6 -6 0 0 5 7 -1 -5 3\n 0 -1 6 0 -3 -5 9 6 -2 1 5 0 -2 7 -8 0\n 2 -4 -6 1 -8 -2 -2 4 -4 -3 7 -2 0 -9 7 1\n -3 1 1 2 3 3 9 -1 8 3 -1 7 -9 0 -6 -8\n 7 -1 8 -4 4 1 2 -7 7 -6 -5 -8 7 -6 0 -9\n 7 9 9 1 3 2 -5 8 7 -6 3 0 1 -8 -9 0", "output": "132"}]
Print Taro's maximum possible total score. * * *
s591886401
Wrong Answer
p03180
Input is given from Standard Input in the following format: N a_{1, 1} \ldots a_{1, N} : a_{N, 1} \ldots a_{N, N}
#!/usr/bin/env python3 import sys sys.setrecursionlimit(10**8) INF = float("inf") def bit(n, k): return (n >> k) & 1 def solve(N: int, a: "List[List[int]]"): DP = [0] * (1 << N) flag = [False] * (1 << N) def rec(S): if flag[S]: return DP[S] flag[S] = True ans = 0 for i in range(N): for j in range(i + 1, N): if bit(S, i) and bit(S, j): ans += a[i][j] T = (S - 1) & S while T > 0: ans = max(ans, rec(S) + rec(S ^ T)) T = (T - 1) & S DP[S] = ans return ans print(rec((1 << N) - 1)) return def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() N = int(next(tokens)) # type: int a = [ [int(next(tokens)) for _ in range(N)] for _ in range(N) ] # type: "List[List[int]]" solve(N, a) if __name__ == "__main__": main()
Statement There are N rabbits, numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N). Taro is dividing the N rabbits into some number of groups. Here, each rabbit must belong to exactly one group. After grouping, for each i and j (1 \leq i < j \leq N), Taro earns a_{i, j} points if Rabbit i and j belong to the same group. Find Taro's maximum possible total score.
[{"input": "3\n 0 10 20\n 10 0 -100\n 20 -100 0", "output": "20\n \n\nThe rabbits should be divided as \\\\{1, 3\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "2\n 0 -10\n -10 0", "output": "0\n \n\nThe rabbits should be divided as \\\\{1\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "4\n 0 1000000000 1000000000 1000000000\n 1000000000 0 1000000000 1000000000\n 1000000000 1000000000 0 -1\n 1000000000 1000000000 -1 0", "output": "4999999999\n \n\nThe rabbits should be divided as \\\\{1, 2, 3, 4\\\\}. Note that the answer may\nnot fit into a 32-bit integer type.\n\n* * *"}, {"input": "16\n 0 5 -4 -5 -8 -4 7 2 -4 0 7 0 2 -3 7 7\n 5 0 8 -9 3 5 2 -7 2 -7 0 -1 -4 1 -1 9\n -4 8 0 -9 8 9 3 1 4 9 6 6 -6 1 8 9\n -5 -9 -9 0 -7 6 4 -1 9 -3 -5 0 1 2 -4 1\n -8 3 8 -7 0 -5 -9 9 1 -9 -6 -3 -8 3 4 3\n -4 5 9 6 -5 0 -6 1 -2 2 0 -5 -2 3 1 2\n 7 2 3 4 -9 -6 0 -2 -2 -9 -3 9 -2 9 2 -5\n 2 -7 1 -1 9 1 -2 0 -6 0 -6 6 4 -1 -7 8\n -4 2 4 9 1 -2 -2 -6 0 8 -6 -2 -4 8 7 7\n 0 -7 9 -3 -9 2 -9 0 8 0 0 1 -3 3 -6 -6\n 7 0 6 -5 -6 0 -3 -6 -6 0 0 5 7 -1 -5 3\n 0 -1 6 0 -3 -5 9 6 -2 1 5 0 -2 7 -8 0\n 2 -4 -6 1 -8 -2 -2 4 -4 -3 7 -2 0 -9 7 1\n -3 1 1 2 3 3 9 -1 8 3 -1 7 -9 0 -6 -8\n 7 -1 8 -4 4 1 2 -7 7 -6 -5 -8 7 -6 0 -9\n 7 9 9 1 3 2 -5 8 7 -6 3 0 1 -8 -9 0", "output": "132"}]
Print Taro's maximum possible total score. * * *
s351232428
Accepted
p03180
Input is given from Standard Input in the following format: N a_{1, 1} \ldots a_{1, N} : a_{N, 1} \ldots a_{N, N}
#!/usr/bin/env python3 from itertools import combinations import sys sys.setrecursionlimit(10**8) input = sys.stdin.readline MOD = 10**9 + 7 n = int(input()) cost = [] for i in range(n): cost.append([int(item) for item in input().split()]) score = [0] * 2**n for i in range(1, 2**n): lsb = i & -i index = lsb.bit_length() - 1 other = i ^ lsb diff = 0 for j in range(n): if other & 1 << j: diff += cost[index][j] score[i] = score[other] + diff memo = [-1] * 2**n memo[0] = 0 for i in range(n): memo[1 << i] = 0 def dfs(st): if memo[st] != -1: return memo[st] sst = st val = score[st] while True: sst = (sst - 1) & st if sst == 0: break val = max(val, dfs(sst) + dfs(sst ^ st)) memo[st] = val return val ret = dfs(2**n - 1) print(ret)
Statement There are N rabbits, numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N). Taro is dividing the N rabbits into some number of groups. Here, each rabbit must belong to exactly one group. After grouping, for each i and j (1 \leq i < j \leq N), Taro earns a_{i, j} points if Rabbit i and j belong to the same group. Find Taro's maximum possible total score.
[{"input": "3\n 0 10 20\n 10 0 -100\n 20 -100 0", "output": "20\n \n\nThe rabbits should be divided as \\\\{1, 3\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "2\n 0 -10\n -10 0", "output": "0\n \n\nThe rabbits should be divided as \\\\{1\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "4\n 0 1000000000 1000000000 1000000000\n 1000000000 0 1000000000 1000000000\n 1000000000 1000000000 0 -1\n 1000000000 1000000000 -1 0", "output": "4999999999\n \n\nThe rabbits should be divided as \\\\{1, 2, 3, 4\\\\}. Note that the answer may\nnot fit into a 32-bit integer type.\n\n* * *"}, {"input": "16\n 0 5 -4 -5 -8 -4 7 2 -4 0 7 0 2 -3 7 7\n 5 0 8 -9 3 5 2 -7 2 -7 0 -1 -4 1 -1 9\n -4 8 0 -9 8 9 3 1 4 9 6 6 -6 1 8 9\n -5 -9 -9 0 -7 6 4 -1 9 -3 -5 0 1 2 -4 1\n -8 3 8 -7 0 -5 -9 9 1 -9 -6 -3 -8 3 4 3\n -4 5 9 6 -5 0 -6 1 -2 2 0 -5 -2 3 1 2\n 7 2 3 4 -9 -6 0 -2 -2 -9 -3 9 -2 9 2 -5\n 2 -7 1 -1 9 1 -2 0 -6 0 -6 6 4 -1 -7 8\n -4 2 4 9 1 -2 -2 -6 0 8 -6 -2 -4 8 7 7\n 0 -7 9 -3 -9 2 -9 0 8 0 0 1 -3 3 -6 -6\n 7 0 6 -5 -6 0 -3 -6 -6 0 0 5 7 -1 -5 3\n 0 -1 6 0 -3 -5 9 6 -2 1 5 0 -2 7 -8 0\n 2 -4 -6 1 -8 -2 -2 4 -4 -3 7 -2 0 -9 7 1\n -3 1 1 2 3 3 9 -1 8 3 -1 7 -9 0 -6 -8\n 7 -1 8 -4 4 1 2 -7 7 -6 -5 -8 7 -6 0 -9\n 7 9 9 1 3 2 -5 8 7 -6 3 0 1 -8 -9 0", "output": "132"}]
Print Taro's maximum possible total score. * * *
s582103027
Wrong Answer
p03180
Input is given from Standard Input in the following format: N a_{1, 1} \ldots a_{1, N} : a_{N, 1} \ldots a_{N, N}
N = int(input()) a = [list(map(int, input().split())) for _ in range(N)] # base_score[i] := i の立っている bit のウサギで一つのグループを作るときの特典 base_score = [0] * (1 << N) for i in range(1 << N): for j in range(N): for k in range(j): if i & (1 << j) and i & (1 << k): base_score[i] += a[j][k] # dp[i] := i の立っている bit のウサギのグループが決まっているとした場合の得点の最大値 dp = [0] * (1 << N) for i in range(1 << N): # i の部分集合について、ウサギのグループの分け方を全探索 j = i while j > 0: j = (j - 1) & i dp[i] = max(dp[i], dp[i - j] + base_score[j]) print(dp[(1 << N) - 1])
Statement There are N rabbits, numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N). Taro is dividing the N rabbits into some number of groups. Here, each rabbit must belong to exactly one group. After grouping, for each i and j (1 \leq i < j \leq N), Taro earns a_{i, j} points if Rabbit i and j belong to the same group. Find Taro's maximum possible total score.
[{"input": "3\n 0 10 20\n 10 0 -100\n 20 -100 0", "output": "20\n \n\nThe rabbits should be divided as \\\\{1, 3\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "2\n 0 -10\n -10 0", "output": "0\n \n\nThe rabbits should be divided as \\\\{1\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "4\n 0 1000000000 1000000000 1000000000\n 1000000000 0 1000000000 1000000000\n 1000000000 1000000000 0 -1\n 1000000000 1000000000 -1 0", "output": "4999999999\n \n\nThe rabbits should be divided as \\\\{1, 2, 3, 4\\\\}. Note that the answer may\nnot fit into a 32-bit integer type.\n\n* * *"}, {"input": "16\n 0 5 -4 -5 -8 -4 7 2 -4 0 7 0 2 -3 7 7\n 5 0 8 -9 3 5 2 -7 2 -7 0 -1 -4 1 -1 9\n -4 8 0 -9 8 9 3 1 4 9 6 6 -6 1 8 9\n -5 -9 -9 0 -7 6 4 -1 9 -3 -5 0 1 2 -4 1\n -8 3 8 -7 0 -5 -9 9 1 -9 -6 -3 -8 3 4 3\n -4 5 9 6 -5 0 -6 1 -2 2 0 -5 -2 3 1 2\n 7 2 3 4 -9 -6 0 -2 -2 -9 -3 9 -2 9 2 -5\n 2 -7 1 -1 9 1 -2 0 -6 0 -6 6 4 -1 -7 8\n -4 2 4 9 1 -2 -2 -6 0 8 -6 -2 -4 8 7 7\n 0 -7 9 -3 -9 2 -9 0 8 0 0 1 -3 3 -6 -6\n 7 0 6 -5 -6 0 -3 -6 -6 0 0 5 7 -1 -5 3\n 0 -1 6 0 -3 -5 9 6 -2 1 5 0 -2 7 -8 0\n 2 -4 -6 1 -8 -2 -2 4 -4 -3 7 -2 0 -9 7 1\n -3 1 1 2 3 3 9 -1 8 3 -1 7 -9 0 -6 -8\n 7 -1 8 -4 4 1 2 -7 7 -6 -5 -8 7 -6 0 -9\n 7 9 9 1 3 2 -5 8 7 -6 3 0 1 -8 -9 0", "output": "132"}]
Print Taro's maximum possible total score. * * *
s740113055
Accepted
p03180
Input is given from Standard Input in the following format: N a_{1, 1} \ldots a_{1, N} : a_{N, 1} \ldots a_{N, N}
import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ n = int(input()) a = [list(map(int, input().split())) for i in range(n)] max_mask = 1 << n DP = [0] * max_mask for state in range(1, max_mask): flag = [] for i in range(n): if (state >> i) & 1: flag.append(i) tmp = 0 for i in flag: for j in flag: tmp += a[i][j] DP[state] = tmp // 2 j = (state - 1) & state while j: k = state ^ j DP[state] = max(DP[state], DP[j] + DP[k]) j = (j - 1) & state print(DP[-1])
Statement There are N rabbits, numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N). Taro is dividing the N rabbits into some number of groups. Here, each rabbit must belong to exactly one group. After grouping, for each i and j (1 \leq i < j \leq N), Taro earns a_{i, j} points if Rabbit i and j belong to the same group. Find Taro's maximum possible total score.
[{"input": "3\n 0 10 20\n 10 0 -100\n 20 -100 0", "output": "20\n \n\nThe rabbits should be divided as \\\\{1, 3\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "2\n 0 -10\n -10 0", "output": "0\n \n\nThe rabbits should be divided as \\\\{1\\\\}, \\\\{2\\\\}.\n\n* * *"}, {"input": "4\n 0 1000000000 1000000000 1000000000\n 1000000000 0 1000000000 1000000000\n 1000000000 1000000000 0 -1\n 1000000000 1000000000 -1 0", "output": "4999999999\n \n\nThe rabbits should be divided as \\\\{1, 2, 3, 4\\\\}. Note that the answer may\nnot fit into a 32-bit integer type.\n\n* * *"}, {"input": "16\n 0 5 -4 -5 -8 -4 7 2 -4 0 7 0 2 -3 7 7\n 5 0 8 -9 3 5 2 -7 2 -7 0 -1 -4 1 -1 9\n -4 8 0 -9 8 9 3 1 4 9 6 6 -6 1 8 9\n -5 -9 -9 0 -7 6 4 -1 9 -3 -5 0 1 2 -4 1\n -8 3 8 -7 0 -5 -9 9 1 -9 -6 -3 -8 3 4 3\n -4 5 9 6 -5 0 -6 1 -2 2 0 -5 -2 3 1 2\n 7 2 3 4 -9 -6 0 -2 -2 -9 -3 9 -2 9 2 -5\n 2 -7 1 -1 9 1 -2 0 -6 0 -6 6 4 -1 -7 8\n -4 2 4 9 1 -2 -2 -6 0 8 -6 -2 -4 8 7 7\n 0 -7 9 -3 -9 2 -9 0 8 0 0 1 -3 3 -6 -6\n 7 0 6 -5 -6 0 -3 -6 -6 0 0 5 7 -1 -5 3\n 0 -1 6 0 -3 -5 9 6 -2 1 5 0 -2 7 -8 0\n 2 -4 -6 1 -8 -2 -2 4 -4 -3 7 -2 0 -9 7 1\n -3 1 1 2 3 3 9 -1 8 3 -1 7 -9 0 -6 -8\n 7 -1 8 -4 4 1 2 -7 7 -6 -5 -8 7 -6 0 -9\n 7 9 9 1 3 2 -5 8 7 -6 3 0 1 -8 -9 0", "output": "132"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s873160275
Accepted
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
n, k = map(int, input().split()) aList = list(map(int, input().split())) num = [0 for _ in range(n + 1)] for i in aList: num[i] += 1 num.sort() num = num[:-k] print(sum(num))
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s174995262
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
N,K=map(int,input().split()) A=list(map(int,input().split())) b=list(set(A)) ans=0 count=[] for i in range(len(b): count.append(A.count(b[i])) count.sort() for i in range(c-K): ans+=count[i] print(ans)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s406862281
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
10 3 5 1 3 2 4 1 1 2 3 4
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s032503011
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
n, k = map(int, input().split()) a_list = list(map(int, input().split())) b_list = sorted(a_list.count(i) for i in range(n + 1), reverse=True) print(n - sum(b_list[:k:]))
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s871594491
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
n,k=map(int,input().split()) a=set(map(int,input().split())) print(max(0,len(a)-k)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s450399697
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
N,K = map(int, input().split()) A = [int(x) for x in input().split()] d = {} for a in A: if a in d: d[a] +=1 eles: d[a] =1 d =sorted(d.values()) if len(d) > K: ans = 0 for i in range(len(d)-K): ans += d[i] print(ans) else: print(0)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s707661110
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
N, K = map(int, input().split()) a = list(map(int, input().split()) import collections def solve(): c = list(collections.Counter(a).values()) c.sort() if(len(c)<=k): print(0) else: print(sum(c[:len(c)-k])) solve()
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s309770948
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
import collections N, K = map(int, input().split()) a = list(map(int, input().split()) import collections def solve(): c = list(collections.Counter(a).values()) c.sort() if(len(c)<=k): print(0) else: print(sum(c[:len(c)-k])) solve()
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s732897152
Accepted
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
def getN(): return int(input()) def getNM(): return map(int, input().split()) def getList(): return list(map(int, input().split())) n, k = getNM() nums = getList() bucket = [0 for i in range(200001)] for num in nums: bucket[num] += 1 bucket.sort() print(sum(bucket[:-k]))
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s100350706
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
n,k = map(int, input().split()) A = [int(x) for x in input().split()] d = {} for a in A: if a in d: d[a] +=1 eles: d[a] =1 d =sorted(d.values()) if len(d) > k: ans = 0 for i in range(len(d)-k): ans += d[i] print(ans) else: print(0)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s523948664
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
n, k = map(int, input().split()) a = list(map(int, input().split()) ans = 0 dic = {} for i in a: if i in dic: dic[i] += 1 else: dic[i] = 1 dic = sorted(dic.items(), key=lambda x: x[1]) while len(dic) > k: ans += dic[0][1] del dic[0] print(ans)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s380389213
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
B �����j\_������������������@���s����d�dl�Z�d�dlmZ�eee������\ZZdd��e�����D��Z e e�� e ��Z e e �ekr`ed���nJee ���ed�d�Zd�Zx(ee e�e��D�]Zeee�d�7�Zq�W�ee��dS�)�����N)� itemgetterc�������������C���s���g�|�] }t�|��qS���)�int)�.0�jr���r���� ABC081C.py� <listcomp>���s����r�������)�key)� collections�operatorr����mapr����input�split�N�KZball�dict�Counter�kind�len�print�sorted�itemsZskindZsumNum�range�ir���r���r���r����<module>���s���   
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s953256640
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
n, k = map(int, input().split()) num_lists = list(map(int, input().split())) if len(set(num_lists)) <= k: ans = 0 else: num_counts = {} for i in set(num_lists): num_counts[i] = num_lists.count(i) numbers = list(num_counts.values) numbers.sort() ans = 0 for i in range(k - len(set(num_lists)): ans += numbers[i] print(ans)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s483846173
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
import java.util.HashMap; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeSet; class ball implements Comparable<ball>{ int num, id; public ball(int n, int i) { num = n; id = i; } public int compareTo(ball o) { if(num == o.num) return id - o.id; return num - o.num; } } class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(), K = sc.nextInt(); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < N; i++) { int A = sc.nextInt(); if(map.containsKey(A)) map.put(A, map.get(A) + 1); else map.put(A, 1); } /* 本質 */ int ans = 0; TreeSet<ball> balls = new TreeSet<ball>(); for(Entry<Integer, Integer> e : map.entrySet()) { balls.add(new ball(e.getValue(), e.getKey())); } while(balls.size() > K) { ans += balls.pollFirst().num; } System.out.println(ans); } }
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s845934590
Runtime Error
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
n, k = map(int, input().split()) num_lists = list(map(int, input().split())) if len(set(num_lists)) <= k: ans = 0 else: num_counts = {} for i in set(num_lists): num_counts[i] = num_lists.count(i) numbers = list(num_counts.values()) numbers.sort() ans = 0 for i in range(k - len(set(num_lists)): ans += numbers[i] print(ans)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s359531900
Accepted
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
n, k = input().split() n, k = int(n), int(k) balls = input().split() dic = {} for x in balls: if x not in dic: dic[x] = 1 else: dic[x] += 1 change = 0 qnt = list(dic.values()) qnt.sort() dif = len(qnt) - k for x in range(0, dif): change += qnt[x] print(change)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s140078811
Accepted
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
import bisect as bs N, K = (int(x) for x in input().split()) A = sorted([int(x) for x in input().split()]) f = lambda X, x: bs.bisect_right(X, x) - bs.bisect_left(X, x) cnt = sorted([f(A, a) for a in set(A)], reverse=True) vrt = len(cnt) print(sum(cnt[K:]) if vrt > K else 0)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s164342309
Wrong Answer
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
import numpy as np import sys b = [int(x) for x in input().split()] n = b[0] m = b[1] a = [int(x) for x in input().split()] # find number of integers count = 0 for i in range(n): flag = 0 for k in range(i): if a[k] == a[i]: flag += 1 # print(flag) if flag == 0: count += 1 # print("count=",count) # print(count) # sort by the number of integers c = np.zeros((2, n)) # c=np.zeros((2,count)) # for i in range(count): # c[i]=0 # c[0,0]=a[0] # c[1,0]+=1 for i in range(n): flag = 0 for k in range(i): if c[0, k] == a[i]: # c[0,k]: flag += 1 c[1, k] += 1 # print(c) if flag == 0: c[0, i] = a[i] c[1, i] += 1 # print(c) # print(c) e = c if count - m < 0: print(0) sys.exit() d = np.zeros(count - m) for l in range(count - m): for k in range(n): # for k in range(count-m): small = n for i in range(n): # for i in range(count): if small > e[1, i] and e[1, i] != 0: small = e[1, i] # print(c[1,i]) d[l] = small for i in range(count): if e[1, i] == d[l]: e[1, i] = 0 # print('a') continue # print(d) ans = 0 for i in range(count - m): ans += d[i] print(int(ans))
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s438407042
Wrong Answer
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
# https://atcoder.jp/contests/abc081/tasks/arc086_a import sys variety = 0 # 数字の種類 element1 = 0 def main(): n, k = input().split() # N = int(n) K = int(k) numeric = input().split() # サイズがわからなくてもこれでリストとして格納できる # list(map(int, numeric)) <-これもいいけど numeric = [int(x) for x in numeric] # リストを返すなら内包表記の方が速い # 数字の種類の判定アルゴリズム numeric.sort() # まずはソートをして # print(numeric) # まずnumeric内に何種類の数字があるかを判定。n種類ぶんのリスト(vary)を用意、1つずつ格納しておく vary = [] # 種類を格納 TypeDetermination(numeric, vary) # 何種類あるか判定 # print(variety,vary) # そのリストを使って、その数が何個numericにあるかを数える。 # 配列varyと同じ要素数.それぞれnumericに何個あったかを格納 count = [0 for i in range(variety)] if variety > K: TypeOfNumber(vary, numeric, count) else: print(0) sys.exit() # プログラムを終了させたい # varyをkeyに、countをvalueとして辞書を作成 <-varyをkeyに出来ていない # 辞書をcountで昇順ソート dicNum = {} makeDictionary(vary, count, dicNum) # print(dicNum) # ここで辞書の要素数がK個より大きい時、合計で何個の数字を入れ替えるか数える ballcount = 0 ball = [] if len(count) > K: ball = list(dicNum.values()) # print(ball) for i in range(K): ball[i] = 0 # print(ball) for i in range(len(ball)): ballcount += ball[i] print(ballcount) # #[Caution!!]-関数内でグローバル変数を使う時は引数に入れてはいけない!global hoge と関数内で宣言!! # numeric内に何種類の数字があるかを判定 def TypeDetermination(numeric, vary): global element1, variety # element1=0で初期化していますが、入力される数字は1<=x<=Nなので、OK for element in numeric: if element1 is not numeric: variety += 1 element1 = element vary.append(element1) # TypeDeterminationでできたこと # n種類 is variety = n-1 # vary = [1,2,4]など、1種類1つずつ格納! # ここから先、継続して使うのは配列varyと変数varietyと配列numeric # 3種類以上の時、それぞれ何個ずつなのかを数える # vary配列を使う def TypeOfNumber(vary, numeric, count): global variety N = variety for i in range(N): # varyの中身、1つずつやっていく for j in range(len(numeric)): if vary[i] == numeric[j]: count[i] += 1 def makeDictionary(vary, count, dicNum): for i in range(len(count)): dicNum[vary[i]] = count[i] # これがうまく行ってない sorted(dicNum.items(), key=lambda x: x[1]) # 降順でソート if __name__ == "__main__": main()
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s340656802
Wrong Answer
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
import sys ## io ## def IS(): return sys.stdin.readline().rstrip() def II(): return int(IS()) def MII(): return list(map(int, IS().split())) def MIIZ(): return list(map(lambda x: x - 1, MII())) ## dp ## INIT_VAL = 0 def DD2(d1, d2): return [[INIT_VAL] * d2 for _ in range(d1)] def DD3(d1, d2, d3): return [DD2(d2, d3) for _ in range(d1)] ## math ## def to_bin(x: int) -> str: return format(x, "b") # rev => int(res, 2) def to_oct(x: int) -> str: return format(x, "o") # rev => int(res, 8) def to_hex(x: int) -> str: return format(x, "x") # rev => int(res, 16) MOD = 10**9 + 7 def divc(x, y) -> int: return -(-x // y) def divf(x, y) -> int: return x // y def gcd(x, y): while y: x, y = y, x % y return x def lcm(x, y): return x * y // gcd(x, y) def enumerate_divs(n): """Return a tuple list of divisor of n""" return [(i, n // i) for i in range(1, int(n**0.5) + 1) if n % i == 0] def get_primes(MAX_NUM=10**3): """Return a list of prime numbers n or less""" is_prime = [True] * (MAX_NUM + 1) is_prime[0] = is_prime[1] = False for i in range(2, int(MAX_NUM**0.5) + 1): if not is_prime[i]: continue for j in range(i * 2, MAX_NUM + 1, i): is_prime[j] = False return [i for i in range(MAX_NUM + 1) if is_prime[i]] ## libs ## from itertools import accumulate as acc from collections import deque, Counter from heapq import heapify, heappop, heappush from bisect import bisect_left # ======================================================# def main(): n, k = MII() aa = Counter(MII()) c = aa.most_common()[-(len(aa) - k) :] print(sum([ci[1] for ci in c])) if __name__ == "__main__": main()
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
Print the minimum number of balls that Takahashi needs to rewrite the integers on them. * * *
s099164085
Accepted
p03495
Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N
S = input().split(" ") N = int(S[0]) K = int(S[1]) ARR = [int(s) for s in input().split(" ")] def calculate(n, k, arr): dict = {} for ar in arr: if dict.get(ar) == None: dict.__setitem__(ar, 1) else: tmp = dict.get(ar) tmp = tmp + 1 dict.__setitem__(ar, tmp) sortedDict = sorted(dict.items(), key=lambda k: -k[1]) sum = 0 for i in sortedDict[k:]: sum = sum + i[1] print(sum) calculate(N, K, ARR)
Statement Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
[{"input": "5 2\n 1 1 2 2 5", "output": "1\n \n\nFor example, if we rewrite the integer on the fifth ball to 2, there are two\ndifferent integers written on the balls: 1 and 2. On the other hand, it is not\npossible to rewrite the integers on zero balls so that there are at most two\ndifferent integers written on the balls, so we should print 1.\n\n* * *"}, {"input": "4 4\n 1 1 2 2", "output": "0\n \n\nAlready in the beginning, there are two different integers written on the\nballs, so we do not need to rewrite anything.\n\n* * *"}, {"input": "10 3\n 5 1 3 2 4 1 1 2 3 4", "output": "3"}]
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
s431004006
Wrong Answer
p00743
The input consists of multiple datasets, each in the following format. > _n_ _m_ > _s_ _g_ > _x_ 1 _y_ 1 _d_ 1 _c_ 1 > ... > _x m _ _y m _ _d m _ _c m _ > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. _n_ is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. _m_ is the number of roads between cities, which may be zero. The second line gives the trip. _s_ is the city index of the starting city. _g_ is the city index of the goal city. _s_ is not equal to _g_. You can assume that all city indices in a dataset (including the above two) are between 1 and _n_ , inclusive. The following _m_ lines give the details of roads between cities. The _i_ -th road connects two cities with city indices _x i _ and _y i _, and has a distance _d i _ (1 ≤ _i_ ≤ _m_). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by _c i _. You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space).
# AOJ 1162: Discrete Speed # Python3 2018.7.15 bal4u INF = 0x7FFFFFFF import heapq def dijkstra(V, to, start, goal): node = [[[INF for k in range(32)] for j in range(V)] for i in range(V)] Q = [] node[start][0][0] = 0 heapq.heappush(Q, (0, start, 0, 0)) while Q: t, s, v, p = heapq.heappop(Q) if s == goal and v == 1: return node[goal][p][v] for e, d, c in to[s]: if e == p: continue for i in range(-1, 2): nv = v + i if nv > c or nv <= 0: continue nt = node[s][p][v] + d / nv if nt < node[e][s][nv]: node[e][s][nv] = nt heapq.heappush(Q, (nt, e, nv, s)) return -1 while True: n, m = map(int, input().split()) if n == 0: break s, g = map(int, input().split()) s -= 1 g -= 1 to = [[] for i in range(n)] for i in range(m): x, y, d, c = map(int, input().split()) x -= 1 y -= 1 to[x].append((y, d, c)) to[y].append((x, d, c)) ans = dijkstra(n, to, s, g) print(ans if ans >= 0 else "unreachable")
D: Discrete Speed Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed _v_ , it leaves the city at one of _v_ \- 1, _v_ , or _v_ \+ 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
[{"input": "0\n 1 2\n 5 4\n 1 5\n 1 2 1 1\n 2 3 2 2\n 3 4 2 2\n 4 5 1 1\n 6 6\n 1 6\n 1 2 2 1\n 2 3 2 1\n 3 6 2 1\n 1 4 2 30\n 4 5 3 30\n 5 6 2 30\n 6 7\n 1 6\n 1 2 1 30\n 2 3 1 30\n 3 1 1 30\n 3 4 100 30\n 4 5 1 30\n 5 6 1 30\n 6 4 1 30\n 0 0", "output": "unreachable\n 4.00000\n 5.50000\n 11.25664"}]
For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character _before each key_.
s072344934
Accepted
p02284
In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given.
import collections sent = -1 def insert(hoge, new_node, root): # print(hoge) parent_maybe = sent now_looking = root hoge[new_node]["node_id"] = new_node while now_looking != sent: parent_maybe = now_looking if new_node < hoge[now_looking]["node_id"]: now_looking = hoge[now_looking]["left"] else: now_looking = hoge[now_looking]["right"] hoge[new_node]["parent"] = parent_maybe if parent_maybe == sent: root = new_node hoge[new_node]["parent"] = sent hoge[new_node]["left"] = sent hoge[new_node]["right"] = sent elif new_node < hoge[parent_maybe]["node_id"]: hoge[parent_maybe]["left"] = new_node hoge[new_node]["left"] = sent hoge[new_node]["right"] = sent else: hoge[parent_maybe]["right"] = new_node hoge[new_node]["left"] = sent hoge[new_node]["right"] = sent return root def inorder(node_id): if node_id == sent: return None inorder(hoge[node_id]["left"]) print(" {}".format(node_id), end="") inorder(hoge[node_id]["right"]) def preorder(node_id): if node_id == sent: return None print(" {}".format(node_id), end="") preorder(hoge[node_id]["left"]) preorder(hoge[node_id]["right"]) def getTree(root): inorder(root) print() preorder(root) print() def searchNode(hoge, num, node_id): if node_id == -1: return "no" if num == node_id: return "yes" elif num < node_id: return searchNode(hoge, num, hoge[node_id]["left"]) elif num > node_id: return searchNode(hoge, num, hoge[node_id]["right"]) if __name__ == "__main__": num = int(input()) hoge = collections.defaultdict(dict) root = -1 for _ in range(num): command = input() if command.split()[0] == "insert": root = insert(hoge, int(command.split()[1]), root) elif command.split()[0] == "find": print(searchNode(hoge, int(command.split()[1]), root)) else: getTree(root)
Binary Search Tree II Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.
[{"input": "10\n insert 30\n insert 88\n insert 12\n insert 1\n insert 20\n find 12\n insert 17\n insert 25\n find 16\n print", "output": "yes\n no\n 1 12 17 20 25 30 88\n 30 12 1 20 17 25 88"}]
For each query with T_i=2, print the answer. * * *
s832984934
Wrong Answer
p02569
Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q
mod = 1000000007 eps = 10**-9 def main(): import sys input = sys.stdin.buffer.readline def op(a, b): a0, a1, aa = a b0, b1, bb = b return (a0 + b0, a1 + b1, aa + bb + a1 * b0) e = (0, 0, 0) def mapping(a, x, seg_len): if x: a0, a1, aa = a return (a1, a0, a0 * a1 - aa) else: return a def composition(x, y): return x ^ y id = 0 class LazySegTree: # Range update query def __init__( self, A, op=op, e=e, mapping=mapping, composition=composition, id=id, initialize=True, ): self.N = len(A) self.LV = (self.N - 1).bit_length() self.N0 = 1 << self.LV self.op = op self.e = e self.mapping = mapping self.composition = composition self.id = id if initialize: self.data = [self.e] * self.N0 + A + [self.e] * (self.N0 - self.N) for i in range(self.N0 - 1, 0, -1): self.data[i] = op(self.data[i * 2], self.data[i * 2 + 1]) else: self.data = [self.e] * (self.N0 * 2) self.lazy = [id] * (self.N0 * 2) def _ascend(self, i): for _ in range(i.bit_length() - 1): i >>= 1 self.data[i] = self.op(self.data[i * 2], self.data[i * 2 + 1]) def _descend(self, idx): lv = idx.bit_length() seg_len = 1 << self.LV for j in range(lv - 1, 0, -1): seg_len >>= 1 i = idx >> j x = self.lazy[i] if x == self.id: continue self.lazy[i * 2] = self.composition(self.lazy[i * 2], x) self.lazy[i * 2 + 1] = self.composition(self.lazy[i * 2 + 1], x) self.lazy[i] = self.id self.data[i * 2] = self.mapping(self.data[i * 2], x, seg_len) self.data[i * 2 + 1] = self.mapping(self.data[i * 2 + 1], x, seg_len) # open interval [l, r) def apply(self, l, r, x): l += self.N0 - 1 r += self.N0 - 1 self._descend(l // (l & -l)) self._descend(r // (r & -r) - 1) l_ori = l r_ori = r seg_len = 1 while l < r: if l & 1: self.data[l] = self.mapping(self.data[l], x, seg_len) self.lazy[l] = self.composition(self.lazy[l], x) l += 1 if r & 1: r -= 1 self.data[r] = self.mapping(self.data[r], x, seg_len) self.lazy[r] = self.composition(self.lazy[r], x) l >>= 1 r >>= 1 seg_len <<= 1 self._ascend(l_ori // (l_ori & -l_ori)) self._ascend(r_ori // (r_ori & -r_ori) - 1) # open interval [l, r) def query(self, l, r): l += self.N0 - 1 r += self.N0 - 1 self._descend(l // (l & -l)) self._descend(r // (r & -r) - 1) ret = self.e while l < r: if l & 1: ret = self.op(ret, self.data[l]) l += 1 if r & 1: ret = self.op(self.data[r - 1], ret) r -= 1 l >>= 1 r >>= 1 return ret N, Q = map(int, input().split()) A_raw = list(map(int, input().split())) A = [None] * N for i, a in enumerate(A_raw): if a: A[i] = (0, 1, 0) else: A[i] = (1, 0, 0) ST = LazySegTree(A) for _ in range(Q): t, l, r = map(int, input().split()) if t == 1: ST.apply(l, r + 1, 1) else: print(ST.query(l, r + 1)[2]) if __name__ == "__main__": main()
Statement You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j.
[{"input": "5 5\n 0 1 0 0 1\n 2 1 5\n 1 3 4\n 2 2 5\n 1 1 3\n 2 1 2", "output": "2\n 0\n 1\n \n\n * First query: Print 2, which is the inversion of (A_1,A_2,A_3,A_4,A_5)=(0,1,0,0,1).\n * Second query: Replace the value of A_3 and A_4 with 1 and 1, respectively.\n * Third query: Print 0, which is the inversion of (A_2,A_3,A_4,A_5)=(1,1,1,1).\n * Fourth query: Replace the value of A_1, A_2 and A_4 with 1, 0 and 0, respectively.\n * Fifth query: Print 1, which is the inversion of (A_1,A_2)=(1,0)."}]
For each query with T_i=2, print the answer. * * *
s776200691
Accepted
p02569
Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q
# self.data: 1-indexed # __1__ # _2_ _3_ # 4 5 6 7 # f(f(a, b), c) == f(a, f(b, c)) class LazySegmentTree: # a = [default] * n # O(n) def __init__(self, n, f, default=(0, 0, 1)): self.num_leaf = 2 ** (n - 1).bit_length() self.data = [default] * (2 * self.num_leaf) self.lazy = [True] * (2 * self.num_leaf) self.f = f # You can use first_update before you use update. # a[i] = x # O(log(n)) def first_update(self, i, x): i += self.num_leaf self.data[i] = x i >>= 1 while i > 0: self.data[i] = self.f(self.data[2 * i], self.data[2 * i + 1]) i >>= 1 def gindex(self, l, r): lis = [] l += self.num_leaf r += self.num_leaf lm = (l // (l & -l)) >> 1 rm = (r // (r & -r)) >> 1 while l < r: if l <= lm: lis.append(l) if r <= rm: lis.append(r) l >>= 1 r >>= 1 while l: lis.append(l) l >>= 1 lis.reverse() return lis def lazy_processing(self, i): self.data[i] = ( self.data[i][1] * self.data[i][2] - self.data[i][0], self.data[i][2], self.data[i][1], ) self.lazy[i] = not self.lazy[i] # from parent to children def propagate(self, lis): for i in lis: if self.lazy[i]: continue self.lazy_processing(2 * i) self.lazy_processing(2 * i + 1) self.lazy[i] = True # update a[l:r] def update(self, l, r): lis = self.gindex(l, r) # top-down propagation self.propagate(lis) l += self.num_leaf r += self.num_leaf - 1 while l < r: if l & 1: self.lazy_processing(l) l += 1 if not r & 1: self.lazy_processing(r) r -= 1 l >>= 1 r >>= 1 if l == r: self.lazy_processing(l) # bottom-up propagation lis.reverse() for i in lis: self.data[i] = self.f(self.data[2 * i], self.data[2 * i + 1]) # return f(a[l:r]) def query(self, l, r): # top-down propagation self.propagate(self.gindex(l, r)) l += self.num_leaf r += self.num_leaf - 1 lres, rres = (0, 1, 0), self.data[0] # self.data[0] == default while l < r: if l & 1: lres = self.f(lres, self.data[l]) l += 1 if not r & 1: rres = self.f(self.data[r], rres) r -= 1 l >>= 1 r >>= 1 if l == r: res = self.f(self.f(lres, self.data[l]), rres) else: res = self.f(lres, rres) return res from sys import stdin input = stdin.buffer.readline def main(): n, q = map(int, input().split()) a = list(map(int, input().split())) def f(tup1, tup2): return ( tup1[0] + tup2[0] + tup1[2] * tup2[1], tup1[1] + tup2[1], tup1[2] + tup2[2], ) lst = LazySegmentTree(n, f=f) for i, x in enumerate(a): lst.first_update(i, (0, 1 - x, x)) ans = [] for _ in range(q): t, l, r = list(map(int, input().split())) if t == 1: lst.update(l - 1, r) else: ans.append(lst.query(l - 1, r)[0]) for i in ans: print(i) main()
Statement You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j.
[{"input": "5 5\n 0 1 0 0 1\n 2 1 5\n 1 3 4\n 2 2 5\n 1 1 3\n 2 1 2", "output": "2\n 0\n 1\n \n\n * First query: Print 2, which is the inversion of (A_1,A_2,A_3,A_4,A_5)=(0,1,0,0,1).\n * Second query: Replace the value of A_3 and A_4 with 1 and 1, respectively.\n * Third query: Print 0, which is the inversion of (A_2,A_3,A_4,A_5)=(1,1,1,1).\n * Fourth query: Replace the value of A_1, A_2 and A_4 with 1, 0 and 0, respectively.\n * Fifth query: Print 1, which is the inversion of (A_1,A_2)=(1,0)."}]
For each query with T_i=2, print the answer. * * *
s070608268
Accepted
p02569
Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q
def I(): return int(input()) def MI(): return map(int, input().split()) def LI(): return list(map(int, input().split())) def main(): ####################### class LazySegmentTree: __slots__ = ["n", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"] def __init__( self, monoid_data, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator, func_operator_operator, ): self.me = monoid_identity self.oe = operator_identity self.fmm = func_monoid_monoid self.fmo = func_monoid_operator self.foo = func_operator_operator self.n = len(monoid_data) self.data = monoid_data * 2 for i in range(self.n - 1, 0, -1): self.data[i] = self.fmm(self.data[2 * i], self.data[2 * i + 1]) self.lazy = [self.oe] * (self.n * 2) def update(self, index, value): index += self.n # propagation for shift in range(index.bit_length() - 1, 0, -1): i = index >> shift self.lazy[2 * i] = self.foo(self.lazy[2 * i], self.lazy[i]) self.lazy[2 * i + 1] = self.foo(self.lazy[2 * i + 1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # update self.data[index] = value self.lazy[index] = self.oe # recalculation i = index while i > 1: i //= 2 self.data[i] = self.fmm( self.fmo(self.data[2 * i], self.lazy[2 * i]), self.fmo(self.data[2 * i + 1], self.lazy[2 * i + 1]), ) self.lazy[i] = self.oe def range_update(self, l, r, operator): l += self.n r += self.n # preparing indices indices = [] l0 = (l // (l & -l)) // 2 r0 = (r // (r & -r) - 1) // 2 while r0 > l0: indices.append(r0) r0 //= 2 while l0 > r0: indices.append(l0) l0 //= 2 while l0 and l0 != r0: indices.append(r0) r0 //= 2 if l0 == r0: break indices.append(l0) l0 //= 2 while r0: indices.append(r0) r0 //= 2 # propagation for i in reversed(indices): self.lazy[2 * i] = self.foo(self.lazy[2 * i], self.lazy[i]) self.lazy[2 * i + 1] = self.foo(self.lazy[2 * i + 1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # effect while l < r: if l % 2: self.lazy[l] = self.foo(self.lazy[l], operator) l += 1 if r % 2: r -= 1 self.lazy[r] = self.foo(self.lazy[r], operator) l //= 2 r //= 2 # recalculation for i in indices: self.data[i] = self.fmm( self.fmo(self.data[2 * i], self.lazy[2 * i]), self.fmo(self.data[2 * i + 1], self.lazy[2 * i + 1]), ) self.lazy[i] = self.oe def query(self, l, r): l += self.n r += self.n # preparing indices indices = [] l0 = (l // (l & -l)) // 2 r0 = (r // (r & -r) - 1) // 2 while r0 > l0: indices.append(r0) r0 //= 2 while l0 > r0: indices.append(l0) l0 //= 2 while l0 and l0 != r0: indices.append(r0) r0 //= 2 if l0 == r0: break indices.append(l0) l0 //= 2 while r0: indices.append(r0) r0 //= 2 # propagation for i in reversed(indices): self.lazy[2 * i] = self.foo(self.lazy[2 * i], self.lazy[i]) self.lazy[2 * i + 1] = self.foo(self.lazy[2 * i + 1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # fold left_folded = self.me right_folded = self.me while l < r: if l % 2: left_folded = self.fmm( left_folded, self.fmo(self.data[l], self.lazy[l]) ) l += 1 if r % 2: r -= 1 right_folded = self.fmm( self.fmo(self.data[r], self.lazy[r]), right_folded ) l //= 2 r //= 2 return self.fmm(left_folded, right_folded) ######################## N, Q = LI() A = LI() B = [] for i in range(N): # 0の個数,1の個数,反転数 if A[i]: temp = (0, 1, 0) else: temp = (1, 0, 0) B.append(temp) def foo(x, y): return x ^ y def fmm(x, y): z1 = x[0] + y[0] z2 = x[1] + y[1] z3 = x[2] + y[2] + x[1] * y[0] return (z1, z2, z3) def fmo(x, y): if y: z1 = x[1] z2 = x[0] z3 = x[0] * x[1] - x[2] return (z1, z2, z3) else: return x seg = LazySegmentTree(B, (0, 0, 0), 0, fmm, fmo, foo) ans = [] for _ in range(Q): t, l, r = MI() if t == 1: seg.range_update(l - 1, r, 1) else: temp = seg.query(l - 1, r) ans.append(temp[-1]) for v in ans: print(v) main()
Statement You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j.
[{"input": "5 5\n 0 1 0 0 1\n 2 1 5\n 1 3 4\n 2 2 5\n 1 1 3\n 2 1 2", "output": "2\n 0\n 1\n \n\n * First query: Print 2, which is the inversion of (A_1,A_2,A_3,A_4,A_5)=(0,1,0,0,1).\n * Second query: Replace the value of A_3 and A_4 with 1 and 1, respectively.\n * Third query: Print 0, which is the inversion of (A_2,A_3,A_4,A_5)=(1,1,1,1).\n * Fourth query: Replace the value of A_1, A_2 and A_4 with 1, 0 and 0, respectively.\n * Fifth query: Print 1, which is the inversion of (A_1,A_2)=(1,0)."}]
For each query with T_i=2, print the answer. * * *
s587033921
Accepted
p02569
Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q
import sys sys.setrecursionlimit(10**7) def MI(): return map(int, sys.stdin.readline().rstrip().split()) def LI(): return list(map(int, sys.stdin.readline().rstrip().split())) # 空白あり class LazySegTree: # モノイドに対して適用可能、Nが2冪でなくても良い def __init__(self, N, X_func, A_func, operate, X_unit, A_unit): self.N = N self.X_func = X_func self.A_func = A_func self.operate = operate self.X_unit = X_unit self.A_unit = A_unit self.X = [self.X_unit] * (2 * self.N) self.A = [self.A_unit] * (2 * self.N) self.size = [0] * (2 * self.N) def build(self, init_value): # 初期値を[N,2N)に格納 for i in range(self.N): self.X[self.N + i] = init_value[i] self.size[self.N + i] = 1 for i in range(self.N - 1, 0, -1): self.X[i] = self.X_func(self.X[i << 1], self.X[i << 1 | 1]) self.size[i] = self.size[i << 1] + self.size[i << 1 | 1] def update(self, i, x): # i番目(0-index)の値をxに変更 i += self.N self.X[i] = x i >>= 1 while i: self.X[i] = self.X_func(self.X[i << 1], self.X[i << 1 | 1]) i >>= 1 def eval_at(self, i): # i番目で作用を施した値を返す return self.operate(self.X[i], self.A[i], self.size[i]) def eval_above(self, i): # i番目より上の値を再計算する i >>= 1 while i: self.X[i] = self.X_func(self.eval_at(i << 1), self.eval_at(i << 1 | 1)) i >>= 1 def propagate_at(self, i): # i番目で作用を施し、1つ下に作用の情報を伝える self.X[i] = self.eval_at(i) self.A[i << 1] = self.A_func(self.A[i << 1], self.A[i]) self.A[i << 1 | 1] = self.A_func(self.A[i << 1 | 1], self.A[i]) self.A[i] = self.A_unit def propagate_above(self, i): # i番目より上で作用を施す H = i.bit_length() for h in range(H, 0, -1): self.propagate_at(i >> h) def fold(self, L, R): # [L,R)の区間取得 L += self.N R += self.N L0 = L // (L & -L) R0 = R // (R & -R) - 1 self.propagate_above(L0) self.propagate_above(R0) vL = self.X_unit vR = self.X_unit while L < R: if L & 1: vL = self.X_func(vL, self.eval_at(L)) L += 1 if R & 1: R -= 1 vR = self.X_func(self.eval_at(R), vR) L >>= 1 R >>= 1 return self.X_func(vL, vR) def operate_range(self, L, R, x): # [L,R)にxを作用 L += self.N R += self.N L0 = L // (L & -L) R0 = R // (R & -R) - 1 self.propagate_above(L0) self.propagate_above(R0) while L < R: if L & 1: self.A[L] = self.A_func(self.A[L], x) L += 1 if R & 1: R -= 1 self.A[R] = self.A_func(self.A[R], x) L >>= 1 R >>= 1 self.eval_above(L0) self.eval_above(R0) N, Q = MI() A = LI() B = [] for i in range(N): if A[i] == 0: B.append((0, 1, 0)) else: B.append((0, 0, 1)) # (その区間の転倒数,0の個数,1の個数) def X_func(x, y): x0, x1, x2 = x y0, y1, y2 = y return (x0 + y0 + x2 * y1, x1 + y1, x2 + y2) def A_func(a, b): return a ^ b def operate(x, a, r): # 右作用 if a == 0: return x x0, x1, x2 = x return (x1 * x2 - x0, x2, x1) X_unit = (0, 0, 0) A_unit = 0 LST = LazySegTree(N, X_func, A_func, operate, X_unit, A_unit) LST.build(B) for i in range(Q): T, L, R = MI() if T == 1: LST.operate_range(L - 1, R, 1) else: print(LST.fold(L - 1, R)[0])
Statement You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j.
[{"input": "5 5\n 0 1 0 0 1\n 2 1 5\n 1 3 4\n 2 2 5\n 1 1 3\n 2 1 2", "output": "2\n 0\n 1\n \n\n * First query: Print 2, which is the inversion of (A_1,A_2,A_3,A_4,A_5)=(0,1,0,0,1).\n * Second query: Replace the value of A_3 and A_4 with 1 and 1, respectively.\n * Third query: Print 0, which is the inversion of (A_2,A_3,A_4,A_5)=(1,1,1,1).\n * Fourth query: Replace the value of A_1, A_2 and A_4 with 1, 0 and 0, respectively.\n * Fifth query: Print 1, which is the inversion of (A_1,A_2)=(1,0)."}]
For each query with T_i=2, print the answer. * * *
s489802340
Accepted
p02569
Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q
I = [int(_) for _ in open(0).read().split()] N, Q = I[:2] A = I[2 : 2 + N] T = I[2 + N :: 3] L = I[3 + N :: 3] R = I[4 + N :: 3] class LazySegmentTree: def __init__(self, array, f, g, h, ti, ei): """ Parameters ---------- array : list to construct segment tree from f : func binary operation of the monoid T x T -> T T is dat g : func binary operation of the monoid T x E -> T T is dat, E is laz h : func binary operation of the monoid E x E -> T E is laz ti : T identity element of T ei : E identity element of E """ self.f = f self.g = g self.h = h self.ti = ti self.ei = ei self.height = height = len(array).bit_length() self.n = n = 2**height self.dat = dat = [ti] * n + array + [ti] * (n - len(array)) self.laz = [ei] * (2 * n) for i in range(n - 1, 0, -1): # build dat[i] = f(dat[i << 1], dat[i << 1 | 1]) def reflect(self, k): dat = self.dat ei = self.ei laz = self.laz g = self.g return self.dat[k] if laz[k] is ei else g(dat[k], laz[k]) def evaluate(self, k): laz = self.laz ei = self.ei reflect = self.reflect dat = self.dat h = self.h if laz[k] is ei: return laz[(k << 1) | 0] = h(laz[(k << 1) | 0], laz[k]) laz[(k << 1) | 1] = h(laz[(k << 1) | 1], laz[k]) dat[k] = reflect(k) laz[k] = ei def thrust(self, k): height = self.height evaluate = self.evaluate for i in range(height, 0, -1): evaluate(k >> i) def recalc(self, k): dat = self.dat reflect = self.reflect f = self.f while k: k >>= 1 dat[k] = f(reflect((k << 1) | 0), reflect((k << 1) | 1)) def update(self, a, b, x): # set value at position [a, b) (0-indexed) thrust = self.thrust n = self.n h = self.h laz = self.laz recalc = self.recalc a += n b += n - 1 l = a r = b + 1 thrust(a) thrust(b) while l < r: if l & 1: laz[l] = h(laz[l], x) l += 1 if r & 1: r -= 1 laz[r] = h(laz[r], x) l >>= 1 r >>= 1 recalc(a) recalc(b) def set_val(self, a, x): n = self.n thrust = self.thrust dat = self.dat laz = self.laz recalc = self.recalc ei = self.ei a += n thrust(a) dat[a] = x laz[a] = ei recalc(a) def query(self, a, b): # result on interval [a, b) (0-indexed) f = self.f ti = self.ti n = self.n thrust = self.thrust reflect = self.reflect a += n b += n - 1 thrust(a) thrust(b) l = a r = b + 1 vl = vr = ti while l < r: if l & 1: vl = f(vl, reflect(l)) l += 1 if r & 1: r -= 1 vr = f(reflect(r), vr) l >>= 1 r >>= 1 return f(vl, vr) # general linear functions array = [(0, 0, 0)] + [(0, 1, 0) if a else (1, 0, 0) for a in A] f = lambda a, b: (a[0] + b[0], a[1] + b[1], a[2] + b[2] + a[1] * b[0]) def g(a, b): if b == -1: x = a[1] y = a[0] z = (x + y) * (x + y - 1) // 2 - x * (x - 1) // 2 - y * (y - 1) // 2 - a[2] return (x, y, z) else: return a h = lambda a, b: a * b ti = (0, 0, 0) ei = 1 # b[0] * (a[0] * x + a[1]) + b[1] # = b[0] * a[0] * x + (b[0] * a[1] + b[1]) LST = LazySegmentTree(array=array, ti=ti, ei=ei, f=f, g=g, h=h) for t, l, r in zip(T, L, R): r += 1 if t == 1: LST.update(l, r, -1) else: print(LST.query(l, r)[2])
Statement You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j.
[{"input": "5 5\n 0 1 0 0 1\n 2 1 5\n 1 3 4\n 2 2 5\n 1 1 3\n 2 1 2", "output": "2\n 0\n 1\n \n\n * First query: Print 2, which is the inversion of (A_1,A_2,A_3,A_4,A_5)=(0,1,0,0,1).\n * Second query: Replace the value of A_3 and A_4 with 1 and 1, respectively.\n * Third query: Print 0, which is the inversion of (A_2,A_3,A_4,A_5)=(1,1,1,1).\n * Fourth query: Replace the value of A_1, A_2 and A_4 with 1, 0 and 0, respectively.\n * Fifth query: Print 1, which is the inversion of (A_1,A_2)=(1,0)."}]
For each query with T_i=2, print the answer. * * *
s323926427
Accepted
p02569
Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q
import sys input = lambda: sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x + "\n") ### 遅延評価セグメント木 class LazySegmentTree: def __init__(self, n, a=None): """初期化 num : n以上の最小の2のべき乗 """ num = 1 v = 0 while num <= n: num *= 2 v += 1 self.q = [None] * (2 * v + 10) self.num = num self.seg = [ninf] * (2 * self.num - 1) self.lazy = [f0] * (2 * self.num - 1) self.ls = [0] * (2 * self.num - 1) self.rs = [0] * (2 * self.num - 1) self.ls[0] = 0 self.rs[0] = self.num for i in range(self.num - 1): self.ls[2 * i + 1] = self.ls[i] self.rs[2 * i + 1] = (self.ls[i] + self.rs[i]) // 2 self.ls[2 * i + 2] = (self.ls[i] + self.rs[i]) // 2 self.rs[2 * i + 2] = self.rs[i] if a is not None: # O(n)で初期化 assert len(a) == n for i in range(n): self.seg[num - 1 + i] = a[i] for k in range(num - 2, -1, -1): self.seg[k] = op(self.seg[2 * k + 1], self.seg[2 * k + 2]) def eval(self, k): if self.lazy[k] == f0: return if k < self.num - 1: self.lazy[k * 2 + 1] = composition(self.lazy[k], self.lazy[k * 2 + 1]) self.lazy[k * 2 + 2] = composition(self.lazy[k], self.lazy[k * 2 + 2]) self.seg[k] = mapping(self.lazy[k], self.seg[k]) self.lazy[k] = f0 def eval_all(self): for i in range(2 * self.num - 1): self.eval(i) def update(self, a, b, x=None, f=None): """A[a]...A[b-1]をxに更新する""" if f is None: # 更新クエリ f = lambda y: x k = 0 self.q[0] = k # k>=0なら行きがけ順 ind = 1 # 重なる区間を深さ優先探索 while ind: ind -= 1 k = self.q[ind] l, r = self.ls[k], self.rs[k] if k >= 0: self.eval(k) if r <= a or b <= l: continue elif a <= l and r <= b: self.lazy[k] = composition(f, self.lazy[k]) self.eval(k) else: self.q[ind] = ~k self.q[ind + 1] = 2 * k + 1 self.q[ind + 2] = 2 * k + 2 ind += 3 # q.append(~k) # q.append(2*k+1) # q.append(2*k+2) else: k = ~k self.seg[k] = op(self.seg[2 * k + 1], self.seg[2 * k + 2]) def query(self, a, b): k = 0 l = 0 r = self.num self.q[0] = k ind = 1 ans = ninf # 重なる区間を深さ優先探索 while ind: ind -= 1 k = self.q[ind] l, r = self.ls[k], self.rs[k] self.eval(k) if r <= a or b <= l: continue elif a <= l and r <= b: ans = op(ans, self.seg[k]) else: self.q[ind] = 2 * k + 2 self.q[ind + 1] = 2 * k + 1 ind += 2 # q.append(2*k+2) # q.append(2*k+1) # print(q, ans, l,r,a,b, self.seg[k]) return ans n, q = list(map(int, input().split())) a = list(map(int, input().split())) # ninf = -10**9 # op = max # mapping = lambda f,x: f(x) # composition = lambda f1, f2: f1 if f1 is not None else f2 ninf = (0, 0, 0) # (転倒数, #0, #1) op = lambda x, y: (x[0] + y[0] + x[2] * y[1], x[1] + y[1], x[2] + y[2]) mapping = lambda f, x: ( ( (x[1] + x[2]) * (x[1] + x[2] - 1) // 2 - (x[1] * (x[1] - 1) // 2) - (x[2] * (x[2] - 1) // 2) - x[0], x[2], x[1], ) if f else x ) composition = lambda f1, f2: f1 ^ f2 f0 = False sg = LazySegmentTree(n, [((0, 1, 0) if item == 0 else (0, 0, 1)) for item in a]) ans = [] for _ in range(q): t = tuple(map(int, input().split())) if t[0] == 1: _, l, r = t sg.update(l - 1, r, f=True) else: _, l, r = t ans.append(sg.query(l - 1, r)[0]) # break write("\n".join(map(str, ans)))
Statement You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j.
[{"input": "5 5\n 0 1 0 0 1\n 2 1 5\n 1 3 4\n 2 2 5\n 1 1 3\n 2 1 2", "output": "2\n 0\n 1\n \n\n * First query: Print 2, which is the inversion of (A_1,A_2,A_3,A_4,A_5)=(0,1,0,0,1).\n * Second query: Replace the value of A_3 and A_4 with 1 and 1, respectively.\n * Third query: Print 0, which is the inversion of (A_2,A_3,A_4,A_5)=(1,1,1,1).\n * Fourth query: Replace the value of A_1, A_2 and A_4 with 1, 0 and 0, respectively.\n * Fifth query: Print 1, which is the inversion of (A_1,A_2)=(1,0)."}]
For each query with T_i=2, print the answer. * * *
s595978263
Accepted
p02569
Input is given from Standard Input in the following format: N Q A_1 A_2 \cdots A_N T_1 L_1 R_1 T_2 L_2 R_2 \vdots T_Q L_Q R_Q
import os import sys import numpy as np def solve(inp): SEGTREE_TABLES = [] COMMON_STACK = np.zeros(10**7, dtype=np.int64) def bit_length(n): ret = 0 while n: n >>= 1 ret += 1 return ret def segtree_init(n): n2 = 1 << bit_length(n) table = np.zeros((n2 << 1, 4), dtype=np.int64) SEGTREE_TABLES.append(table) return len(SEGTREE_TABLES) - 1 def segtree_build(ins, arr): table = SEGTREE_TABLES[ins] offset = table.shape[0] >> 1 table[:, 1] = 1 table[offset : offset + len(arr), 0] = 1 - arr table[offset : offset + len(arr), 1] = arr for i in range(offset - 1, 0, -1): ch = i << 1 table[i, 0] = table[ch, 0] + table[ch + 1, 0] table[i, 1] = table[ch, 1] + table[ch + 1, 1] table[i, 2] = ( table[ch, 2] + table[ch + 1, 2] + table[ch, 1] * table[ch + 1, 0] ) def segtree_eval(table, offset, i): if table[i, 3] == 0: return if i < offset: ch = i << 1 table[ch, 3] ^= 1 table[ch + 1, 3] ^= 1 table[i, 0], table[i, 1] = table[i, 1], table[i, 0] table[i, 2] = table[i, 0] * table[i, 1] - table[i, 2] table[i, 3] = 0 def segtree_bottomup(table, i): lch = i << 1 rch = lch + 1 l0, l1, l2 = table[lch, 0], table[lch, 1], table[lch, 2] r0, r1, r2 = table[rch, 0], table[rch, 1], table[rch, 2] if table[lch, 3]: l0, l1 = l1, l0 l2 = l0 * l1 - l2 if table[rch, 3]: r0, r1 = r1, r0 r2 = r0 * r1 - r2 table[i, 0] = l0 + r0 table[i, 1] = l1 + r1 table[i, 2] = l2 + r2 + l1 * r0 def segtree_range_swap(ins, l, r): """i for [l, r), Ai ← ~Ai""" table = SEGTREE_TABLES[ins] offset = table.shape[0] >> 1 stack = COMMON_STACK stack[:3] = (1, 0, offset) si = 3 updated = [] while si: i, a, b = stack[si - 3 : si] segtree_eval(table, offset, i) if b <= l or r <= a: si -= 3 continue if l <= a and b <= r: table[i, 3] ^= 1 si -= 3 continue updated.append(i) m = (a + b) // 2 stack[si - 3 : si] = (i << 1, a, m) stack[si : si + 3] = ((i << 1) + 1, m, b) si += 3 while updated: i = updated.pop() segtree_bottomup(table, i) def segtree_query(ins, l, r): """sum [l, r)""" table = SEGTREE_TABLES[ins] offset = table.shape[0] >> 1 stack = COMMON_STACK stack[:3] = (1, 0, offset) si = 3 pick = [] updated = [] while si: i, a, b = stack[si - 3 : si] segtree_eval(table, offset, i) if b <= l or r <= a: si -= 3 continue if l <= a and b <= r: pick.append((a, i)) si -= 3 continue updated.append(i) m = (a + b) // 2 stack[si - 3 : si] = (i << 1, a, m) stack[si : si + 3] = ((i << 1) + 1, m, b) si += 3 while updated: i = updated.pop() segtree_bottomup(table, i) pick.sort() cnt0, cnt1 = 0, 0 res = 0 for a, i in pick: r0, r1, r2 = table[i, 0], table[i, 1], table[i, 2] res += r2 + cnt1 * r0 cnt0 += r0 cnt1 += r1 return res def segtree_debug_print(ins): table = SEGTREE_TABLES[ins] offset = table.shape[0] >> 1 for t in range(4): i = 1 while i <= offset: print(table[i : 2 * i, t]) i <<= 1 n = inp[0] aaa = inp[2 : n + 2] ins = segtree_init(n) segtree_build(ins, aaa) qi = n + 2 ans = [] while qi < inp.size: t = inp[qi] if t == 1: segtree_range_swap(ins, inp[qi + 1] - 1, inp[qi + 2]) qi += 3 else: ans.append(segtree_query(ins, inp[qi + 1] - 1, inp[qi + 2])) qi += 3 return ans if sys.argv[-1] == "ONLINE_JUDGE": from numba.pycc import CC cc = CC("my_module") cc.export("solve", "(i8[:],)")(solve) cc.compile() exit() if os.name == "posix": # noinspection PyUnresolvedReferences from my_module import solve else: from numba import njit solve = njit("(i8[:],)", cache=True)(solve) print("compiled", file=sys.stderr) inp = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=" ") ans = solve(inp) print("\n".join(map(str, ans)))
Statement You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}. Note:The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j.
[{"input": "5 5\n 0 1 0 0 1\n 2 1 5\n 1 3 4\n 2 2 5\n 1 1 3\n 2 1 2", "output": "2\n 0\n 1\n \n\n * First query: Print 2, which is the inversion of (A_1,A_2,A_3,A_4,A_5)=(0,1,0,0,1).\n * Second query: Replace the value of A_3 and A_4 with 1 and 1, respectively.\n * Third query: Print 0, which is the inversion of (A_2,A_3,A_4,A_5)=(1,1,1,1).\n * Fourth query: Replace the value of A_1, A_2 and A_4 with 1, 0 and 0, respectively.\n * Fifth query: Print 1, which is the inversion of (A_1,A_2)=(1,0)."}]
For each dataset, print the coordinate (X, Y) of the person or "LOOP" in a line. X and Y should be separated by a space.
s301229130
Accepted
p00104
The input consists of multiple datasets. The input ends with a line which contains two 0. Each dataset consists of: H W H lines where each line contains W characters You can assume that 0 < W, H < 101\.
while True: H, W = list(map(int, input().split())) if H == 0 and W == 0: break else: a = list(input() for i in range(H)) visitedlist = [] h = 0 w = 0 while True: if [h, w] not in visitedlist: visitedlist.append([h, w]) if a[h][w] == ">": w += 1 if a[h][w] == "<": w -= 1 if a[h][w] == "^": h -= 1 if a[h][w] == "v": h += 1 if a[h][w] == ".": print(w, h) break else: print("LOOP") break
Magic Tile There is a magic room in a homestead. The room is paved with H × W tiles. There are five different tiles: * Tile with a east-pointing arrow * Tile with a west-pointing arrow * Tile with a south-pointing arrow * Tile with a north-pointing arrow * Tile with nothing Once a person steps onto a tile which has an arrow, the mystic force makes the person go to the next tile pointed by the arrow. If the next tile has an arrow, the person moves to the next, ans so on. The person moves on until he/she steps onto a tile which does not have the arrow (the tile with nothing). The entrance of the room is at the northwest corner. Your task is to write a program which simulates the movement of the person in the room. The program should read strings which represent the room and print the last position of the person. The input represents the room as seen from directly above, and up, down, left and right side of the input correspond to north, south, west and east side of the room respectively. The horizontal axis represents _x_ -axis (from 0 to W-1, inclusive) and the vertical axis represents _y_ -axis (from 0 to H-1, inclusive). The upper left tile corresponds to (0, 0). The following figure shows an example of the input: 10 10 >>>v..>>>v ...v..^..v ...>>>^..v .........v .v<<<<...v .v...^...v .v...^<<<< .v........ .v...^.... .>>>>^.... Characters represent tiles as follows: '>': Tile with a east-pointing arrow '<': Tile with a west-pointing arrow '^': Tile with a north-pointing arrow 'v': Tile with a south-pointing arrow '.': Tile with nothing If the person goes in cycles forever, your program should print "LOOP". You may assume that the person never goes outside of the room.
[{"input": "10\n >>>v..>>>v\n ...v..^..v\n >>>>>>^..v\n .........v\n .v<<<<...v\n .v.v.^...v\n .v.v.^<<<<\n .v.v.....v\n .v...^...v\n .>>>>^....\n 6 10\n >>>>>>>>>v\n .........v\n .........v\n >>>>v....v\n ^...v....v\n ^<<<<<<<<<\n 0 0", "output": "7\n LOOP"}]
For each dataset, print the coordinate (X, Y) of the person or "LOOP" in a line. X and Y should be separated by a space.
s497454838
Wrong Answer
p00104
The input consists of multiple datasets. The input ends with a line which contains two 0. Each dataset consists of: H W H lines where each line contains W characters You can assume that 0 < W, H < 101\.
H, W = map(int, input().split()) tiles = [input() for _ in range(H)] i = j = 0 info = {">": (0, 1), "<": (0, -1), "^": (-1, 0), "v": (1, 0), ".": (-1, -1)} for cnt in range(H * W): a, b = info[tiles[i][j]] if a == b == -1: print(j, i) break i += a j += b else: print("LOOP")
Magic Tile There is a magic room in a homestead. The room is paved with H × W tiles. There are five different tiles: * Tile with a east-pointing arrow * Tile with a west-pointing arrow * Tile with a south-pointing arrow * Tile with a north-pointing arrow * Tile with nothing Once a person steps onto a tile which has an arrow, the mystic force makes the person go to the next tile pointed by the arrow. If the next tile has an arrow, the person moves to the next, ans so on. The person moves on until he/she steps onto a tile which does not have the arrow (the tile with nothing). The entrance of the room is at the northwest corner. Your task is to write a program which simulates the movement of the person in the room. The program should read strings which represent the room and print the last position of the person. The input represents the room as seen from directly above, and up, down, left and right side of the input correspond to north, south, west and east side of the room respectively. The horizontal axis represents _x_ -axis (from 0 to W-1, inclusive) and the vertical axis represents _y_ -axis (from 0 to H-1, inclusive). The upper left tile corresponds to (0, 0). The following figure shows an example of the input: 10 10 >>>v..>>>v ...v..^..v ...>>>^..v .........v .v<<<<...v .v...^...v .v...^<<<< .v........ .v...^.... .>>>>^.... Characters represent tiles as follows: '>': Tile with a east-pointing arrow '<': Tile with a west-pointing arrow '^': Tile with a north-pointing arrow 'v': Tile with a south-pointing arrow '.': Tile with nothing If the person goes in cycles forever, your program should print "LOOP". You may assume that the person never goes outside of the room.
[{"input": "10\n >>>v..>>>v\n ...v..^..v\n >>>>>>^..v\n .........v\n .v<<<<...v\n .v.v.^...v\n .v.v.^<<<<\n .v.v.....v\n .v...^...v\n .>>>>^....\n 6 10\n >>>>>>>>>v\n .........v\n .........v\n >>>>v....v\n ^...v....v\n ^<<<<<<<<<\n 0 0", "output": "7\n LOOP"}]
For each dataset, print the coordinate (X, Y) of the person or "LOOP" in a line. X and Y should be separated by a space.
s028096141
Accepted
p00104
The input consists of multiple datasets. The input ends with a line which contains two 0. Each dataset consists of: H W H lines where each line contains W characters You can assume that 0 < W, H < 101\.
def magicall(tiles, a, b): point = tiles[a][b] if point == ".": return a, b elif point == ">": tiles[a][b] = "0" return magicall(tiles, a, b + 1) elif point == "<": tiles[a][b] = "0" return magicall(tiles, a, b - 1) elif point == "^": tiles[a][b] = "0" return magicall(tiles, a - 1, b) elif point == "v": tiles[a][b] = "0" return magicall(tiles, a + 1, b) elif point == "0": return "LOOP" while 1: H, W = map(int, input().split()) if H == 0: break tilis = [list(input()) for i in range(H)] answer = magicall(tilis, 0, 0) if type(answer) == tuple: print(answer[1], answer[0]) else: print(answer)
Magic Tile There is a magic room in a homestead. The room is paved with H × W tiles. There are five different tiles: * Tile with a east-pointing arrow * Tile with a west-pointing arrow * Tile with a south-pointing arrow * Tile with a north-pointing arrow * Tile with nothing Once a person steps onto a tile which has an arrow, the mystic force makes the person go to the next tile pointed by the arrow. If the next tile has an arrow, the person moves to the next, ans so on. The person moves on until he/she steps onto a tile which does not have the arrow (the tile with nothing). The entrance of the room is at the northwest corner. Your task is to write a program which simulates the movement of the person in the room. The program should read strings which represent the room and print the last position of the person. The input represents the room as seen from directly above, and up, down, left and right side of the input correspond to north, south, west and east side of the room respectively. The horizontal axis represents _x_ -axis (from 0 to W-1, inclusive) and the vertical axis represents _y_ -axis (from 0 to H-1, inclusive). The upper left tile corresponds to (0, 0). The following figure shows an example of the input: 10 10 >>>v..>>>v ...v..^..v ...>>>^..v .........v .v<<<<...v .v...^...v .v...^<<<< .v........ .v...^.... .>>>>^.... Characters represent tiles as follows: '>': Tile with a east-pointing arrow '<': Tile with a west-pointing arrow '^': Tile with a north-pointing arrow 'v': Tile with a south-pointing arrow '.': Tile with nothing If the person goes in cycles forever, your program should print "LOOP". You may assume that the person never goes outside of the room.
[{"input": "10\n >>>v..>>>v\n ...v..^..v\n >>>>>>^..v\n .........v\n .v<<<<...v\n .v.v.^...v\n .v.v.^<<<<\n .v.v.....v\n .v...^...v\n .>>>>^....\n 6 10\n >>>>>>>>>v\n .........v\n .........v\n >>>>v....v\n ^...v....v\n ^<<<<<<<<<\n 0 0", "output": "7\n LOOP"}]
For each dataset, print the coordinate (X, Y) of the person or "LOOP" in a line. X and Y should be separated by a space.
s070493814
Accepted
p00104
The input consists of multiple datasets. The input ends with a line which contains two 0. Each dataset consists of: H W H lines where each line contains W characters You can assume that 0 < W, H < 101\.
def run_magic_tiles(magic_tiles, past_matrix): i, j = 0, 0 while True: move = { "^": (-1, 0), "v": (1, 0), "<": (0, -1), ">": (0, 1), ".": (-1, -1), }.get(magic_tiles[i][j]) if move[0] == -1 and move[1] == -1: return j, i else: i += move[0] j += move[1] if past_matrix[i][j]: return "LOOP" past_matrix[i][j] = 1 def main(): while True: c, r = map(int, input().split(" ")) if c == 0 and r == 0: break past_matrix = [[0 for _ in range(r)] for _ in range(c)] tiles = [] for _ in range(c): tiles.append(list(input())) res = run_magic_tiles(tiles, past_matrix) print("LOOP" if res == "LOOP" else "%d %d" % (res[0], res[1])) if __name__ == "__main__": main()
Magic Tile There is a magic room in a homestead. The room is paved with H × W tiles. There are five different tiles: * Tile with a east-pointing arrow * Tile with a west-pointing arrow * Tile with a south-pointing arrow * Tile with a north-pointing arrow * Tile with nothing Once a person steps onto a tile which has an arrow, the mystic force makes the person go to the next tile pointed by the arrow. If the next tile has an arrow, the person moves to the next, ans so on. The person moves on until he/she steps onto a tile which does not have the arrow (the tile with nothing). The entrance of the room is at the northwest corner. Your task is to write a program which simulates the movement of the person in the room. The program should read strings which represent the room and print the last position of the person. The input represents the room as seen from directly above, and up, down, left and right side of the input correspond to north, south, west and east side of the room respectively. The horizontal axis represents _x_ -axis (from 0 to W-1, inclusive) and the vertical axis represents _y_ -axis (from 0 to H-1, inclusive). The upper left tile corresponds to (0, 0). The following figure shows an example of the input: 10 10 >>>v..>>>v ...v..^..v ...>>>^..v .........v .v<<<<...v .v...^...v .v...^<<<< .v........ .v...^.... .>>>>^.... Characters represent tiles as follows: '>': Tile with a east-pointing arrow '<': Tile with a west-pointing arrow '^': Tile with a north-pointing arrow 'v': Tile with a south-pointing arrow '.': Tile with nothing If the person goes in cycles forever, your program should print "LOOP". You may assume that the person never goes outside of the room.
[{"input": "10\n >>>v..>>>v\n ...v..^..v\n >>>>>>^..v\n .........v\n .v<<<<...v\n .v.v.^...v\n .v.v.^<<<<\n .v.v.....v\n .v...^...v\n .>>>>^....\n 6 10\n >>>>>>>>>v\n .........v\n .........v\n >>>>v....v\n ^...v....v\n ^<<<<<<<<<\n 0 0", "output": "7\n LOOP"}]
For each dataset, print the coordinate (X, Y) of the person or "LOOP" in a line. X and Y should be separated by a space.
s861372427
Accepted
p00104
The input consists of multiple datasets. The input ends with a line which contains two 0. Each dataset consists of: H W H lines where each line contains W characters You can assume that 0 < W, H < 101\.
import sys readline = sys.stdin.readline write = sys.stdout.write dd = ((-1, 0), (0, -1), (1, 0), (0, 1)) df = "<^>v".find def solve(): H, W = map(int, readline().split()) if H == 0: return False MP = [readline().strip() for i in range(H)] x = y = 0 used = [[0] * W for i in range(H)] used[0][0] = 1 while 1: i = df(MP[y][x]) if i == -1: write("%d %d\n" % (x, y)) return True dx, dy = dd[i] x += dx y += dy if used[y][x]: write("LOOP\n") return True used[y][x] = 1 while solve(): ...
Magic Tile There is a magic room in a homestead. The room is paved with H × W tiles. There are five different tiles: * Tile with a east-pointing arrow * Tile with a west-pointing arrow * Tile with a south-pointing arrow * Tile with a north-pointing arrow * Tile with nothing Once a person steps onto a tile which has an arrow, the mystic force makes the person go to the next tile pointed by the arrow. If the next tile has an arrow, the person moves to the next, ans so on. The person moves on until he/she steps onto a tile which does not have the arrow (the tile with nothing). The entrance of the room is at the northwest corner. Your task is to write a program which simulates the movement of the person in the room. The program should read strings which represent the room and print the last position of the person. The input represents the room as seen from directly above, and up, down, left and right side of the input correspond to north, south, west and east side of the room respectively. The horizontal axis represents _x_ -axis (from 0 to W-1, inclusive) and the vertical axis represents _y_ -axis (from 0 to H-1, inclusive). The upper left tile corresponds to (0, 0). The following figure shows an example of the input: 10 10 >>>v..>>>v ...v..^..v ...>>>^..v .........v .v<<<<...v .v...^...v .v...^<<<< .v........ .v...^.... .>>>>^.... Characters represent tiles as follows: '>': Tile with a east-pointing arrow '<': Tile with a west-pointing arrow '^': Tile with a north-pointing arrow 'v': Tile with a south-pointing arrow '.': Tile with nothing If the person goes in cycles forever, your program should print "LOOP". You may assume that the person never goes outside of the room.
[{"input": "10\n >>>v..>>>v\n ...v..^..v\n >>>>>>^..v\n .........v\n .v<<<<...v\n .v.v.^...v\n .v.v.^<<<<\n .v.v.....v\n .v...^...v\n .>>>>^....\n 6 10\n >>>>>>>>>v\n .........v\n .........v\n >>>>v....v\n ^...v....v\n ^<<<<<<<<<\n 0 0", "output": "7\n LOOP"}]
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7. * * *
s616409729
Accepted
p02990
Input is given from Standard Input in the following format: N K
class Mint: MOD = 1000000007 # Must be a prime CACHE_FACTORIALS = [1, 1] def __init__(self, v): if self.__isally(v): self.v = v.v else: self.v = v % self.MOD @property def inv(self): return Mint(self.__minv(self.v)) @classmethod def factorial(cls, v): for i in range(len(cls.CACHE_FACTORIALS), int(v) + 1): cls.CACHE_FACTORIALS.append(cls.CACHE_FACTORIALS[-1] * i % cls.MOD) return Mint(cls.CACHE_FACTORIALS[int(v)]) @classmethod def perm(cls, n, r): if n < r or r < 0: return 0 return cls.factorial(n) // cls.factorial(n - r) @classmethod def comb(cls, n, r): if n < r or r < 0: return 0 return cls.perm(n, r) // cls.factorial(r) @classmethod def __isally(cls, v) -> bool: return isinstance(v, cls) @classmethod def __minv(cls, v) -> int: return pow(v, cls.MOD - 2, cls.MOD) @classmethod def __mpow(cls, v, w) -> int: return pow(v, w, cls.MOD) def __str__(self): return str(self.v) __repr__ = __str__ def __int__(self): return self.v def __eq__(self, w): return self.v == w.v if self.__isally(w) else self.v == w def __add__(self, w): return Mint(self.v + w.v) if self.__isally(w) else Mint(self.v + w) __radd__ = __add__ def __sub__(self, w): return Mint(self.v - w.v) if self.__isally(w) else Mint(self.v - w) def __rsub__(self, u): return Mint(u.v - self.v) if self.__isally(u) else Mint(u - self.v) def __mul__(self, w): return Mint(self.v * w.v) if self.__isally(w) else Mint(self.v * w) __rmul__ = __mul__ def __floordiv__(self, w): return ( Mint(self.v * self.__minv(w.v)) if self.__isally(w) else Mint(self.v * self.__minv(w)) ) def __rfloordiv__(self, u): return ( Mint(u.v * self.__minv(self.v)) if self.__isally(u) else Mint(u * self.__minv(self.v)) ) def __pow__(self, w): return ( Mint(self.__mpow(self.v, w.v)) if self.__isally(w) else Mint(self.__mpow(self.v, w)) ) def __rpow__(self, u): return ( Mint(self.__mpow(u.v, self.v)) if self.__isally(u) else Mint(self.__mpow(u, self.v)) ) n, k = map(int, input().split()) for i in range(1, k + 1): print(Mint.comb(n - k + 1, i) * Mint.comb(k - 1, i - 1))
Statement There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls. First, Snuke will arrange the N balls in a row from left to right. Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible. How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.
[{"input": "5 3", "output": "3\n 6\n 1\n \n\nThere are three ways to arrange the balls so that Takahashi will need exactly\none move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B\nstands for red and blue, respectively).\n\nThere are six ways to arrange the balls so that Takahashi will need exactly\ntwo moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B),\n(B, R, B, B, R), and (B, R, R, B, B).\n\nThere is one way to arrange the balls so that Takahashi will need exactly\nthree moves: (B, R, B, R, B).\n\n* * *"}, {"input": "2000 3", "output": "1998\n 3990006\n 327341989\n \n\nBe sure to print the numbers of arrangements modulo 10^9+7."}]
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7. * * *
s431812876
Wrong Answer
p02990
Input is given from Standard Input in the following format: N K
import sys stdin = sys.stdin sys.setrecursionlimit(10**7) def li(): return map(int, stdin.readline().split()) def li_(): return map(lambda x: int(x) - 1, stdin.readline().split()) def lf(): return map(float, stdin.readline().split()) def ls(): return stdin.readline().split() def ns(): return stdin.readline().rstrip() def lc(): return list(ns()) def ni(): return int(stdin.readline()) def nf(): return float(stdin.readline()) class CombTools(object): def __init__(self, cap: int, mod: int): self.cap = cap self.mod = mod self.inv = self._calc_inv() self.fac = self._calc_fac() self.fac_inv = self._calc_fac_inv() def _calc_inv(self): inv = [0, 1] for i in range(2, self.cap + 1): inv.append((self.mod - (self.mod // i) * inv[self.mod % i]) % self.mod) return inv def _calc_fac(self): fac = [1] for i in range(1, self.cap + 1): fac.append((i * fac[-1]) % self.mod) return fac def _calc_fac_inv(self): fac_inv = [1] for i in range(1, self.cap + 1): fac_inv.append((self.inv[i] * fac_inv[-1]) % self.mod) return fac_inv def nCr(self, n: int, r: int): # validation if r > n: raise ValueError("n must be larger than r (n={}, r={})".format(n, r)) # calculation return self.fac[n] * self.fac_inv[n - r] * self.fac_inv[r] % self.mod def nPr(self, n: int, r: int): # validation if r > n: raise ValueError("n must be larger than r (n={}, r={})".format(n, r)) # calculation return self.fac[n] * self.fac_inv[n - r] % self.mod def nHr(self, n: int, r: int): return self.nCr(n + r - 1, n) n, k = li() CAP = 10**5 MOD = 10**9 + 7 ct = CombTools(CAP, MOD) for i in range(1, k + 1): ans = ct.nHr(n - k - i + 1, i + 1) * ct.nHr(k - i, i) print(ans % MOD)
Statement There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls. First, Snuke will arrange the N balls in a row from left to right. Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible. How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.
[{"input": "5 3", "output": "3\n 6\n 1\n \n\nThere are three ways to arrange the balls so that Takahashi will need exactly\none move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B\nstands for red and blue, respectively).\n\nThere are six ways to arrange the balls so that Takahashi will need exactly\ntwo moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B),\n(B, R, B, B, R), and (B, R, R, B, B).\n\nThere is one way to arrange the balls so that Takahashi will need exactly\nthree moves: (B, R, B, R, B).\n\n* * *"}, {"input": "2000 3", "output": "1998\n 3990006\n 327341989\n \n\nBe sure to print the numbers of arrangements modulo 10^9+7."}]
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7. * * *
s176562523
Wrong Answer
p02990
Input is given from Standard Input in the following format: N K
N, B = map(int, input().split()) R = N - B mod = pow(10, 9) + 7 ans = [0] * (B + 1) Bn = B - 1 Rn = R + 1 if R + 1 < B: Br = B - R - 1 Bbunshi = 1 Bbunbo = 1 for i in range(Br): Bbunshi = (Bbunshi * (Bn - i)) % mod Bbunbo = (Bbunbo * (i + 1)) % mod Rbunshi = 1 Rbunbo = 1 Rr = 1 Bn -= Br Br += 1 ans[R + 1] = (Bbunshi * pow(Bbunbo, -1, mod)) % mod print("tuuka", ans[R + 1]) elif R + 1 > B: Rr = R - B + 1 # ここあってるか未確認 Rbunshi = 1 Rbunbo = 1 for i in range(Rr): Rbunshi = (Rbunshi * (Rn - i)) % mod Rbunbo = (Rbunbo * (i + 1)) % mod Bbunshi = 1 Bbunbo = 1 Br = 1 Rn -= Rr Rr += 1 ans[B] = (Rbunshi * pow(Rbunbo, -1, mod)) % mod else: Br = 1 Bbunshi = 1 Bbunbo = 1 Rr = 1 Rbunshi = 1 Rbunbo = 1 ans[B] = 1 n = min(R + 1, B) for i in range(n - 1, 0, -1): Bbunshi = (Bbunshi * Bn) % mod Bbunbo = (Bbunbo * Br) % mod Rbunshi = (Rbunshi * Rn) % mod Rbunbo = (Rbunbo * Rr) % mod ans[i] = (Bbunshi * pow(Bbunbo, -1, mod)) % mod ans[i] *= (Rbunshi * pow(Rbunbo, -1, mod)) % mod Bn -= 1 Rn -= 1 Br += 1 Rr += 1 for i in range(1, B + 1): print(ans[i])
Statement There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls. First, Snuke will arrange the N balls in a row from left to right. Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible. How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.
[{"input": "5 3", "output": "3\n 6\n 1\n \n\nThere are three ways to arrange the balls so that Takahashi will need exactly\none move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B\nstands for red and blue, respectively).\n\nThere are six ways to arrange the balls so that Takahashi will need exactly\ntwo moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B),\n(B, R, B, B, R), and (B, R, R, B, B).\n\nThere is one way to arrange the balls so that Takahashi will need exactly\nthree moves: (B, R, B, R, B).\n\n* * *"}, {"input": "2000 3", "output": "1998\n 3990006\n 327341989\n \n\nBe sure to print the numbers of arrangements modulo 10^9+7."}]
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7. * * *
s775777414
Wrong Answer
p02990
Input is given from Standard Input in the following format: N K
class Combinatorics: def __init__(self, N, mod): """ Preprocess for calculating binomial coefficients nCr (0 <= r <= n, 0 <= n <= N) over the finite field Z/(mod)Z. Input: N (int): maximum n mod (int): a prime number. The order of the field Z/(mod)Z over which nCr is calculated. """ self.mod = mod self.fact = {i: None for i in range(N + 1)} # n! self.inverse = { i: None for i in range(1, N + 1) } # inverse of n in the field Z/(MOD)Z self.fact_inverse = { i: None for i in range(N + 1) } # inverse of n! in the field Z/(MOD)Z # preprocess self.fact[0] = self.fact[1] = 1 self.fact_inverse[0] = self.fact_inverse[1] = 1 self.inverse[1] = 1 for i in range(2, N + 1): self.fact[i] = i * self.fact[i - 1] % self.mod q, r = divmod(self.mod, i) self.inverse[i] = (-(q % self.mod) * self.inverse[r]) % self.mod self.fact_inverse[i] = self.inverse[i] * self.fact_inverse[i - 1] % self.mod def perm(self, n, r): """ Calculate nPr = n! / (n-r)! % mod """ if n < r or n < 0 or r < 0: return 0 else: return (self.fact[n] * self.fact_inverse[n - r]) % self.mod def binom(self, n, r): """ Calculate nCr = n! /(r! (n-r)!) % mod """ if n < r or n < 0 or r < 0: return 0 else: return ( self.fact[n] * (self.fact_inverse[r] * self.fact_inverse[n - r] % self.mod) % self.mod ) def hom(self, n, r): """ Calculate nHr = {n+r-1}Cr % mod. Assign r objects to one of n classes. Arrangement of r circles and n-1 partitions: o o o | o o | | | o | | | o o | | o """ if n == 0 and r > 0: return 0 if n >= 0 and r == 0: return 1 return self.binom(n + r - 1, r) N, K = map(int, input().split()) MOD = 10**9 + 7 com = Combinatorics(N, MOD) for i in range(1, K + 1): blue = com.binom(K - 1, i - 1) red = ( com.binom(N - K - 1, i) + 2 * com.binom(N - K - 1, i - 1) + com.binom(N - K - 1, i - 2) ) % MOD ans = (blue * red) % MOD print(ans)
Statement There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls. First, Snuke will arrange the N balls in a row from left to right. Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible. How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.
[{"input": "5 3", "output": "3\n 6\n 1\n \n\nThere are three ways to arrange the balls so that Takahashi will need exactly\none move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B\nstands for red and blue, respectively).\n\nThere are six ways to arrange the balls so that Takahashi will need exactly\ntwo moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B),\n(B, R, B, B, R), and (B, R, R, B, B).\n\nThere is one way to arrange the balls so that Takahashi will need exactly\nthree moves: (B, R, B, R, B).\n\n* * *"}, {"input": "2000 3", "output": "1998\n 3990006\n 327341989\n \n\nBe sure to print the numbers of arrangements modulo 10^9+7."}]
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7. * * *
s536317958
Accepted
p02990
Input is given from Standard Input in the following format: N K
# -*- coding: utf-8 -*- MOD = 10**9 + 7 class BiCoeff(object): def __init__(self, MAX, m): super(BiCoeff, self).__init__() fac = [0] * MAX finv = [0] * MAX inv = [0] * MAX fac[0] = 1 fac[1] = 1 finv[0] = 1 finv[1] = 1 inv[1] = 1 for i in range(2, MAX): fac[i] = (fac[i - 1] * i) % m inv[i] = m - (inv[m % i] * (m // i)) % m finv[i] = (finv[i - 1] * inv[i]) % m self.MAX = MAX self.m = m self.fac = fac self.finv = finv self.inv = inv def calc(self, n, k): if n < k: return 0 if n < 0 or k < 0: return 0 return (self.fac[n] * (self.finv[k] * self.finv[n - k]) % self.m) % self.m bi = BiCoeff(2001, MOD) n, k = map(int, input().split()) for i in range(1, k + 1): a = (bi.calc(n - k + 1, i) * bi.calc(k - 1, i - 1)) % MOD print(a)
Statement There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls. First, Snuke will arrange the N balls in a row from left to right. Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible. How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.
[{"input": "5 3", "output": "3\n 6\n 1\n \n\nThere are three ways to arrange the balls so that Takahashi will need exactly\none move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B\nstands for red and blue, respectively).\n\nThere are six ways to arrange the balls so that Takahashi will need exactly\ntwo moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B),\n(B, R, B, B, R), and (B, R, R, B, B).\n\nThere is one way to arrange the balls so that Takahashi will need exactly\nthree moves: (B, R, B, R, B).\n\n* * *"}, {"input": "2000 3", "output": "1998\n 3990006\n 327341989\n \n\nBe sure to print the numbers of arrangements modulo 10^9+7."}]
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7. * * *
s357136339
Wrong Answer
p02990
Input is given from Standard Input in the following format: N K
def euclid(a, n): a0 = a a1 = n x0 = 1 x1 = 0 while a1 != 1: q = a0 // a1 temp = a1 a1 = a0 - a1 * q a0 = temp temp = x1 x1 = x0 - q * x1 x0 = temp if x1 < 0: x1 = n + x1 return x1 n, k = map(int, input().split()) r = n - k z = 10**9 + 7 tm = [1] for i in range(1, n + 1): tm.append(tm[-1] * i % z) tm.append(1) print(r + 1) c = min(k, r + 1) a = tm[r + 1] for i in range(2, c + 1): b = tm[k - 1] * euclid(tm[i - 1] * tm[k - i], z) % z print(b * a * euclid(tm[i] * tm[r - i + 1] % z, z) % z) for j in range(i, k): print(0)
Statement There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls. First, Snuke will arrange the N balls in a row from left to right. Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible. How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.
[{"input": "5 3", "output": "3\n 6\n 1\n \n\nThere are three ways to arrange the balls so that Takahashi will need exactly\none move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B\nstands for red and blue, respectively).\n\nThere are six ways to arrange the balls so that Takahashi will need exactly\ntwo moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B),\n(B, R, B, B, R), and (B, R, R, B, B).\n\nThere is one way to arrange the balls so that Takahashi will need exactly\nthree moves: (B, R, B, R, B).\n\n* * *"}, {"input": "2000 3", "output": "1998\n 3990006\n 327341989\n \n\nBe sure to print the numbers of arrangements modulo 10^9+7."}]
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7. * * *
s414348182
Runtime Error
p02990
Input is given from Standard Input in the following format: N K
# n個からk個を選ぶ順列 def perm(n, k): if n == 0: return 0 else: result = 1 if k != 0: for i in range(k): result *= n - i return result # n個からk個を選ぶ組合せ def comb(n, k): if n == 0: return 0 else: k = min(k, n - k) if k == 0: return 1 else: return perm(n, k) / perm(k, k) # n種類からk個を選ぶ重複組合せ def homo(n, k): if n == 0: return 0 else: return comb(n + k - 1, k) def main(n, k, i): # 青玉k個のうち、まずi箇所に1個ずつ配置 # 残りの(k - i)個を、ゼロを許容してi箇所に配置 => i種類から(k - i)個を選ぶ重複組合せ result = homo(i, k - i) # 赤玉(n - k)個のうち、まず(i - 1)個は青玉を区切るために配置 # 残りの(n - k - i + 1)個を、ゼロを許容して(i + 1)箇所に配置 => (i + 1)種類から(n - k - i + 1)個を選ぶ重複組合せ result *= homo(i + 1, n - k - i + 1) result = result % (10**9 + 7) return int(result) N, K = [int(x) for x in input().split()] for i in range(K): print(main(N, K, i + 1))
Statement There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls. First, Snuke will arrange the N balls in a row from left to right. Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible. How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.
[{"input": "5 3", "output": "3\n 6\n 1\n \n\nThere are three ways to arrange the balls so that Takahashi will need exactly\none move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B\nstands for red and blue, respectively).\n\nThere are six ways to arrange the balls so that Takahashi will need exactly\ntwo moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B),\n(B, R, B, B, R), and (B, R, R, B, B).\n\nThere is one way to arrange the balls so that Takahashi will need exactly\nthree moves: (B, R, B, R, B).\n\n* * *"}, {"input": "2000 3", "output": "1998\n 3990006\n 327341989\n \n\nBe sure to print the numbers of arrangements modulo 10^9+7."}]
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7. * * *
s331688056
Accepted
p02990
Input is given from Standard Input in the following format: N K
import sys sys.setrecursionlimit(200000) input = sys.stdin.readline def ii(): return int(input()) def mi(): return map(int, input().rstrip().split()) def lmi(): return list(map(int, input().rstrip().split())) def li(): return list(input().rstrip()) # template # BEGIN CUT HERE MOD = 10**9 + 7 class Modint: """ 自動でMODで割った余りを返してくれる。 """ def __init__(self, n, mod=MOD): if n >= 0: self.n = n % mod else: self.n = (mod - (-n) % mod) % mod self.mod = mod def __eq__(self, other): return self.n == int(other) def __ne__(self, other): return not self == other def __neg__(self): return Modint(-self.n, self.mod) def __str__(self): return str(self.n) def __int__(self): return int(self.n) def __iadd__(self, other): self.n += int(other) self.n %= self.mod return self def __radd__(self, other): self.n += int(other) self.n %= self.mod return self def __isub__(self, other): self.n -= int(other) self.n %= self.mod return self def __rsub__(self, other): self.n -= int(other) self.n %= self.mod return self def __imul__(self, other): self.n = self.n * int(other) % self.mod return self def __rmul__(self, other): self.n = self.n * int(other) % self.mod return self def inverse(self): return self.__class__(pow(self.n, self.mod - 2, self.mod), self.mod) def __ifloordiv__(self, other): self *= pow(int(other), self.mod - 2, self.mod) return self def __rfloordiv__(self, other): self *= pow(int(other), self.mod - 2, self.mod) return self def __add__(self, other): self += other return self def __sub__(self, other): self -= other return self def __mul__(self, other): self *= other return self def __floordiv__(self, other): self //= other return self """コンビネーション絡みの定義 ・ comb(n,k):特に前処理をせずnCkを求める """ def comb(self, n, k): if n < k or k < 0: return Modint(0) res = Modint(1) for i in range(int(k)): res *= Modint(n - i) res //= Modint(i + 1) return res def H(self, n, k): if n < 0 or k < 0: return Modint(0) elif n == 0 and k == 0: return Modint(1) else: return self.comb(n + k - 1, n) if __name__ == "__main__": N, K = mi() res = Modint(0) for i in range(1, K + 1): print(res.comb(K - 1, i - 1) * res.H(N - K - i + 1, i + 1))
Statement There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls. First, Snuke will arrange the N balls in a row from left to right. Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible. How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.
[{"input": "5 3", "output": "3\n 6\n 1\n \n\nThere are three ways to arrange the balls so that Takahashi will need exactly\none move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B\nstands for red and blue, respectively).\n\nThere are six ways to arrange the balls so that Takahashi will need exactly\ntwo moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B),\n(B, R, B, B, R), and (B, R, R, B, B).\n\nThere is one way to arrange the balls so that Takahashi will need exactly\nthree moves: (B, R, B, R, B).\n\n* * *"}, {"input": "2000 3", "output": "1998\n 3990006\n 327341989\n \n\nBe sure to print the numbers of arrangements modulo 10^9+7."}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s918393594
Accepted
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
import heapq n = int(input()) pts = [list(map(int, input().split())) for _ in range(n)] x = sorted([(i, pts[i][0]) for i in range(n)], key=lambda x: x[1]) y = sorted([(i, pts[i][1]) for i in range(n)], key=lambda x: x[1]) invx = [0] * n invy = [0] * n for i in range(n): invx[x[i][0]] = i invy[y[i][0]] = i q = [(0, 0)] visit = [0] * n ans = 0 while q: cnt, i = heapq.heappop(q) if visit[i] == 1: continue visit[i] = 1 ans += cnt xi = invx[i] yi = invy[i] for delta in [-1, 1]: nx = xi + delta ny = yi + delta if 0 <= nx < n and visit[x[nx][0]] == 0: heapq.heappush(q, (abs(x[nx][1] - x[xi][1]), x[nx][0])) if 0 <= ny < n and visit[y[ny][0]] == 0: heapq.heappush(q, (abs(y[ny][1] - y[yi][1]), y[ny][0])) print(ans)
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s171933380
Runtime Error
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
import sys input = sys.stdin.readline import heapq def prim_heap(): used = [True] * n #True:不使用 edgelist = [] for e in edge[0]: heapq.heappush(edgelist,e) used[0] = False res = 0 while len(edgelist) != 0: minedge = heapq.heappop(edgelist) if not used[minedge[1]]: continue v = minedge[1] used[v] = False for e in edge[v]: if used[e[1]]: heapq.heappush(edgelist,e) res += minedge[0] return res n = int(input()) st = [] edge = [[] for i in range(n)] for i in range(n): x,y = map(int,input().split()) st_append = st.append st_append((i,x,y)) from operator import itemgetter bb = tuple(sorted(st,key=itemgetter(1))) chk = tuple(sorted(st,key=itemgetter(2))) #print(bb,chk) for i in range(n-1): x = bb[i][0] y = bb[i+1][0] z = bb[i+1][1]-bb[i][1] edge[x]_append = edge[x].append edge[y]_append = edge[y].append edge[x]_append([z,y]) edge[y]_append([z,x]) for i in range(n-1): a = chk[i][0] b = chk[i+1][0] c = chk[i+1][2]-chk[i][2] edge[a]_append = edge[a].append edge[b]_append = edge[b].append edge[a]_append([c,b]) edge[b]_append([c,a]) print(prim_heap())
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s561632496
Runtime Error
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
def main: import sys input = sys.stdin.readline import heapq def prim_heap(): used = [True] * n #True:不使用 edgelist = [] for e in edge[0]: heapq.heappush(edgelist,e) used[0] = False res = 0 while len(edgelist) != 0: minedge = heapq.heappop(edgelist) if not used[minedge[1]]: continue v = minedge[1] used[v] = False for e in edge[v]: if used[e[1]]: heapq.heappush(edgelist,e) res += minedge[0] return res from collections import deque n = int(input()) st = deque([]) edge = deque([[] for i in range(n)]) for i in range(n): x,y = map(int,input().split()) st_append = st.append st_append((i,x,y)) from operator import itemgetter bb = tuple(sorted(st,key=itemgetter(1))) chk = tuple(sorted(st,key=itemgetter(2))) #print(bb,chk) for i in range(n-1): x = bb[i][0] y = bb[i+1][0] z = bb[i+1][1]-bb[i][1] edge[x].append((z,y)) edge[y].append((z,x)) for i in range(n-1): a = chk[i][0] b = chk[i+1][0] c = chk[i+1][2]-chk[i][2] edge[a].append((c,b)) edge[b].append((c,a)) edge = tuple(edge) print(prim_heap()) if __name__ == '__main__': main()
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s504526297
Wrong Answer
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
n = int(input()) cities_x = [list(map(int, input().split())) for _ in range(n)] for i in range(n): cities_x[i].append(i) cities_y = cities_x[:] cities_x.sort() cities_y.sort(key=lambda x: x[1]) graph_1 = [[0] * n] * n graph_2 = [[0] * n] * n memory = [[0] * 2] * n ans = 0 for i in range(n - 1): if i == n - 1: p = abs(cities_x[i][0] - cities_x[0][0]) graph_1[cities_x[i][2]][cities_x[0][2]] = 1 graph_1[cities_x[0][2]][cities_x[i][2]] = 1 memory[cities_x[i][2]][0] = p ans += p else: p = abs(cities_x[i][0] - cities_x[i + 1][0]) graph_1[cities_x[i][2]][cities_x[i + 1][2]] = 1 graph_1[cities_x[i + 1][2]][cities_x[i][2]] = 1 memory[cities_x[i][2]][0] = p ans += p for i in range(n): if i == n - 1: p = abs(cities_y[i][0] - cities_y[0][0]) graph_1[cities_y[i][2]][cities_y[0][2]] = 1 graph_1[cities_y[0][2]][cities_y[i][2]] = 1 memory[cities_y[i][2]][1] = p ans += p else: p = abs(cities_y[i][0] - cities_y[i + 1][0]) graph_1[cities_y[i][2]][cities_y[i + 1][2]] = 1 graph_1[cities_y[i + 1][2]][cities_y[i][2]] = 1 memory[cities_y[i][2]][1] = p ans += p for i in range(n): ans -= max(memory[i]) print(ans // 2)
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s169502067
Runtime Error
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
#最小全域木 プリム法 from heapq import * n=int(input()) xy=[] for i in range(n): x,y=map(int,input().split()) xy.append([x,y,i]) #今回の問題では,高々xが隣のやつとyが隣のやつを全部考えればよし #(詳しくは解説pdfより) x_sort = sorted(xy, key=lambda x: x[0]) y_sort = sorted(xy, key=lambda x: x[1]) cost = [[]for _ in range(n+3)] #cost[i]にはi番目から(j,k)でj番目にコストkかかる for i in range(n-1): cost[x_sort[i][2]].append((x_sort[i+1][2],x_sort[i+1][0]-x_sort[i][0])) cost[x_sort[i+1][2]].append((x_sort[i][2],x_sort[i+1][0]-x_sort[i][0])) cost[y_sort[i][2]].append((y_sort[i+1][2],y_sort[i+1][1]-y_sort[i][1])) cost[y_sort[i+1][2]].append((y_sort[i][2],y_sort[i+1][1]-y_sort[i][1])) used=[False]*(n+3)#頂点が最小全域木にもうすでに含まれているかどうか q=[] #すでに最小全域木が決まっている部分からまだ決まっていない部分への辺をヒープで管理 #(a,b)でaには向かう先の頂点,bにはかかるコスト #ヒープで小さいコストからとりだせる #初期条件 #はじめはどこでもよいので0番目スタートとする(0番目だけではコストは0) used[0] = True ans = 0 #0番目からの辺をすべてヒープに挿入 for to,cst in cost[0]: heappush(q,(cst,to)) #すでに決まっている最小全域木部分からまだ決まっていない部分を貪欲的にひたすら追加する #はじめは初期条件の通り while(len(q)!=0): c,ver=heappop(q) #すでに決まっている部分から一番小さいコストの辺を取り出す if used[ver] == True: continue #もしすでに最小全域木部分であればやり直し #そうでなければコストの分を加算し、新しい頂点を最小全域木部分に追加する ans += c used[ver] = True #新しく追加した頂点からの辺をヒープに追加する for to,cst in cost[ver]: heappush(q,(cst,to))  #これを貪欲的に繰り返すことでうまくいくらしい print(ans)
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s596025120
Runtime Error
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
#!/usr/bin/env python3 from collections import defaultdict from collections import deque from heapq import heappush, heappop import sys import math import bisect import random import itertools sys.setrecursionlimit(10**5) stdin = sys.stdin bisect_left = bisect.bisect_left bisect_right = bisect.bisect_right def LI(): return list(map(int, stdin.readline().split())) def LF(): return list(map(float, stdin.readline().split())) def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split())) def II(): return int(stdin.readline()) def IF(): return float(stdin.readline()) def LS(): return list(map(list, stdin.readline().split())) def S(): return list(stdin.readline().rstrip()) def IR(n): return [II() for _ in range(n)] def LIR(n): return [LI() for _ in range(n)] def FR(n): return [IF() for _ in range(n)] def LFR(n): return [LI() for _ in range(n)] def LIR_(n): return [LI_() for _ in range(n)] def SR(n): return [S() for _ in range(n)] def LSR(n): return [LS() for _ in range(n)] mod = 1000000007 inf = float('INF') #A def A(): x, a, b = LI() if b <= a: print("delicious") elif b <= a + x: print("safe") else: print("dangerous") return #B def B(): n = II() a = IR(n) check = [False] * (n + 1) check[1] = True now = a[0] for i in range(1,n+1): if check[now]: break if now == 2: print(i) return check[now] = True now = a[now - 1] print(-1) return #C def C(): return #D def D(): def find(x): if x == par[x]: return x par[x] = find(par[x]) return par[x] def same(x, y): return find(x) == find(y) def unite(x, y): x = find(x) y = find(y) par[y] = x return True def solve(a, k): for i in range(n-1): q0, q1 = xy[i][k], xy[i + 1][k] z, v = xy[i][2], xy[i + 1][2] edg[a + i] = [q1 - q0, z, v] n = II() par = [i for i in range(n)] xy = [None] * n for i in range(n): x, y = LI() xy[i] = [x, y, i] xy.sort(key=lambda x: x[0]) edg = [None] * (2 * n - 2) solve(0, 0) xy.sort(key=lambda x: x[1]) solve(n - 1, 1) ans = 0 a = 0 edg.sort(key=lambda x: x[0]) for i in range(2 * n - 2): value, p0, p1 = edg[i] if a == n - 1: break if not same(p0, p1): unite(p0, p1): a += 1 ans += value print(ans) return #Solve if __name__ == '__main__': D()
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s693487129
Runtime Error
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
import heapq from bisect import bisect_left,bisect_right INFTY = 10**10 N = int(input()) X = [list(map(int,input().split())) for _ in range(N)] A = sorted([(X[i][0],-X[i][1],i) for i in range(N)],key=lambda x:x[1]) A = sorted([(X[i][0],-X[i][1],i) for i in range(N)],key=lambda x:x[0]) B = sorted([(X[i][1],-X[i][0],i) for i in range(N)],key=lambda x:x[1]) B = sorted([(X[i][1],-X[i][0],i) for i in range(N)],key=lambda x:x[0]) hist = [0 for _ in range(N)] heap = [(0,0)] cnt = 0 while heap: d,i = heapq.heappop(heap) if hist[i]==1:continue hist[i] = 1 cnt += d indx0 = bisect_left(A,(X[i][0],-INFTY,0)) j = indx0 while j<N: if A[j][0]==X[i][0]: if A[j][2]!=i: hist[A[j][2]] = 1 else:break j += 1 if indx0>0: d0 = A[indx0][0]-A[indx0-1][0] j = A[indx0-1][2] if hist[j]==0: heapq.heappush(heap,(d0,j)) indx1 = bisect_right(A,(X[i][0],1,N)) if indx1<N: d1 = A[indx1][0]-A[indx1-1][0] j = A[indx1][2] if hist[j]==0: heapq.heappush(heap,(d1,j)) indy0 = bisect_left(B,(X[i][1],-INFTY,0)) j = indy0 while j<N: if B[j][0]==X[i][1]: if B[j][2]!=i: hist[B[j][2]] = 1 else B[j][0]!=X[i][1]: break j += 1 if indy0>0: d0 = B[indy0][0]-B[indy0-1][0] j = B[indy0-1][2] if hist[j]==0: heapq.heappush(heap,(d0,j)) indy1 = bisect_right(B,(X[i][1],1,N)) if indy1<N: d1 = B[indy1][0]-B[indy1-1][0] j = B[indy1][2] if hist[j]==0: heapq.heappush(heap,(d1,j)) print(cnt)
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s816815407
Runtime Error
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
#include<iostream> #include<iomanip> #include<cstdio> #include<vector> #include<queue> #include<set> #include<map> #include<string> #include<algorithm> #include<cmath> #include<numeric> using namespace std; typedef long long ll; template <class T> inline bool chmax(T& a, T b) {if (a < b) {a = b; return 1;} return 0;} template <class T> inline bool chmin(T& a, T b) {if (a > b) {a = b; return 1;} return 0;} /* 木にすべき N-1本 最小全域木を作りたい 可能性のある道は、x,yそれぞれで隣接した辺のみで合計候補2nぐらい これにクラスカル? */ const int MAX_N = 100000; int par[MAX_N]; int rk[MAX_N]; //配列が長さnのものとして0で初期化する void init(int n) { for (int i = 0; i < n; i++) { par[i] = i; rk[i] = 0; } } //xの親の要素の番号を返す int find(int x) { if (par[x] == x) { return x; } else { return par[x] = find(par[x]); } } //要素を併合する //木の高さrkが低いほうを高いほうの親につなげる void unite(int x, int y){ x = find(x); y = find(y); if (x == y) return; if (rk[x] < rk[y]) { par[x] = y; } else { par[y] = x; if (rk[x] == rk[y]) rk[x]++; } } //要素が同じ集合に属しているかどうかを返す bool same(int x, int y) { return find(x) == find(y); } const int MAX_E = 2e5; struct edge {int u, v, cost;}; bool comp(const edge& e1, const edge& e2) { return e1.cost < e2.cost; } edge es[MAX_E]; int V, E; //クラスカル法 UNION_FINDを使って既に同じ木にあるかどうか判定する ll kruskal() { sort(es, es + E, comp); init(V); int res = 0; for (int i = 0; i < E; i++) { edge e = es[i]; if (!same(e.u, e.v)) { unite(e.u,e.v); res += (ll)e.cost; } } return res; } int main() { int N; cin >> N; vector<pair<ll,ll> > x(N), y(N); for (int i = 0; i < N; i++) { ll s,t; cin >> s >> t; x[i] = make_pair(s,i); y[i] = make_pair(t,i); } //argsortしないとだめ sort(x.begin(),x.end()); sort(y.begin(),y.end()); for (int i = 0; i < N-1; i++) { edge e1, e2; e1.u = x[i].second; e2.u = y[i].second; e1.v = x[i+1].second; e2.v = y[i+1].second; e1.cost = abs(x[i].first-x[i+1].first); e2.cost = abs(y[i].first-y[i+1].first); es[i] = e1; es[i+N-1] = e2; } V = N; E = 2 * N - 2; ll res = kruskal(); cout << res << endl; }
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s670929171
Runtime Error
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
""" ...(ggNMMMMMMMMMNg+... ..(gMH9"^` ?"YMa, ..gMY"! 7Mm. ` ..gM9^ (Ma.` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` .JM9^ ` ?Ma ..M#"` .h ..g ` ` TN, .d#^ (b ..+MY"! ` ?N. ` `..M" ` `..&M#"! UN ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` `.+#^ .b `..MY"! ,N ` ` ` M[ ` ` ` .J#^ WJ+#"` .gNe ` ` dF .M= ..gHN ..J#9= W/ ` JF J@ ."` d|.-"= .N. ` ` MF .dF ,N ..M#= ` ` ` .M` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` .MD Up ...k#M= ` ..` ` `.M^ dF ` ?"""! ,p ...gM9"` ` (#! .# .MgMD^ ` ` .M" d] ..H94#N-TWMNag+J......J+ggMWY .MD` M} .J9^ .M!,b ` `.+M" M] T"` .B` vb .(MD` ` ...JgMH""""""MNa,` -N. .Mt Up ..gM"' ` ..(gMH9"^` TN, ?N, .J@` W[ ..gM"! ` ..JH#""! .Hp .Wm, (! ,@ ..+MB= ` ..+MB"! .M[ .TNa, ., ...&MMY"^ `...g#"! ,N, .TWNg... ` ` ... .MMH9"=` .gWH9"! db _7T"HMMNHQQkMM9"`M. d\ ... .M, J] # ` ` ` ` ` ................ .......JggHMMM"""""` dN .N. .# ` .....JggHMMH""""""""""7"""""""""""HMMMNNg+-.... 7"""7?! .M[ -b .# ` ` ` ...gHM""""!` ?7"T"HMMNg+.... (N. vp M. ` ...(gMMMMNNggg+(.... _?""WMNNg... M\ ?bJ] ..gMY""!` `??""WMNJ, _7TWMNgJ.. ` ...JggHHNag-,. ` ,HN. ` .+M9^ _TMNJ, ?TWMNJ.. ` ` ..gM9"! ?"Ma, ` ,H\ .(MD! ?WNx. ?THNg.,..dB= .TN, .d#^ ?MN, Q, ?TMm. TN, ` .d#^ ..&MM; .TN, .W, .Mp ` ` .(M= ..gMB@! .WN, ?b Wb `.M" ... ` ` ?` M. ?Me ?b Mp .j#` ..&MH"79 db .Mb ?b ........ ,M, ` .MF ...gM#"4, .M, UN. ?b ` ?""HNgJ, JN .M$ (=` M[ ` ,M] .. TN. Tb TD M] dF Jb .(HY""! UN. Wb -N. .M` ,M, ` ,"^ Mb Mc M] ` dF -W:..gMM@ ` ,M. ,N. ""9Sa,. J# M] ` ..gM9"` .m M] H] ` ,M. M] ` T=` M_ db -N M) MF M) J# ,M. .aJ..... M] d@ ` ` M) J# .M_ ?7TBNgJ, M] J# ` .M+..(gx J# .M` ?^ M] ` ,M. ` ` _7?! dF .# ., M% M] ` MF JF .(M" .M! JN. ` ` .M} ` ..g#"` dF WN ` ` -# ` ..JMY"! .M` ` WN. ` ...&gM] MF ` ..gM9^ ,NJ, .M^ TN, ` ` ` ...JgMHB"=` `(# ` ..gMB"! ?TMMNggJ.........gM@` ?N, ` ` ..gMW""! .M! ..&MY"! `?7"""""7! ` ?N, ` ..&MB"` .dB` ` ..+MY"! (Ma. ..+MB"! `.MD ` ...gMB"! 7Ma. ` .=` .J#' ` `..JMH9"` ` ` ?HN, ` .uM= ..+MY"^ .TMg, .JM9! ` ...gM""! .TMN., .+M9' ..&M#"=` ` ` ` ?TMNg... .. ..gM"! ...gMY"=` ?"""HMMMMMMMY""=(.gMM9^ ...JkMB"^ .T"9"! ...JdM"""! ` ` ` .....JdT"""! ` ` ` ?!` """
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s533591656
Runtime Error
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
n = int(input()) p = [list(map(int, input().split())) for i in range(n)] # x,yだけのリストを作る。座標順にソートもします。 x = sorted([[p[i][0], i] for i in range(n)]) y = sorted([[p[i][1], i] for i in range(n)]) # x,yについて隣り合ったものだけをedgeとしてみればよい(これもソートします) edge = [0]*(2*n) for i in range(n): edge[2*i] = [abs(x[i][0] - x[i-1][0]), x[i][1], x[i-1][1]]) edge[2*i+1] = [abs(y[i][0] - y[i-1][0]), y[i][1], y[i-1][1]] edge.sort() # Union-Find group = [i for i in range(n)] def findParent(i): if i == group[i]: return i else: group[i] = findParent(group[i]) return group[i] def merge(i, j): i = findParent(i) j = findParent(j) group[i] = j # クラスカル法で最小全域木の重みを求めます ret = 0 for e in edge: weight, a, b = e if findParent(a) != findParent(b): merge(a, b) ret += weight print(ret)
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s455731450
Wrong Answer
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
s = input() l = [] p = s[0] seq = 1 for c in s[1:]: if c == p: seq += 1 else: l.append(seq) seq = 1 p = c l.append(seq) ans = float("inf") if len(l) >= 3: d1 = max([a + b for a, b in zip(l[0::2], l[1::2])]) d2 = max([a + b for a, b in zip(l[1::2], l[2::2])]) print(max(d1, d2)) else: if s[0] == "1": print(sum(l) - l[0]) else: print(l[0])
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s834773755
Wrong Answer
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
n = int(input()) cityx = [] cityy = [] for _ in range(n): x, y = input().split() cityx.append(int(x)) cityy.append(int(y)) done = [] money = 0 x = cityx[-1] y = cityy[-1] for i in range(n - 1): money += min([abs(cityx[i] - x), abs(cityy[i] - y)]) print(money)
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s885986132
Accepted
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
import sys sys.setrecursionlimit(4100000) import math import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) from collections import defaultdict # d = defaultdict(list) from itertools import combinations # comb = combinations(range(N), 2) from functools import reduce from collections import Counter class UnionFind: def __init__(self, n): self.N = n self.parent = list(range(n)) self.rank = [1 for _ in range(n)] def findRoot(self, i): if self.parent[i] == i: # 親が自分ならroot return i else: self.parent[i] = self.findRoot(self.parent[i]) # 親をrootに付け替える return self.parent[i] def unite(self, i, j): i_root = self.findRoot(i) j_root = self.findRoot(j) if i_root == j_root: return if self.rank[i_root] > self.rank[j_root]: # ランクが高い方を親にする。 self.parent[j_root] = i_root elif self.rank[i_root] == self.rank[j_root]: self.parent[j_root] = i_root self.rank[i_root] += 1 else: self.parent[i_root] = j_root return i def isSame(self, i, j): return self.findRoot(i) == self.findRoot(j) def setGroup(self, elements): reduce(self.unite, elements) def getElementCount(self): # 要素ごとにそれが属してる集合の要素数を取る roots = [self.findRoot(i) for i in range(self.N)] counts = Counter(roots) return [counts[r] for r in roots] def getRootCount(self): # ルートごとにそれが属してる集合の要素数を取る roots = [self.findRoot(i) for i in range(self.N)] counts = Counter(roots) return counts def resolve(): # S = [x for x in sys.stdin.readline().split()][0] # 文字列 一つ N = [int(x) for x in sys.stdin.readline().split()][0] # int 一つ # N, D = [int(x) for x in sys.stdin.readline().split()] # 複数int # h_list = [int(x) for x in sys.stdin.readline().split()] # 複数int # grid = [list(sys.stdin.readline().split()[0]) for _ in range(N)] # 文字列grid # v_list = [int(sys.stdin.readline().split()[0]) for _ in range(N)] grid = [ [int(x) for x in sys.stdin.readline().split()] + [i] for i in range(N) ] # int grid logger.debug("{}".format([])) edge_list = [] # x でソート grid = sorted(grid, key=lambda xy: xy[0]) for i in range(N - 1): xi, yi, vi = grid[i] xj, yj, vj = grid[i + 1] edge_list.append((min(abs(xi - xj), abs(yi - yj)), vi, vj)) # y でソート grid = sorted(grid, key=lambda xy: xy[1]) for i in range(N - 1): xi, yi, vi = grid[i] xj, yj, vj = grid[i + 1] edge_list.append((min(abs(xi - xj), abs(yi - yj)), vi, vj)) edge_list = sorted(edge_list) union_find = UnionFind(N) total_cost = 0 for edge in edge_list: cost, i, j = edge if not union_find.isSame(i, j): union_find.unite(i, j) total_cost += cost print(total_cost) if __name__ == "__main__": resolve() # AtCoder Unit Test で自動生成できる, 最後のunittest.main は消す # python -m unittest template/template.py で実行できる # pypy3 -m unittest template/template.py で実行できる import sys from io import StringIO import unittest class TestClass(unittest.TestCase): def assertIO(self, input, output): stdout, stdin = sys.stdout, sys.stdin sys.stdout, sys.stdin = StringIO(), StringIO(input) resolve() sys.stdout.seek(0) out = sys.stdout.read()[:-1] sys.stdout, sys.stdin = stdout, stdin self.assertEqual(out, output) def test_入力例_1(self): input = """3 1 5 3 9 7 8""" output = """3""" self.assertIO(input, output) def test_入力例_2(self): input = """6 8 3 4 9 12 19 18 1 13 5 7 6""" output = """8""" self.assertIO(input, output) def test_入力例_3(self): input = """2 0 0 0 0""" output = """0""" self.assertIO(input, output)
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s496211915
Accepted
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
import heapq N = int(input()) iXY = [[i] + list(map(int, input().split())) for i in range(N)] G = [set() for _ in range(N)] for k in [1, 2]: iXY.sort(key=lambda a: a[k]) for i in range(1, N): i0 = iXY[i - 1][0] i1 = iXY[i][0] G[i0].add((i1)) G[i1].add((i0)) Q = [(0, 0)] B = set() a = 0 iXY.sort() while True: d, v = heapq.heappop(Q) while v in B: d, v = heapq.heappop(Q) a += d B.add(v) if len(B) == N: break for i in G[v]: if i not in B: heapq.heappush( Q, (min(abs(iXY[v][1] - iXY[i][1]), abs(iXY[v][2] - iXY[i][2])), i) ) print(a)
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s744816662
Accepted
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
def solve_abc065d(): from collections import namedtuple from heapq import heappush, heappop from operator import attrgetter from itertools import tee import sys input = sys.stdin.readline City = namedtuple("City", "x y idx") Edge = namedtuple("Edge", "cost to") N = int(input()) cities = [] for city_idx in range(N): x, y = map(int, input().split()) c_ = City(x, y, city_idx) cities.append(c_) cities_x_asc = sorted(cities, key=attrgetter("x")) cities_y_asc = sorted(cities, key=attrgetter("y")) graph = tuple(set() for _ in range(N)) it_x = iter(cities_x_asc) gx1, gx2 = tee(it_x, 2) next(gx2) for c1, c2 in zip(gx1, gx2): d_ = c2.x - c1.x graph[c1.idx].add(Edge(d_, c2.idx)) graph[c2.idx].add(Edge(d_, c1.idx)) # x方向にN-1本の辺を張る it_y = iter(cities_y_asc) gy1, gy2 = tee(it_y, 2) next(gy2) for c1, c2 in zip(gy1, gy2): d_ = c2.y - c1.y graph[c1.idx].add(Edge(d_, c2.idx)) graph[c2.idx].add(Edge(d_, c1.idx)) # y方向にN-1本の辺を張る # <Prim’s Algorithm> # https://tjkendev.github.io/procon-library/python/graph/min_st_prim.html # プリム法では、グラフGの1頂点からなる木から始め、 # 木に含まれる頂点と木に含まれない頂点を繋ぐ辺のうち、 # 一番コストが小さい辺が繋ぐ(木に含まれない方の)頂点を木に追加する、 # ことを繰り返すことで最小全域木を求める。 # G[v] = [w, ...] # グラフG上で頂点vが隣接する辺集合 start = 0 # 起点とする頂点 used = [-1] * N used[start] = 1 h = [] for e_ in graph[start]: heappush(h, e_) mi = 0 while h: e_ = heappop(h) if ~used[e_.to]: continue used[e_.to] = 1 mi += e_.cost for ne_ in graph[e_.to]: if ~used[ne_.to]: continue heappush(h, ne_) # miが最小全域木の解 print(mi) return if __name__ == "__main__": solve_abc065d()
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s478794359
Wrong Answer
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
import heapq class Graph: def __init__(self, v, edgelist, w_v=None, directed=False): super().__init__() self.v = v self.w_e = [{} for _ in [0] * self.v] self.neighbor = [[] for _ in [0] * self.v] self.w_v = w_v self.directed = directed for i, j, w in edgelist: self.w_e[i][j] = w self.neighbor[i].append(j) def dijkstra(self, v_n): d = [float("inf")] * self.v d[v_n] = 0 prev = [-1] * self.v queue = [] for i, d_i in enumerate(d): heapq.heappush(queue, (d_i, i)) while len(queue) > 0: d_u, u = queue.pop() if d[u] < d_u: continue for v in self.neighbor[u]: alt = d[u] + self.w_e[u][v] if d[v] > alt: d[v] = alt prev[v] = u heapq.heappush(queue, (alt, v)) return d, prev def warshallFloyd(self): d = [[10**18] * self.v for _ in [0] * self.v] for i in range(self.v): d[i][i] = 0 for i in range(self.v): for j in self.neighbor[i]: d[i][j] = self.w_e[i][j] for i in range(self.v): for j in self.neighbor[i]: d[i][j] = self.w_e[i][j] for k in range(self.v): for i in range(self.v): for j in range(self.v): check = d[i][k] + d[k][j] if d[i][j] > check: d[i][j] = check return d def prim(self): gb = GraphBuilder(self.v, self.directed) queue = [] for i, w in self.w_e[0].items(): heapq.heappush(queue, (w, 0, i)) rest = [True] * self.v rest[0] = False while len(queue) > 0: w, i, j = heapq.heappop(queue) if rest[j]: gb.addEdge(i, j, w) rest[j] = False for k, w in self.w_e[j].items(): heapq.heappush(queue, (w, j, k)) return gb class Tree: def __init__(self, v, e): pass class GraphBuilder: def __init__(self, v, directed=False): self.v = v self.directed = directed self.edge = [] def addEdge(self, i, j, w=1): if not self.directed: self.edge.append((j, i, w)) self.edge.append((i, j, w)) def addEdges(self, edgelist, weight=True): if weight: if self.directed: for i, j, w in edgelist: self.edge.append((i, j, w)) else: for i, j, w in edgelist: self.edge.append((i, j, w)) self.edge.append((j, i, w)) else: if self.directed: for i, j, w in edgelist: self.edge.append((i, j, 1)) else: for i, j, w in edgelist: self.edge.append((i, j, 1)) self.edge.append((j, i, 1)) def addAdjMat(self, mat): for i, mat_i in enumerate(mat): for j, w in enumerate(mat_i): self.edge.append((i, j, w)) def buildTree(self): pass def buildGraph(self): return Graph(self.v, self.edge, directed=self.directed) def main(): n = int(input()) edge = [] for i in range(n): x, y = list(map(int, input().split())) edge.append((x, y, i)) xs = sorted(edge, key=lambda a: a[0]) ys = sorted(edge, key=lambda a: a[1]) edge = [] for i in range(n - 1): x1, y1, p1 = xs[i] x2, y2, p2 = xs[i + 1] edge.append((p1, p2, min(x2 - x1, y2 - y1))) x1, y1, p1 = ys[i] x2, y2, p2 = ys[i + 1] edge.append((p1, p2, y2 - y1)) gb = GraphBuilder(n) gb.addEdges(edge) mint = gb.buildGraph().prim() print(mint.edge) ans = 0 for a in mint.edge: ans += a[2] print(ans // 2) if __name__ == "__main__": main()
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s798438425
Wrong Answer
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
def cost(a, b, c, d): return min(abs(a - c), abs(b - d)) n = int(input()) xyi = [list(map(int, input().split())) + [x] for x in range(n)] a = [None for x in range(n)] class Node: def __init__(self, c, i, j): self.i = i self.j = j self.c = c def __lt__(self, a): return self.c < a.c field = [[Node(float("inf"), 0, 0)] for x in range(n)] import heapq for x, y, i in xyi: for j, f in enumerate(field[:i]): c = Node(cost(x, y, xyi[j][0], xyi[j][1]), i, j) heapq.heappush(field[j], c) heapq.heappush(field[i], c) nodes = [False for x in range(n)] r = [] for f in field: while True: try: n = heapq.heappop(f) except: break if not nodes[n.i]: r.append(n.c) nodes[n.i] = True break print(sum(filter(lambda x: x != float("inf"), r)))
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. * * *
s117717534
Accepted
p03682
Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N
def main(): import heapq from sys import stdin input = stdin.readline class unionfind: # size:要素数,tree:unionfind木 def __init__(self, size): # self,要素数 self.size = size self.tree = [[i, 1] for i in range(self.size)] # root,depth # rootを探す def root(self, index): if self.tree[index][0] == index: return index else: self.tree[index][0] = self.root(self.tree[index][0]) return self.tree[index][0] # 結合 def unite(self, index1, index2): r1 = self.root(index1) r2 = self.root(index2) if r1 != r2: d1, d2 = self.tree[r1][1], self.tree[r2][1] if d1 <= d2: self.tree[r1][0] = r2 self.tree[r2][1] = max(d1 + 1, d2) else: self.tree[r2][0] = r1 self.tree[r1][1] = max(d2 + 1, d1) # 同じか判定 def same(self, index1, index2): r1 = self.root(index1) r2 = self.root(index2) return r1 == r2 n = int(input()) xy = [list(map(int, input().split())) for _ in [0] * n] xyz = [xy[i] + [i] for i in range(n)] x_sort = sorted(xyz, key=lambda x: x[0]) y_sort = sorted(xyz, key=lambda x: x[1]) g = [] heapq.heapify(g) for i in range(n - 1): heapq.heappush( g, [abs(x_sort[i + 1][0] - x_sort[i][0]), x_sort[i][2], x_sort[i + 1][2]] ) for i in range(n - 1): heapq.heappush( g, [abs(y_sort[i + 1][1] - y_sort[i][1]), y_sort[i][2], y_sort[i + 1][2]] ) u = unionfind(n) cnt = 0 while g: d, i, j = heapq.heappop(g) if u.same(i, j) == False: cnt += d u.unite(i, j) print(cnt) main()
Statement There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?
[{"input": "3\n 1 5\n 3 9\n 7 8", "output": "3\n \n\nBuild a road between Towns 1 and 2, and another between Towns 2 and 3. The\ntotal cost is 2+1=3 yen.\n\n* * *"}, {"input": "6\n 8 3\n 4 9\n 12 19\n 18 1\n 13 5\n 7 6", "output": "8"}]
Print the minimum cost incurred before reaching the goal. * * *
s818702166
Accepted
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
import sys, re from collections import deque, defaultdict, Counter from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians from itertools import accumulate, permutations, combinations, product, groupby from operator import itemgetter, mul from copy import deepcopy from string import ascii_lowercase, ascii_uppercase, digits from bisect import bisect, bisect_left from fractions import gcd from heapq import heappush, heappop from functools import reduce def input(): return sys.stdin.readline().strip() def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(): return list(map(int, input().split())) def ZIP(n): return zip(*(MAP() for _ in range(n))) sys.setrecursionlimit(10**9) INF = float("inf") mod = 10**9 + 7 N, M, X = MAP() A = LIST() cost = [0] * (N + 1) for i in range(M): cost[A[i]] = 1 print(min(sum(cost[:X]), sum(cost[X:])))
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s876991479
Accepted
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time, copy, functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**15 mod = 10**9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): n, m, x = LI() t = LI() a = collections.defaultdict(int) for c in t: a[c] = 1 r = inf tr = 0 for i in range(x + 1, n): tr += a[i] r = tr tr = 0 for i in range(x - 1, -1, -1): tr += a[i] if r > tr: r = tr return r print(main())
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s664697466
Wrong Answer
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
a, b, c = map(int, input().split()) b = list(map(int, input().split())) i = c total = 0 total2 = 0 while True: i += 1 if i in b: total += 1 if i == a: break while True: i -= 1 if i in b: total2 += 1 if i == 0: break print(min(total, total2))
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s013826362
Runtime Error
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
#!/usr/bin/env python3 import sys def solve(N: int, M: int, X: int, A: "List[int]"): ans = 0 for i in range(X-1, 0, -1): if i in A: ans += 1 c = 0 for i in range(X+1, N): if i in A: c += 1 if ans > c: ans = c print(ans) return # Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template) def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() N = int(next(tokens)) # type: int M = int(next(tokens)) # type: int X = int(next(tokens)) # type: int A = [int(next(tokens)) for _ in range(M)] # type: "List[int]" solve(N, M, X, A) if __name__ == '__main__':
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s691664427
Runtime Error
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
N,M,X=map(int,input().split()) a = [int(input()) for in range(M)] count_low = 0 count_high = 0 for i in range(a): if a[i-1]<X: count_low +=1 for i in range(a): if a[i-1]>X: count_high +=1 print(min(count_low,count_high))
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s463367049
Wrong Answer
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
N, gate, start = list(map(int, input().split())) W = list(map(int, input().split())) le = 0 ri = 0 for i in range(start - 1, N): if i in W: ri += 1 for k in range(start - 1): if k in W: le += 1 print(min(ri, le))
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s129677687
Runtime Error
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
a,b,c=map(int,input().split()) d=list(map(int, input().split()) d.append(c) d.sort() print(min(d.index(c), len(d)-d.index(c)-1))
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s552804462
Runtime Error
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
import bisect from bisect_left N,M,X = [int(x) for x in input().split()] A = [int(x) for x in input().split()] b = bisect_left(A,X) print(min(b,N-1-B))
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s675028373
Runtime Error
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
n, m, x = map(int, input().split()) a = map(int, input().split()) print(min(sum([1 for i in a if i>x]),sum([1 for i in a if i<x]))
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s644044301
Accepted
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
N, M, X = (int(T) for T in input().split()) A = [int(T) for T in input().split()] Gate = [0] * (N + 1) for T in A: Gate[T] += 1 print(min(sum(Gate[:X]), sum(Gate[(X + 1) :])))
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]
Print the minimum cost incurred before reaching the goal. * * *
s617765985
Accepted
p03378
Input is given from Standard Input in the following format: N M X A_1 A_2 ... A_M
n, m, x = input().split() list01 = input().split() list02 = [int(a) for a in list01] b = sum(c > int(x) for c in list02) d = sum(e < int(x) for e in list02) print(min(b, d))
Statement There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right. Initially, you are in Square X. You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N. However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1. It is guaranteed that there is no toll gate in Square 0, Square X and Square N. Find the minimum cost incurred before reaching the goal.
[{"input": "5 3 3\n 1 2 4", "output": "1\n \n\nThe optimal solution is as follows:\n\n * First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.\n * Then, travel from Square 4 to Square 5. This time, no cost is incurred.\n * Now, we are in Square 5 and we have reached the goal.\n\nIn this case, the total cost incurred is 1.\n\n* * *"}, {"input": "7 3 2\n 4 5 6", "output": "0\n \n\nWe may be able to reach the goal at no cost.\n\n* * *"}, {"input": "10 7 5\n 1 2 3 4 6 8 9", "output": "3"}]