Problem:


Score : 300 points

Problem Statement

Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).

Consider a sequence A satisfying the following conditions:

A is a sequence of N positive integers.

1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.

Let us define a score of this sequence as follows:

The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)

Find the maximum possible score of A.

Constraints

All values in input are integers.

2 ≤ N ≤ 10

1 \leq M \leq 10

1 \leq Q \leq 50

1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )

0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )

(a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)

1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )

Input

Input is given from Standard Input in the following format:

N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q

Output

Print the maximum possible score of A.

Sample Input 1

3 4 3
1 3 3 100
1 2 2 10
2 3 2 10

Sample Output 1

110

When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110.

Sample Input 2

4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328

Sample Output 2

357500

Sample Input 3

10 10 1
1 10 9 1

Sample Output 3

1



Sample input:
3 4 3
1 3 3 100
1 2 2 10
2 3 2 10


Sample output:
110

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement

N, M, Q = map(int, input().split())
abcdn = [tuple(map(int, input().split())) for _ in range(Q)]

mx = 0
for AN in combinations_with_replacement(range(1, M+1), N):
	score = 0
	for a, b, c, d in abcdn:
		score += d if AN[b-1] - AN[a-1] == c else 0
	mx = max(score, mx)
print(mx)

Submission status: Accepted

Solution code:
def solve(A, nNow, n, m, q, a, b, c, d):
    if nNow == n:
        ret = 0
        for i in range(q):
            if A[b[i] - 1] - A[a[i] - 1] == c[i]:
                ret += d[i]
        return ret
    elif nNow == 0:
        ret = 0
        for i in range(1, m + 1):
            ret = max(ret, solve(A + [i], nNow + 1, n, m, q, a, b, c, d))
        return ret
    else:
        ret = 0
        for i in range(A[nNow - 1], m + 1):
            ret = max(ret, solve(A + [i], nNow + 1, n, m, q, a, b, c, d))
        return ret


def main():
    n, m, q = map(int, input().split())
    a, b, c, d = [[], [], [], []]
    for _ in range(q):
        ai, bi, ci, di = map(int, input().split())
        a.append(ai)
        b.append(bi)
        c.append(ci)
        d.append(di)
    print(solve([], 0, n, m, q, a, b, c, d))

    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

N, M, Q = map(int, input().split())

query = [list(map(int, input().split())) for _ in range(Q)]

rlt = 0

stc = deque([])
for i in range(1,M+1):
  stc.append([0,i])

while stc:
  lst = stc.pop()
  if len(lst) == N+1:
    now = 0
    for a,b,c,d in query:
      if lst[b] - lst[a] == c:
        now += d
    rlt = max(rlt, now)
  else:
    for j in range(lst[-1],M+1):
      tmp = lst + [j]
      stc.append(tmp)

print(rlt)

Submission status: Accepted

Solution code:
import itertools

N, M, Q = map(int, input().split(' '))

q_list = []

for i in range(Q):
    q_list.append(list(map(int, input().split(' '))))


def check(target, point, i):

    if len(q_list) == i:
        return point

    a = q_list[i][0]
    b = q_list[i][1]
    c = q_list[i][2]
    d = q_list[i][3]

    if target[b - 1] - target[a - 1] == c:
        point = check(target, point + d, i + 1)

    else:
        point = check(target, point, i + 1)

    return point


a_list = list(itertools.combinations_with_replacement(range(1, M+1), N))

result = max([check(target, 0, 0) for target in a_list])
print(result)

Submission status: Accepted

Solution code:
n,m,q=map(int,input().split())
A=[]
B=[]
C=[]
D=[]

for i in range(q):
  a,b,c,d=map(int,input().split())
  A.append(a)
  B.append(b)
  C.append(c)
  D.append(d)

ans=0
#print(A)
#print(B)
#print(C)
#print(D)

#mCn
def dfs(l):
  global ans # UnboundLocalError: local variable 'ans' referenced before assignment
  if len(l)==n+1:
    #print(l)
    tmp=0
    for i in range(q):
      #print(l[B[i]],l[A[i]],C[i])
      if l[B[i]]-l[A[i]]==C[i]:
        tmp+=D[i]
    ans=max(ans,tmp)
    return
  x=l[len(l)-1]
  while x<=m:
    y=l[:]
    y.append(x)
    dfs(y)
    x+=1

