AGC009 A - Multiple Array
備忘録
問題
回答
import sys, os, math, bisect, itertools, collections, heapq, queue # from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall from decimal import Decimal from collections import defaultdict, deque # import fractions sys.setrecursionlimit(10000000) ii = lambda: int(sys.stdin.buffer.readline().rstrip()) il = lambda: list(map(int, sys.stdin.buffer.readline().split())) fl = lambda: list(map(float, sys.stdin.buffer.readline().split())) iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)] iss = lambda: sys.stdin.buffer.readline().decode().rstrip() sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split())) isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)] lcm = lambda x, y: (x * y) // math.gcd(x, y) # lcm = lambda x, y: (x * y) // fractions.gcd(x, y) MOD = 10 ** 9 + 7 MAX = float('inf') def main(): if os.getenv("LOCAL"): sys.stdin = open("input.txt", "r") N = ii() A, B = [], [] for n in range(N): a, b = il() A.append(a) B.append(b) ret = 0 for n in reversed(range(N)): if (A[n] + ret) % B[n] == 0: continue else: ret += B[n] - ((A[n] + ret) % B[n]) print(ret) if __name__ == '__main__': main()
考え方
N
個の数列をN
番目から降順(N番目, N-1番目, ... , 2番目, 1番目)に、
貪欲法でボタンの押す回数を求める。
N
個の数列に対して、1番目の項を増加させるためには、
1番目のボタンを使用してもいいし、2番目のボタンでも、N-1番目のボタンでも、N番目のボタンでもよい。
しかし、N番目の項を増加させるためには、N番目のボタンを使用する以外に選択肢が存在しない。
そのため、N番目からボタンの押す回数を求め、
その増加分を下(N-1番目、N-2番目、 .... 、2番目、1番目)に伝播させていく。
なお、数列A
は数列B
の倍数となるので、
ボタンを押すために必要な回数は、Aのi項目の値 + 既に押したボタンの回数 % Bのi項目の値
で余りを求め、Bのi項目の値 - 余り
から求めることが出来る。