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: Runtime Error

Solution code:
conditions = input().split(' ')
n = int(conditions[0])
m = int(conditions[1])
q = int(conditions[2])

data = [input().split(' ') for _ in range(q)]

def next_dim(dl, max_val):
    l = len(dl)
    output_list = []
    for i in range(l):
        for j in range(dl[i][-1], max_val + 1):
            buf_list = dl[i].copy()
            buf_list.append(j)
            output_list.append(buf_list)
    return output_list

a_list =[[i] for i in range(1, m + 1)]
for _ in range(n - 1):
    a_list = next_dim(a_list, m)

max_score = 0
for a in a_list:
    a_score = 0
    for i in range(q):
#         num_1 = int(data[i][0]) - 1
#         num_2 = int(data[i][1]) - 1
#         diff = int(data[i][2])
#         if a[num_2] - a[num_1] == diff:
        if a[int(data[i][1])] - a[int(data[i][0])] == int(data[i][2]):
            a_score += int(data[i][3])
    if a_score > max_score:
        max_score = a_score
    
print(max_score)

Submission status: Runtime Error

Solution code:
from itertools import product
from collections import defaultdict


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

    m_list = defaultdict(list)

    for i in range(1,m+1):
        m_list[i].append(0)

    for data in abcd:
        for i in range(1, m+1):
            for j in range(i+1, m+1):
                if j - i == data[2]:
                    m_list[data[0]].append(i)
                    m_list[data[1]].append(j)

    ll = list(product(*m_list.values()))

    ans = 0
    for l in ll:
        tmp = 0
        for data in abcd:
            if l[data[1]-1] - l[data[0]-1] == data[2]:
                tmp += data[3]
        if tmp > ans:
            ans = tmp

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
def main():
	n,m,q = map(int,input().split())
	qu = [list(map(int,input().split())) for x in range(q)]
	ans = 0
	import itertools

	ans_list = set()
	for i in itertools.combinations_with_replacement([1,2,3,4,5,6,7,8,9,10],m):
		for qul in range(q):
			if i[ qu[qul][1]-1 ] - i[ qu[qul][0]-1 ] == qu[qul][2]:
				ans += qu[qul][3]
		ans_list.add(ans)
		ans = 0
	print(max(ans_list))

if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
import numpy as np
import itertools


def solve(N: int, M: int, Q: int, a: "List[int]", b: "List[int]", c: "List[int]", d: "List[int]"):
    l = [i for i in range(1,M+1)]
    A = []
    if N==M:
        A.append(l)
    else:
        for v in itertools.permutations(l, N):
            if sorted(v) not in A:
                A.append(sorted(v))

    ans = [0] * len(A)

    for i in range(len(A)):
        #print(A[i])
        for j in range(Q):
            #print(a[j],b[j],c[j],d[j],A[i][b[j]-1]-A[i][a[j]-1], c[j], d[j])
            #print(A[i][b[j]-1]-A[i][a[j]-1], c[j])
            if (A[i][b[j]-1]-A[i][a[j]-1])==c[j]:
                ans[i] += d[j]
        #print(ans[i])
    #print(ans)
    print(max(ans))

    return


# Generated by 1.1.6 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
    Q = int(next(tokens))  # type: int
    a = [int()] * (Q)  # type: "List[int]"
    b = [int()] * (Q)  # type: "List[int]"
    c = [int()] * (Q)  # type: "List[int]"
    d = [int()] * (Q)  # type: "List[int]"
    for i in range(Q):
        a[i] = int(next(tokens))
        b[i] = int(next(tokens))
        c[i] = int(next(tokens))
        d[i] = int(next(tokens))
    solve(N, M, Q, a, b, c, d)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import itertools
N,M,Q=map(int,input().split())
L=[]
for q in range(Q):
    L.append(list(map(int,input().split())))

A = itertools.combinations([q for q in range(1,(M+1))], N)
# print(L)
# print(A)
count=[]
for a in A:
    tmp=[]
    for l in L:
        try:
            if a[l[1]-1] - a[l[0]-1] == l[2]:
                tmp.append(l[3])
            else:
                pass
        except:
            pass
    # print(tmp)
    count.append(sum(tmp))

# print(count)

print(max(count))

Submission status: Runtime Error

Solution code:
import itertools

