LoginSignup
0
0

More than 3 years have passed since last update.

C - Modulo Summation, D - Flipping Signs

Last updated at Posted at 2021-02-28

C - Modulo Summation

O(N)
最小公倍数を計算。
その後、最小公倍数-1の値で余りを取得し加算していきます。

python
import math
import heapq
import itertools
from functools import reduce

def my_lcm_base(x, y):
    return (x * y) // math.gcd(x, y)

# main
def main():
    N = int(input())
    A = list(map(int, input().split()))

    g = reduce(my_lcm_base, A, 1)
    g = g - 1
    res=0
    for i in range(0, len(A)):
        res += g % A[i]

    print(res)

# エントリポイント
if __name__ == '__main__':
    main()

D - Flipping Signs

O(N)
i, i+1に-1をかけていくのを繰り返す。
最終的に奇数なら−符号が一つ存在、偶数なら全て+符号になります。

偶数なら全てを正整数に変更して全ての整数の合計を出力。

奇数なら全てを正整数に変更して最小値を取得。
全ての整数-(最小値*2)を計算。
正整数にした際の最小値を負数に変更して、全ての整数の合計を出力。

python
import math
import heapq
import itertools
from functools import reduce

def my_lcm_base(x, y):
    return (x * y) // math.gcd(x, y)

# main
def main():
    N = int(input())
    A = list(map(int, input().split()))

    cnt=0
    for i in range(0, len(A)):
        if A[i]<0:
            cnt+=1

    min_v=10000000000
    for i in range(0, len(A)):
        if A[i]<0:
            A[i] = A[i] * -1
        min_v = min(min_v, A[i])

    if cnt%2==0:
        print(sum(A))
    else:
        print(sum(A)-(min_v*2))

# エントリポイント
if __name__ == '__main__':
    main()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0