dfs([1])
print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement
CList = []
N, M, Q = map(int, input().split())
for i in range(1, M+1):
    CList.append(i)
Qtotal = []
x = 0
ans = 0

CList=list(combinations_with_replacement(CList, N))

a, b, c, d = map(int, input().split())
for i in CList:
    if CList[x][b-1]-CList[x][a-1] == c:
        Qtotal.append(d)
    else:
        Qtotal.append(0)
    x = x+1
x=0
for i in range(Q-1):
    a, b, c, d = map(int, input().split())
    for j in CList:
        if CList[x][b-1]-CList[x][a-1] == c:
            Qtotal[x] = Qtotal[x]+d
        x = x+1
    x=0

ans=max(Qtotal)
print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.read
readline = sys.stdin.buffer.readline
from itertools import combinations_with_replacement
INF = float('inf')

def main():
    N, M, Q = map(int, readline().split())
    abcd = []

    for _ in range(Q):
        a,b,c,d = map(int, readline().split())
        abcd.append([a,b,c,d])

    As = combinations_with_replacement(range(1,M+1),N)
    ans = 0

    for A in As:
        score = 0
        for a,b,c,d in abcd:
            if A[b-1] - A[a-1] == c:
                score += d

        ans = max(ans, score)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import copy
from collections import deque
n, m, q = list(map(int, input().split()))

abcd = []
for _ in range(q):
    abcd.append(list(map(int, input().split())))

ans = 0
def dfs(A, low, high, n):
    global ans
    if len(A) >= n:
        result = 0
        for a,b,c,d in abcd:

            if A[b-1]-A[a-1] == c:
                result += d
        ans = max(ans, result)
        return

    for i in range(low, high+1):
        A.append(i)
        dfs(A, i, high, n)
        A.pop()

dfs([], 1, m, n)
print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement

def main():
    N, M, Q = map(int, input().split())
    qs = [list(map(int,input().split())) for _ in range(Q)]
    seq = [i for i in range(1,M+1)]
    C = combinations_with_replacement(seq, N)
    max_score = 0

    for A in C:
        A = sorted(A)
        score = 0
        for q in qs:
            if A[q[1]-1] - A[q[0]-1] == q[2]:
                score += q[3]
        max_score = max(score, max_score)
    print(max_score)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.read
readline = sys.stdin.buffer.readline
from itertools import combinations_with_replacement
INF = float('inf')

def main():
    N, M, Q = map(int, readline().split())
    abcd = []

    for _ in range(Q):
        a,b,c,d = map(int, readline().split())
        abcd.append([a,b,c,d])

    As = combinations_with_replacement(range(1,M+1),N)
    ans = 0

    for A in As:
        score = 0
        for a,b,c,d in abcd:
            if A[b-1] - A[a-1] == c:
                score += d

        ans = max(ans, score)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque
import numpy as np
import math
sys.setrecursionlimit(10**6)
def S(): return sys.stdin.readline().rstrip()
def SL(): return map(str,sys.stdin.readline().rstrip().split())
def I(): return int(sys.stdin.readline().rstrip())
def IL(): return map(int,sys.stdin.readline().rstrip().split())

ans = 0
def dfs(l,n,m,e):
    if len(l)==n:
        tmp = 0
        for aa,bb,cc,dd in zip(e[0],e[1],e[2],e[3]):
            if l[bb]-l[aa]==cc:
                tmp += dd
        global ans
        ans = max(ans,tmp)
        return
    x = l[-1] if len(l) else 0
    for i in range(x,m):
        dfs(l+[i],n,m,e)

def Main():
    n,m,q = IL()
    a,b,c,d = [0]*q,[0]*q,[0]*q,[0]*q
    for i in range(q):
        a[i],b[i],c[i],d[i] = IL()
        a[i] -= 1
        b[i] -= 1
    e = [a,b,c,d]
    dfs([],n,m,e)
    print(ans)
    return

if __name__=='__main__':
    Main()

Submission status: Accepted