n,m,q=map(int,input().split())
intt=[]
for i in range(1,m+1):
  intt.append(i)
array=list(itertools.permutations(intt))
print(array)
count=0
maa=0
l=len(array)
for k in range(q):
  a,b,c,d=map(int,input().split())
  for i in range(l):
    if array[i][b-1]-array[i][a-1]==c:
      count+=d
      print(array[i])
      
  if maa<count:
    maa=count
  
  count=0
  
print(maa)

Submission status: Runtime Error

Solution code:
import itertools

n, m, q = [int(x) for x in input().split()]
 
t = [sorted(x) for x in list(itertools.product(range(1, m + 1), repeat=(m-1)))]
t = list(map(list, set(map(tuple, t))))
 
tmp = []
for i in range(q):
    a, b, c, d = [int(x) for x in input().split()]
    tmp.append([a, b, c, d])

score = 0
for _t in t:
    _s = 0
    for a, b, c, d in tmp:
        if c == _t[b - 1] - _t[a - 1]:
            _s += d
    score = max(_s, score)
print(score)

Submission status: Runtime Error

Solution code:
import itertools

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

a = [0] * Q
b = [0] * Q
c = [0] * Q
d = [0] * Q

# 標準出力
baselis = []

for i in range(Q):
    tmplis = []  
    a[i], b[i], c[i],d[i] = map(int, input().split())
    tmplis = [a[i], b[i], c[i],d[i]]
    baselis.append(tmplis)

# 可能性の総列挙

Clis = []

for i in range(1,M+1):
    Clis.append(i)
    
Clis = list(itertools.permutations(Clis, 3))


ans = 0
anslis = []

for i in range(len(Clis)):
    anslis.append(ans)
    ans = 0  
    SingleClis = Clis[i]
    for j in range(len(baselis)):
        SimpleBaselis = baselis[j]
        Bi = SimpleBaselis[1]
        Ai = SimpleBaselis[0]
        Ci = SimpleBaselis[2]
        Di = SimpleBaselis[3]
        
        if len(SingleClis) < Bi-1 or len(SingleClis) < Ai - 1:
            pass
        else:
            if SingleClis[Bi-1] - SingleClis[Ai-1] == Ci:
                ans = ans + Di

print(max(anslis))

Submission status: Runtime Error

Solution code:
from itertools import combinations_with_replacement as c
n, m, q = [int(i) for i in input().split()]
abc = [[int(i) for i in input().split()] for _ in range(q)]
aa = list(range(1,m+1))
ans = 0
for bb in c(aa,m):
    cc = 0
    for a, b, c, d in abc:
        if bb[b-1] - bb[a-1] == c:
            cc += d
    ans = max(ans, cc)
print(ans)

Submission status: Runtime Error

Solution code:
    else:
        listA.append(i)
totals = []
for i in range(li[2]):
    ai = lists[i][0]-1
    bi = lists[i][1]-1
    ci = lists[i][2]
    di = lists[i][3]
    total = 0
    if not listA[bi] - listA[ai] == ci:
        listA[bi] = listA[ai] + ci
    for j in range(li[2]):
        if listA[lists[j][1]-1] - listA[lists[j][0]-1] == lists[j][2]:
            total = total + lists[j][3]   
    totals.append(total)
print(max(totals))

Submission status: Runtime Error

Solution code:
def main():
	n,m,q = map(int,input().split())
	qu = [list(map(int,input().split())) for x in range(q)]
	ans = 0
	import itertools

	ans_list = set()
	for i in itertools.combinations_with_replacement([1,2,3,4,5,6,7,8,9,10],m):
		if list(i) == sorted(i):
			for qul in range(q):
				if i[ qu[qul][1]-1 ] - i[ qu[qul][0]-1 ] == qu[qul][2]:
					ans += qu[qul][3]
			ans_list.add(ans)
			ans = 0
	print(max(ans_list))

if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
#import numpy as np
import math
#from fractions import gcd

def check_Q(current_list,Qset):

    sum_d = 0
    for i in range(len(Qset)):
        current_Qset = Qset[i]
        if (current_list[current_Qset[1]-1]-current_list[current_Qset[0]-1])==current_Qset[2]:
            sum_d = sum_d+current_Qset[3]

    return sum_d

