Open5

競プロ「初中級者が解くべき過去問精選 100 問」 全探索:全列挙

ドリクロドリクロ

01. ITP1_7_B - How Many Ways?

main.py
import sys
import itertools

def main():
    read = sys.stdin.read
    input_data = [int(x) for x in read().rstrip().split()]
    N = input_data[0::2]
    X = input_data[1::2]
    N.pop()
    X.pop()
    for n, x in zip(N, X):
        n_list = range(1, n+1)
        result = 0
        for i, j, k in list(itertools.combinations(n_list, 3)):
            r = i + j + k
            if r == x:
                result += 1
        print(result)

if __name__ == '__main__':
    main()

00:48 sec 18408 KB 478 bytes

実行結果

ドリクロドリクロ

02. AtCoder Beginner Contest 106 B - 105

main.py
#!/usr/bin/env python3

import sys

def make_divisors(n):
    lower_divisors, upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

def cal_divisors(n_list):
    result = 0
    for n in n_list:
        r = len(make_divisors(n))
        if r == 8:
            result += 1
    return result

def main():
    N = int(sys.stdin.readline().rstrip())
    n_list = list(range(1, N+1, 2))
    result = cal_divisors(n_list)
    print(result)

if __name__ == '__main__':
    main()

実行結果

https://qiita.com/LorseKudos/items/9eb560494862c8b4eb56

ドリクロドリクロ

04. パ研杯2019 C - カラオケ

main.py
#!/usr/bin/env python3

import sys
import itertools

def main():
    N, M = [int(x) for x in sys.stdin.readline().rstrip().split()]
    read = sys.stdin.read
    A = [list(map(int, sys.stdin.readline().rstrip().split())) for _ in range(N)]
    result = 0
    for a1, a2 in list(itertools.combinations(range(M), 2)):
        r = 0
        for i in range(N):
            if A[i][a1] > A[i][a2]:
                r += A[i][a1]
            elif A[i][a1] < A[i][a2]:
                r += A[i][a2]
            else:
                r += A[i][a1]
        if result < r:
            result = r
    print(result)

if __name__ == '__main__':
    main()

実行結果