Solution code:
N, M, Q = map(int, input().split())
a = [0] * Q
b = [0] * Q
c = [0] * Q
d = [0] * Q
for i in range(Q):
    a[i], b[i], c[i], d[i] = map(int, input().split())
    a[i] -= 1
    b[i] -= 1


def score(A):
    tmp = 0
    for ai, bi, ci, di in zip(a, b, c, d):
        if A[bi] - A[ai] == ci:
            tmp += di
    return tmp


def dfs(A):
    if len(A) == N:
        return score(A)
    res = 0
    prev_last = A[-1] if len(A) > 0 else 0
    for v in range(prev_last, M):
        A.append(v)
        res = max(res, dfs(A))
        A.pop()
    return res

print(dfs([]))

Submission status: Accepted

Solution code:
import itertools
N, M, Q = map(int, input().split())

a = []
b = []
c = []
d = []

for _ in range(Q):
    ai, bi, ci, di = map(int, input().split())
    a.append(ai)
    b.append(bi)
    c.append(ci)
    d.append(di)


ans = 0

nums = range(1, M+1)


for A in itertools.combinations_with_replacement(nums, N):
    s = 0

    # print(A[0])
    for i in range(Q):
        ai = a[i]-1
        bi = b[i]-1
        ci = c[i]
        di = d[i]
        if A[bi]-A[ai] == ci:

            s += di

    ans = max(ans, s)

print(ans)

Submission status: Accepted

Solution code:
import math
import sys
from collections import deque
import heapq
import copy
import itertools
from itertools import permutations
from itertools import combinations
import bisect
def mi() : return map(int,sys.stdin.readline().split())
def ii() : return int(sys.stdin.readline().rstrip())
def i() : return sys.stdin.readline().rstrip()
a,b,c=mi()
l=[list(mi()) for i in range(c)]
x=list(itertools.combinations_with_replacement(range(1,b+1),a))
ans=0
for j in x:
  c=0
  for i in l:
    if j[i[1]-1]-j[i[0]-1]==i[2]:
      c+=i[3]
  if c>ans:
    ans=c
print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement
n,m,q = map(int, input().split())
abcd = [list(map(int, input().split())) for _ in range(q)]

ans = 0
for i in combinations_with_replacement(range(1,m+1),n):
  t = 0
  for j in abcd:
    if i[j[1]-1] - i[j[0]-1] == j[2]:
      t += j[3]
  ans = max(ans, t)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque


# 数列の点数を計算する関数
def calc(seq):
    score = 0
    for a, b, c, d in req:
        if seq[b - 1] - seq[a - 1] == c:
            score += d

    return score


n, m, q = list(map(int, input().split()))
req = [list(map(int, input().split())) for _ in range(q)]

ans = 0

que = deque()

# 数列の1番目、[1]～[m]までキューに追加しますが、
# 実は、この問題は数列の最初が[1]の場合だけを考えても解けます。
for i in range(1, m + 1):
    que.append([i])

while que:
    seq = que.popleft()

    if len(seq) == n:
        # 長さがnになったので、得点を計算します
        score = calc(seq)
        ans = max(ans, score)
    else:
        # 次に追加する数字は、下限が今の数列の一番後ろの数字、上限がmです
        for i in range(seq[-1], m + 1):
            seq_next = seq + [i]
            que.append(seq_next)

print(ans)

Submission status: Accepted

Solution code:
import itertools
N, M, Q = map(int, input().split())
a = [0]*Q
b = [0]*Q
c = [0]*Q
d = [0]*Q
for i in range(Q):
     a[i], b[i], c[i], d[i] = map(int, input().split())
ans = 0
for A in itertools.combinations_with_replacement(range(1, M+1), N):
    tmp = 0
    for i in range(Q):
        if A[b[i]-1] - A[a[i]-1] == c[i]:
            tmp += d[i]
    ans = max(ans, tmp)
print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement
n, m, q = map(int, input().split())
abcd = [list(map(int, input().split())) for i in range(q)]
ans = 0
for A in combinations_with_replacement(range(1, m+1), n):
  t = 0
  for a, b, c, d in abcd:
    if A[b- 1] - A[a -1] == c:
      t += d
  ans = max(ans, t)