def check_N(preget_list,zan_pre,M,nokori_N,Qset):

    if nokori_N==1:
        sum_list = []
        for i in range(zan_pre,M+1):
            current_list = preget_list+[i]
            sum_list.append(check_Q(current_list,Qset))

        return sum_list
    else:
        sum_list = []
        for i in range(zan_pre,M+1):
            current_list = preget_list+[i]
            sum_list = sum_list + check_N(current_list,i+1,M,nokori_N-1,Qset)

        return sum_list

def main():

    ##get int
    first_input = list(map(lambda x:int(x), input().split(" ")))
    #second_input = list(map(lambda x:int(x), input().split(" ")))

    ##get float
    #first_input = list(map(lambda x:float(x), input().split(" ")))
    #second_input = list(map(lambda x:float(x), input().split(" ")))

    ##get string
    #first_input = input().split(" ")

    N = first_input[0]
    M = first_input[1]
    Q = first_input[2]

    Qset = []
    for i in range(Q):
        secondkara_input = list(map(lambda x:int(x), input().split(" ")))
        Qset.append(secondkara_input)

    #print(check_N([],1,M,N,Qset))
    print(max(check_N([],1,M,N,Qset)))

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n, m, q = [int(x) for x in input().split()]

t = [sorted(x) for x in list(itertools.product(range(1, m + 1), repeat=(m-1)))]
t = list(map(list, set(map(tuple, t))))

tmp = []
for i in range(q):
    a, b, c, d = [int(x) for x in input().split()]
    tmp.append([a, b, c, d])

score = 0
for _t in t:
    _s = 0
    for a, b, c, d in tmp:
        if c == _t[b - 1] - _t[a - 1]:
            _s += d
    score = max(_s, score)
print(score)

Submission status: Runtime Error

Solution code:
import itertools

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

a = [0] * Q
b = [0] * Q
c = [0] * Q
d = [0] * Q

# 標準出力
baselis = []

for i in range(Q):
    tmplis = []  
    a[i], b[i], c[i],d[i] = map(int, input().split())
    tmplis = [a[i], b[i], c[i],d[i]]
    baselis.append(tmplis)

# 可能性の総列挙

Clis = []

for i in range(1,M+1):
    Clis.append(i)
    
Clis = list(itertools.permutations(Clis, 3))


ans = 0
anslis = []

for i in range(len(Clis)):
    anslis.append(ans)
    ans = 0  
    SingleClis = Clis[i]
    for j in range(len(baselis)):
        SimpleBaselis = baselis[j]
        Bi = SimpleBaselis[1]
        Ai = SimpleBaselis[0]
        Ci = SimpleBaselis[2]
        Di = SimpleBaselis[3]
        
        if len(SingleClis) < Bi or len(SingleClis) < Ai :
            pass
        else:
            if SingleClis[Bi-1] - SingleClis[Ai-1] == Ci:
                ans = ans + Di

print(max(anslis))

Submission status: Runtime Error

Solution code:
# /usr/bin/python3
# -*- coding: utf-8 -*-
from queue import Queue
from queue import LifoQueue as Stack
from math import sqrt, floor, ceil, log2, log10, pi
from fractions import gcd
from itertools import permutations, combinations
from operator import itemgetter
from functools import cmp_to_key


INF=1001001001
__MOD__=(10**9)+7
yn = 'YNeos'
judge = False
cnt = 0
ans = None


def lcm(a, b):
    return (a*b) // gcd(a,b)

def intinput():
    return int(input())

def mulinputs():
    return map(int,input().split())

def lineinputs(func=intinput):
    datas = []
    while True:
        try:
            datas.append(func())
        except EOFError:
            break
    return datas

class ModInt():
    def __init__(self, x):
        self.__x = (x % __MOD__)
    def __add__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x + other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x + other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __radd__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x + self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x + self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __sub__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x - other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x - other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rsub__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x - self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x - self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __mul__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x * other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x * other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rmul__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x * self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x * self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __truediv__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x * other.__modinv())%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x * other.__modinv())%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rtruediv__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x * self.__modinv())%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x * self.__modinv())%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __pow__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__(pow(self.__x, other.__x, __MOD__)))
        elif type(other) == ModInt:
            return self.__class__(pow(self.__x, other.__x, __MOD__))
        else:
            raise Exception("Not Int or Not ModInt")
    def __rpow__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__(pow(other.__x, self.__x, __MOD__)))
        elif type(other) == ModInt:
            return self.__class__(pow(other.__x, self.__x, __MOD__))
        else:
            raise Exception("Not Int or Not ModInt")

    def __modinv(self, m=__MOD__):
        a = self.__x
        if a == 0:
            raise ZeroDivisionError()
        if gcd(a, m) != 1:
            raise Exception("%sの逆数は求まりません。" % a)
        b, u, v = m, 1, 0
        while b != 0:
            t = a//b;
            a -= t*b
            a, b = b, a
            u -= t * v
            u, v = v, u
        u %= m
        if u < 0:
            u += m
        return u
    def __int__(self):
        return self.__x
    def __str__(self):
        return str(self.__x)



D_MAX = 0
total = 0
def dfs(midx, nidx, elm_set, comb_set, comb, a, b, c, d, n, q):
    global total
    global D_MAX
    if total >= 1000:
        print(D_MAX)
        exit()
    total += 1
    # if comb in comb_set:
    #     return comb_set
    # print(midx, nidx, elm_set, comb_set, comb, a, b, c, d, n, q)
    # print(midx, nidx, elm_set, comb_set, comb, sep="\t")
    # tmp = [comb] + comb_set if comb and comb not in comb_set else [] + comb_set
    tmp = [comb] + comb_set if comb else [] + comb_set
    tmp.sort()
    if len(tmp) == n:
        d_max_tmp = 0
        for i in range(q):
            # print(tmp, b[i]-1,  a[i]-1, c[i], d[i])
            if tmp[b[i]-1] - tmp[a[i]-1] == c[i]:
                # print(midx, nidx, elm_set, comb_set, comb, D_MAX, sep="\t")
            # if comb_set[b[i]-1] - comb_set[a[i]-1] == c[i]:
                d_max_tmp += d[i]
        D_MAX = max(d_max_tmp, D_MAX)
        return comb_set
    elif len(tmp) > n:
        return comb_set
    if nidx == n:
        return comb_set
    for i in range(nidx,n):
        elm = elm_set[i]
        comb_set = dfs(midx-1, nidx+1, elm_set, tmp, elm, a, b, c, d, n ,q)
    return comb_set


if __name__ == '__main__':
    N, M, Q = mulinputs()
    A, B, C, D = [], [], [], []
    d_max = 0
    for _ in range(Q):
        a, b, c, d = mulinputs()
        if b >= a:
            d_max += d
        A.append(a)
        B.append(b)
        C.append(c)
        D.append(d)

    base_set = list(range(1, M+1))
    dfs(M, 0, base_set, [], None, A, B, C, D, M, Q)

    # 出力
    print(D_MAX)

Submission status: Runtime Error

Solution code:
import itertools
N,M,Q=map(int,input().split())
L=[]
for q in range(Q):
    L.append(list(map(int,input().split())))

A = list(itertools.combinations([q for q in range(1,(M+1))], N))
# print(L)
# print(A)
count=[]
for a in A:
    # tmp=0
    tmp=[]
    for l in L:
        if a[l[1]-1] - a[l[0]-1] == l[2]:
            tmp.append(l[3])
        else:
            pass
    # print(tmp)
    count.append(sum(tmp))

# print(count)

print(max(count))

Submission status: Runtime Error

Solution code:
import numpy as np
N,M,Q=map(int, input().split())
matrix=[]
for _ in range(Q):
    c=list(map(int, input().split()))
    matrix.append(c)
matrix = np.array(matrix)
import itertools
ansscore = 0
maxscore = sum([row[3] for row in matrix])
for i in itertools.product(range(1,M+1), repeat=N):
    i = list(i)
    i.sort()
    score=0
    for l in matrix:
        a=l[0]
        b=l[1]
        c=l[2]
        d=l[3]
        if i[b-1]-i[a-1]==c:
            score+=d
    ansscore = score if score>ansscore else ansscore
    if ansscore == maxscore:
        break
print(ansscore)

Submission status: Runtime Error

Solution code:
import itertools
n, m, q = map(int, input().split(" "))
asset = []
for i in range(q):
    asset.append(list(map(int, input().split(" "))))
A = []