print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement
N,M,Q = map(int,input().split())
li = [list(map(int,input().split())) for i in range(Q) ]
counter = []
for comb in combinations_with_replacement(range(1,M+1),N):
    A = list(comb)
    tmp = 0
    for i in li:
        if A[i[1]-1] - A[i[0]-1] == i[2]:
            tmp += i[3]
    counter.append(tmp)
print(max(counter))

Submission status: Accepted

Solution code:
N, M, Q = list(map(int, input().split()))
abcd = []
for _ in range(Q):
    abcd.append(list(map(int, input().split())))


def get_array(array, index, remain):
    if index == N - 2:
        tmp_array = array.copy()
        tmp_array[index] = remain
        resp = []
        for i in range(remain + 1):
            tmp_array = array.copy()
            tmp_array[index] = i
            resp_array = [1]*N
            for j in range(N-1):
                resp_array[j+1] = resp_array[j] + tmp_array[j]
            resp.append(resp_array)
        return resp
    else:
        resp = []
        for i in range(remain + 1):
            tmp_array = array.copy()
            tmp_array[index] = i
            resp += get_array(tmp_array, index + 1, remain - i)
        return resp


diff_array = [0] * (N - 1)
possible = get_array(diff_array, 0, M - 1)
max_point = 0
for pos in possible:
    point = 0
    for a, b, c, d in abcd:
        if pos[b-1] - pos[a-1] == c:
            point += d
    if point > max_point:
        max_point = point
print(max_point)

Submission status: Accepted

Solution code:
import itertools

n, m, q = map(int, input().split())
abcd = [list(map(int, input().split())) for _ in range(q)]

x = [i + 1 for i in range(m)]
A = itertools.combinations_with_replacement(x, n)

ans = 0
for i in A:
    score = 0
    for j in abcd:
        if i[j[1] - 1] - i[j[0] - 1] == j[2]:
            score += j[3]
    ans = max(ans, score)
print(ans)

Submission status: Accepted

Solution code:
import itertools

N, M, Q = map(int, input().split())
abcd = []
for i in range(Q):
    abcd += [list(map(int, input().split()))]

A = list(itertools.combinations_with_replacement(list(range(1,M+1)), N))
smax = 0
for i in range(len(A)):
    s = 0
    for j in range(Q):
        if A[i][abcd[j][1]-1]-A[i][abcd[j][0]-1] == abcd[j][2]:
            s += abcd[j][3]
    
    if s > smax:
        smax = s

print(smax)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np
# from numpy import cumsum  # accumulate

def solve():
    N, M, Q = MI()
    E = [[] for _ in range(Q)]
    for i in range(Q):
        a, b, c, d = MI()
        E[i] = [a, b, c, d]

    q = deque([
        [1]
    ])
    ans = 0
    while q:
        # print(q)
        A = q.popleft()
        if len(A) == N+1:
            res = 0
            for (a, b, c, d) in E:
                if A[b] - A[a] == c:
                    res += d
            ans = max(ans, res)
            continue

        A.append(A[-1])
        while A[-1] <= M:
            q.appendleft(A.copy())
            A[-1] += 1

    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np
# from numpy import cumsum  # accumulate

N, M, Q = MI()
E = [[] for _ in range(Q)]
for i in range(Q):
    a, b, c, d = MI()
    E[i] = [a, b, c, d]
ans = 0
def dfs(A):
    global ans
    if len(A) == N + 1:
        res = 0
        for (a, b, c, d) in E:
            if A[b] - A[a] == c:
                res += d
        # print(A)
        ans = max(ans, res)
        return

    A.append(A[-1])
    while A[-1] <= M:
        dfs(A.copy())
        A[-1] += 1

def solve():

    dfs([1])
    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np
# from numpy import cumsum  # accumulate

def solve():
    N, M, Q = MI()
    E = [[] for _ in range(Q)]
    for i in range(Q):
        a, b, c, d = MI()
        a -= 1
        b -= 1
        E[i] = [a, b, c, d]

    ans = 0
    for A in comb_w(range(1, M+1), N):
        res = 0
        for (a, b, c, d) in E:
            if A[b] - A[a] == c:
                res += d
        ans = max(ans, res)
    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