max = 0
for a in itertools.product(list(range(1, m + 1)), repeat = n):
    A.append((list(a)))
for i in range(len(A)):
    total = 0
    for j in range(0, n):
        if A[j] <= A[j - 1]:
            continue
    for j in range(q):
        if A[i][asset[j][1] - 1] - A[i][asset[j][0] - 1] == asset[j][2]:
            total += asset[j][3]
    max = total if total > max else max
print(max)

Submission status: Runtime Error

Solution code:
import itertools
n, m, q = map(int, input().split(" "))
asset = []
for i in range(q):
    asset.append(list(map(int, input().split(" "))))
A = []


max = 0
print (asset)
for a in itertools.product(list(range(1, m + 1)), repeat = n):
    A.append((list(a)))
for i in range(len(A)):
    total = 0
    for j in range(0, n):
        if A[j] <= A[j - 1]:
            continue
    for j in range(q):
        if A[i][asset[j][1] - 1] - A[i][asset[j][0] - 1] == asset[j][2]:
            total += asset[j][3]
    max = total if total > max else max
print(max)

Submission status: Runtime Error

Solution code:
a=list(map(int,input().split()))
b=[]
ans=0
c=[]
for _ in range(a[2]):
    b.append(list(map(int,input().split())))

for i in range(1,a[1]+1):
    for j in range(i,a[1]+1):
        for k in range(j,a[1]+1):
            c=[i,j,k]
            for l in range(a[2]):
                if c[b[l][1]-1]-c[b[l][0]-1]==b[l][2]:
                    ans+=b[l][3]
            d.append(ans)
            ans=0
print(max(d))

Submission status: Runtime Error

Solution code:
import math
import itertools

n,m,q = map(int,input().split())
li=[input() for i in range(q)]

ans_list=list()
ans=0

lis =  list(range(1,m+1))
for team in itertools.combinations(lis, n):

    for i in range(q):
      lix=li[i].split()
      
      if team[int(lix[1])-1]-team[int(lix[0])-1]==int(lix[2]):
        ans+=int(lix[3])
        
    ans_list+=[ans]
    ans=0
      
    
    
print(max(ans_list))

Submission status: Runtime Error

Solution code:
m, n, q = map(int, input().split())
aa = [0]*q
bb = [0]*q
cc = [0]*q
dd = [0]*q
for i in range(q):
    aa[i],bb[i],cc[i], dd[i] = list(map(int, input().split()))
    
import itertools
ss = set(itertools.permutations([0]*(n-1)+[1]*(m-1)))
score = 0
for tu in ss:
    tmp = 0
    xx = [1]*n
    j = 0
    for t in tu:
        if t == 0:
            j += 1
        if t == 1:
            xx[j] += 1
    for i in range(q):
        if xx[bb[i]-1] - xx[aa[i]-1] ==cc[i]: 
            tmp += dd[i]
    score = max(score, tmp)
print(score)

Submission status: Runtime Error

Solution code:
import itertools
n,m,q=map(int,input().split())
lis=[i for i  in range(1,m+1)]
lis=list(itertools.combinations(lis,n))
box=[0 for j in range(len(lis))]
for i in range(q):
    que=list(map(int,input().split()))
    for j in range(len(lis)):
        if lis[j][que[1]-1]-lis[j][que[0]-1]==que[2]:
            box[j]+=que[3] 
print(max(box))

Submission status: Runtime Error

Solution code:
import itertools
A = list(map(int,input().split()))
N, M, Q = A[0], A[1], A[2]
B = [list(map(int,input().split())) for _ in range(Q)]

M_list = [i for i in range(1, M+1)]
c = itertools.combinations(M_list, N)
max_list = []
for N_list in c:
    #print(N_list)
    d_list = []
    for i in range(Q):
        a = B[i][0]
        b = B[i][1]
        c = B[i][2]
        d = B[i][3]

        if N_list[b-1] - N_list[a-1] == c:
            d_list.append(d)
        else:
            d_list.append(0)
    max_list.append(sum(d_list))
print(max(max_list))

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque
from itertools import combinations

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

D = defaultdict(set)
for a, b, c, d in ABCD:
  D[b-1].add((a-1, c, d))