import decimal


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [Scanner.string() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [Scanner.int() for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        res = []
        i = 1
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                res.append(i)
                if i != n // i:
                    res.append(n // i)
        return res

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True

    @staticmethod
    def fact(N):
        res = {}
        tmp = N
        for i in range(2, int(N ** 0.5 + 1) + 1):
            cnt = 0
            while tmp % i == 0:
                cnt += 1
                tmp //= i
            if cnt > 0:
                res[i] = cnt
        if tmp != 1:
            res[tmp] = 1
        if res == {}:
            res[N] = 1
        return res


def pop_count(x):
    x = x - ((x >> 1) & 0x5555555555555555)
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    x = x + (x >> 32)
    return x & 0x0000007f


MOD = int(1e09) + 7
INF = int(1e15)

N = None
M = None
Q = None
L = None
ans = 0


def func(A):
    global ans
    if len(A) == N:
        point = 0
        for d in L:
            if A[d[1] - 1] - A[d[0] - 1] == d[2]:
                point += d[3]
        ans = max(ans, point)
        return
    for i in range(A[-1], M + 1):
        func(A + [i])


def solve():
    global N, M, Q, L
    N, M, Q = Scanner.map_int()
    L = Scanner.int_list_list(Q)
    for i in range(1, M + 1):
        func([i])
    print(ans)


def main():
    # sys.stdin = open("sample.txt")
    # T = Scanner.int()
    # for _ in range(T):
    #     solve()
    # print('YNeos'[not solve()::2])
    solve()


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,m,q=map(int,input().split())
e=[list(map(int,input().split())) for i in range(q)]
a=[1]*n
now=0
while(True):
  tp=0
  for i in range(q):
    if(a[e[i][1]-1]-a[e[i][0]-1]==e[i][2]):
      tp+=e[i][3]
  if(tp>now):
    now=tp
    
  a[n-1]+=1
  for i in range(n-1):
    if(a[n-1-i]==m+1):
      a[n-2-i]+=1
  for i in range(n-1):
    if(a[i+1]==m+1):
      a[i+1]=a[i]
  if(a[0]==m+1):
    break

print(now)

Submission status: Accepted

Solution code:
N,M,Q = map(int,input().split())

li = [list(map(int,input().split())) for i in range(Q) ]

from itertools import combinations_with_replacement
counter = []

for comb in combinations_with_replacement(range(1,M+1),N):
    A = list(comb)
    tmp = 0
   
    for i in li:
        if A[i[1]-1] - A[i[0]-1] == i[2]:
            tmp += i[3]

    counter.append(tmp)


print(max(counter))

Submission status: Accepted

Solution code:
import itertools

N,M,Q = map(int,input().split())

# nullで初期化
abcd = [None] * Q
for i in range(Q):
  abcd[i] = list(map(int,input().split()))

ans = 0
# itertools.combinations_with_replacement(イテラブル,組み合わせの数)
for list in list(map(list, itertools.combinations_with_replacement(range(1,M+1), N))):
  num = 0
  for x in abcd:
    if list[x[1]-1] - list[x[0]-1] == x[2]:
      num += x[3]
  ans = max(ans,num)
print(ans)

Submission status: Accepted

Solution code:
import itertools

N,M,Q = map(int,input().split())

# nullで初期化
abcd = [None] * Q
for i in range(Q):
  abcd[i] = list(map(int,input().split()))

ans = 0
# itertools.combinations_with_replacement(リスト,取り出す数)で順列の組み合わせを出力
for list in list(map(list, itertools.combinations_with_replacement(range(1,M+1), N))):
  num = 0
  for x in abcd:
    if list[x[1]-1] - list[x[0]-1] == x[2]:
      num += x[3]
  ans = max(ans,num)
print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement


def main():
    N, M, Q = map(int, input().split())
    Qs = [list(map(int, input().split())) for _ in range(Q)]
    seq = [i for i in range(1, M+1)]
    As = combinations_with_replacement(seq, N)
    max_score = 0
    for A in As:
        A = sorted(A)
        score = 0
        for q in Qs:
            if A[q[1]-1] - A[q[0]-1] == q[2]:
                score += q[3]
        max_score = max(score, max_score)

    print(max_score)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

import glob

# 問題ごとのディレクトリのトップからの相対パス
REL_PATH = 'ABC\\165\\C'

# テスト用ファイル置き場のトップ
TOP_PATH = 'C:\\AtCoder'

class Common:

    problem = []
    index = 0

    def __init__(self, rel_path):
        self.rel_path = rel_path

    def initialize(self, path):
        file = open(path)
        self.problem = file.readlines()
        self.index = 0
        return

    def input_data(self):
        try:
            IS_TEST
            self.index += 1
            return self.problem[self.index-1]

        except NameError:
            return input()

    def resolve(self):
        pass

    def exec_resolve(self):
        try:
            IS_TEST
            for path in glob.glob(TOP_PATH + '\\' + self.rel_path + '/*.txt'):
                print("Test: " + path)
                self.initialize(path)
                self.resolve()
                print("\n\n")
        except NameError:
            self.resolve()


class C(Common):

    def rec(self, A, now_index):

        point1 = 0
        point2 = 0
        if now_index == self.N-1:
            for i in self.abcd:
                if A[i[1]-1] - A[i[0]-1] == i[2]:
                    point1 += i[3]

        else:
            for i in range(A[now_index], self.M+1):
                A[now_index+1] = i
                tmp = self.rec(A, now_index+1)
                if tmp > point2:
                    point2 = tmp

        if point1 > point2:
            return point1
        return point2

    def resolve(self):

        self.N, self.M, self.Q = map(int, self.input_data().split())
        self.abcd = []

        for i in range(self.Q):
            self.abcd.append(list(map(int, self.input_data().split())))

        A = [0]*self.N
        A[0] = 1

        point = self.rec(A, 0)
        print(str(point))

solver = C(REL_PATH)
solver.exec_resolve()

Submission status: Accepted

Solution code:
from sys import stdin
import itertools
import numpy as np
from numba import njit

def main():
#入力
    readline=stdin.readline
    N,M,Q=map(int,readline().split())
    a=np.zeros(Q,dtype=np.int64)
    b=np.zeros(Q,dtype=np.int64)
    c=np.zeros(Q,dtype=np.int64)
    d=np.zeros(Q,dtype=np.int64)
    for i in range(Q):
        a[i],b[i],c[i],d[i]=map(int,readline().split())

    arrays=np.array(list(itertools.combinations_with_replacement(range(1,M+1),N)),dtype=np.int64)
    l=len(arrays)

    print(f(l,Q,a,b,c,d,arrays))
    
@njit("i8(i8,i8,i8[:],i8[:],i8[:],i8[:],i8[:,:])",cache=True)
def f(l,Q,a,b,c,d,arrays):
    max_res=0
    for i in range(l):
        res=0
        for j in range(Q):
            if arrays[i][b[j]-1]-arrays[i][a[j]-1]==c[j]:
                res+=d[j]
        max_res=max(max_res,res)
    return max_res

if __name__=="__main__":
	main()

Submission status: Accepted

Solution code:
from sys import stdin
import itertools
import numpy as np
from numba import njit

@njit("i8(i8,i8,i8[:],i8[:],i8[:],i8[:],i8[:,:])",cache=True)
def f(l,Q,a,b,c,d,arrays):
    max_res=0
    for i in range(l):
        res=0
        for j in range(Q):
            if arrays[i][b[j]-1]-arrays[i][a[j]-1]==c[j]:
                res+=d[j]
        max_res=max(max_res,res)
    return max_res
  
def main():
#入力
    readline=stdin.readline
    N,M,Q=map(int,readline().split())
    a=np.zeros(Q,dtype=np.int64)
    b=np.zeros(Q,dtype=np.int64)
    c=np.zeros(Q,dtype=np.int64)
    d=np.zeros(Q,dtype=np.int64)
    for i in range(Q):
        a[i],b[i],c[i],d[i]=map(int,readline().split())

    arrays=np.array(list(itertools.combinations_with_replacement(range(1,M+1),N)),dtype=np.int64)
    l=len(arrays)

    print(f(l,Q,a,b,c,d,arrays))
    
if __name__=="__main__":
	main()

Submission status: Accepted

Solution code:
from sys import stdin
import itertools
import numpy as np
from numba import njit

@njit(cache=True)
def f():
    max_res=0
    for i in range(l):
        res=0
        for j in range(Q):
            if arrays[i][b[j]-1]-arrays[i][a[j]-1]==c[j]:
                res+=d[j]
        max_res=max(max_res,res)
    return max_res

#入力
readline=stdin.readline
N,M,Q=map(int,readline().split())
a=np.zeros(Q,dtype=np.int64)
b=np.zeros(Q,dtype=np.int64)
c=np.zeros(Q,dtype=np.int64)
d=np.zeros(Q,dtype=np.int64)
for i in range(Q):
    a[i],b[i],c[i],d[i]=map(int,readline().split())

arrays=np.array(list(itertools.combinations_with_replacement(range(1,M+1),N)),dtype=np.int64)
l=len(arrays)

print(f())

Submission status: Accepted

Solution code:
import itertools
n, m, q = list(map(int, input().split()))
a = []
b = []
c = []
d = []
for i in range(q):
    a_, b_, c_, d_ = list(map(int, input().split()))
    a.append(a_)
    b.append(b_)
    c.append(c_)
    d.append(d_)

A = range(1, m+1)
lis = list(itertools.combinations_with_replacement(A, n))

ans = 0
for each in lis:
    tmp = 0
    for i in range(len(a)):
        if each[b[i]-1] - each[a[i]-1] == c[i]:
            tmp += d[i]

    ans = max(ans, tmp)

print(ans)

Submission status: Accepted

Solution code:
N,M,Q=map(int,input().split())
L=[]
for i in range(Q):
  L.append(list(map(int,input().split())))
  L[i][0]-=1
  L[i][1]-=1
#print(L)
import itertools
R=list(range(1,M+1))#ここで変数Lを使っていた
A=list(itertools.combinations_with_replacement(R,N))
ans=0
#print(L)変数を上書きしていた！！！！！
for i in A:
  tmp=0  
  for a,b,c,d in L:
    if (i[b]-i[a])==c:
      tmp+=d
  ans=max(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement
N,M,Q=map(int,input().split())
L=[]
for i in range(Q):
  LI=list(map(int,input().split()))
  L.append(LI)
  L[i][0]-=1
  L[i][1]-=1
R=range(1,M+1)
V=list(combinations_with_replacement(R,N))
ans=0
for arr in V:
  tmp=0
  for a,b,c,d in L:
    if arr[b]-arr[a]==c:
      tmp+=d
  ans=max(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
N,M,Q=map(int,input().split())
L = []
for i in range(Q):
  L.append(list(map(int, input().split())))
  L[i][0]-=1
  L[i][1]-=1
 
import itertools
l =list(range(1,M+1))
v=list(itertools.combinations_with_replacement(l,N))
ans=0
for arr in v:
  score=0
  for a,b,c,d in L:
    if (arr[b] - arr[a])==c:      
      score+=d
  ans=max(ans,score)
print(ans)

Submission status: Accepted

Solution code:
N,M,Q=map(int,input().split())
L = []
for i in range(Q):
  L.append(list(map(int, input().split())))
  L[i][0]-=1
  L[i][1]-=1

import itertools
l =list(range(1,M+1))
v=list(itertools.combinations_with_replacement(l,N))
ans=0
for arr in v:
  score=0
  for a,b,c,d in L:
    if (arr[b] - arr[a])==c:      
      score+=d
  ans=max(ans,score)
print(ans)

Submission status: Accepted

Solution code:
import math
from itertools import combinations_with_replacement

n, m, q = map(int, input().split())
ls = []
for i in range(1, m + 1):
    ls.append(i)

a = []
b = []
c = []
d = []

for i in range(q):
    aa, bb, cc, dd = map(int, input().split())
    a.append(aa)
    b.append(bb)
    c.append(cc)
    d.append(dd)

zzz = list(combinations_with_replacement(ls, n))
ans = 0

for i in zzz:
    com = list(i)
    p = 0
    for j in range(q):
        if (com[b[j] - 1] - com[a[j] - 1]) == c[j]:
            p += d[j]
    ans = max(ans, p)

print(ans)