for j in range(N-1, 0, -1):
  for x, y in combinations(D[j], 2):
    if x[0] == y[0]:
      continue
    if x[0] > y[0]:
      x, y = y, x
    if x[1] > y[1]:
      for a, c, d in D[y[0]]:
        if a == x[0] and c == x[1] - y[1]:
          break
      else:
        D[y[0]].add((x[0], x[1] - y[1], 0))

for j in range(1, N):
  for a, c, d in D[y[0]]:
    if a == j-1 and c == 0:
      break
  else:
    D[j].add((j-1, 0, 0))

que = deque([([1], 0)])
ans = 0
while que:
  L, score = que.popleft()
  if len(L) == N:
    if score > ans:
      ans = score
  else:
    for a, c, d in D[len(L)]:
      l = L[a] + c
      if l <= M:
        que.append((L + [l], score + sum(d for a, c, d in D[len(L)] if l - L[a] == c)))
print(ans)

Submission status: Runtime Error

Solution code:
import itertools

N, M, Q = list(map(int,input().split()))
numbers = [i for i in range(1, M+1)]
array = itertools.combinations_wih_replacement(numbers, N)

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

max_score = 0
for A in array:
    score = 0
    for _ in range(Q):
        a, b, c, d = input_data[_]
        a = a - 1
        b = b - 1
        if A[b] - A[a] == c:
            score += d
    if score > max_score:
        max_score = score
    
print(max_score)

Submission status: Runtime Error

Solution code:
a, b, n = map(int, input().split())
ans = 0
s = max(int(b/a),e-1000)
e = min(n+1,b)
for i in range(s, e):
  x = (int(a*i/b)-a*int(i/b))
  if ans < x:
    ans = x
print(ans)

Submission status: Runtime Error

Solution code:
from itertools import combinations
n,m,q = map(int, input().split())
tmp_A = [i+1 for i in range(m)]

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

top = 0    
for a in tmp_A:
    for b in [x for x in tmp_A if x >= a]:
        for c in [x for x in tmp_A if x >= b]:
            for d in [x for x in tmp_A if x >= c]:
                base = [a,b,c,d]
                res = 0
                for i in range(len(SU)):
                    e,f,g,h = SU[i][0], SU[i][1], SU[i][2], SU[i][3]
                    if (base[f-1] - base[e-1]) == g:
                        res += h
                    if res >= top:
                        top = res         
print(top)

Submission status: Runtime Error

Solution code:
import copy
import sys
sys.setrecursionlimit(2*10**9)
def solve(n, m, q, A):
  if len(A) == m+1:
    rtn = 0
    for a, b, c, d in q:
      rtn += d if A[b]-A[a] == c else 0
    return rtn
  else:
    return max([solve(n, m, q, A+[i]) for i in range(A[-1], m+1)])

N, M, Q = map(int, input().split())
ABCD = [list(map(int, input().split())) for _ in range(Q)]
print(solve(N, M, ABCD, [1]))

Submission status: Runtime Error

Solution code:
N,M,Q=map(int,input().split())
ABCD=[list(map(int,input().split())) for i in range(Q)]
from itertools import combinations
ans=0
for p in combinations(range(N+M),M):
    r=0
    for a,b,c,d in ABCD:
        if p[b-1]-b+1-p[a-1]+a-1==c:
            r+=d
    ans=max(ans,r)
print(ans)

Submission status: Runtime Error

Solution code:
from heapq import heappush, heappop
from itertools import permutations, accumulate, combinations
from math import pi, ceil, floor
import numpy as np
from collections import defaultdict, deque,Counter
from operator import itemgetter
from bisect import bisect_left, bisect_right, insort_left, insort_right
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10 ** 6)
# MOD = 10 ** 9 + 7
# INF = float("inf")


def main():
    n, m, q = map(int, input().split())
    l = [tuple(map(int, input().split())) for _ in range(q)]
    ans = 0
    for i in range(2 ** q):  # とるかとらないかの2択
        check = [0] * q
        for j in range(q):
            if i >> j & 1:
                check[j] = 1
        # print(check)
        A = [1] * n
        used = [0] * n
        tmp = 0
        for k in range(q):
            if check[k]:  # とる時
                a, b, c, d = l[k]
                a -= 1
                b -= 1
                if not used[b]:  # 使ってない時は変更できる
                    A[b] = c + A[a]
                    tmp += d
                    used[b] = 1  # 変更ずみにする
                    used[a] = 1
                    if A[b] > m:  # m以上の場合はダメ
                        tmp = 0
                        break
                elif A[b] == c + A[a]:  # たまたま変更してからあってたら追加
                    tmp += d
                else:  # 条件に合わない場合
                    tmp = 0
                    break
        ans = max(ans, tmp)
    print(ans)



if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

import itertools
N,M,Q = input().split()
N,M,Q = int(N),int(M),int(Q)

abcdl = []

for i in range(0,Q):
    abcdl.append(input().split())
abcdint = [[int(s) for s in row] for row in abcdl]

#listAは長さN,数列Aの各要素は1～M、数列の得点は
#1番目-0番目 = ci
#条件を満たすiについてのdiの総和が得点,iがないときは0
#aiとbiは配列Aのindexを表す
Alist = []
rangelist = []
resultlist = []
for h in range(1,M):
    rangelist.append(h)
count = 0
for j in itertools.permutations(rangelist,N):
    count += 1
    Alist.append(j)


for k in range(0,count):
    box = 0
    for i in range(0,Q):
        if Alist[k][abcdint[i][1]-1] - Alist[k][abcdint[i][0]-1] == abcdint[i][2]:
            box += abcdint[i][3]
        
    resultlist.append(box)
# print(Alist)
# print(rangelist)
# print("Alen",len(Alist))
print(max(resultlist))

Submission status: Runtime Error

Solution code:
from itertools import combinations
n,m,q = map(int, input().split())
tmp_A = [i+1 for i in range(m)]

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

top = 0    
for a in tmp_A:
    for b in tmp_A:
        for c in tmp_A:
            for d in tmp_A:
                base = [a,b,c,d]
                res = 0
                for i in range(len(SU)):
                    e,f,g,h = SU[i][0], SU[i][1], SU[i][2], SU[i][3]
                    if (base[f-1] - base[e-1]) == g:
                        res += h
                    if res >= top:
                        top = res         
print(top)

Submission status: Runtime Error

Solution code:
from itertools import combinations

n,m,q = map(int,input().split())

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

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

l = list(range(1,m+1))

ans = list(combinations(l,n))
a_ns = []

for j in range(len(ans)):
	ANS = 0
	for i in range(len(a)):
		if ans[j][b[i]-1] - ans[j][a[i]-1] == c[i]:
			ANS += d[i]
	a_ns.append(ANS)

print(max(a_ns))

Submission status: Runtime Error

Solution code:
#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int N, M, B;
    cin >> N >> M >> B;
    int size = N*M;
    int blocks[size];
    int modeData[size] = { 0 };
    for(int i=0; i<size; i++) cin >> blocks[i];
    // 최빈 값을 확인한다!
    int index = 0;
    for(int j=0; j<size; j++){
        for(int i=0; i<size; i++) if(blocks[index] == blocks[i]) modeData[index]++;
        index++;
    }
    int max = 0;
    for(int i=0; i<size; i++) if(modeData[i] > max) max = modeData[i];
    for(int i=0; i<size; i++) if(modeData[i] == max) max = i;
    index = blocks[max]; // index 변수 재활용 -> 최빈값 저장.
    int plus = 0, min = 0;
    for(int i=0; i<size; i++){
        if(blocks[i] < index ){ // 블록이 최빈값보다 작다면 인벤에서 꺼내서 줘야함.
            plus += blocks[i]-index;
        } else if(blocks[i] > index){ // 제거 후 인벤에 넣어야함.
            min += index - blocks[i];
        }
    }
    if(plus <= B){
        cout << plus;
    } else{
        for(int i=0; i<size; i++){
            
        }
    }
}

Submission status: Runtime Error

Solution code:
import copy
import sys
sys.setrecursionlimit(10**9)
def solve(n, m, q, A):
  if len(A) == m+1:
    rtn = 0
    for a, b, c, d in q:
      rtn += d if A[b]-A[a] == c else 0
    return rtn
  else:
    return max([solve(n, m, q, A+[i]) for i in range(A[-1], m+1)])

N, M, Q = map(int, input().split())
ABCD = [list(map(int, input().split())) for _ in range(Q)]
print(solve(N, M, ABCD, [1]))