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

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

n, m, q = [int(x) for x in input().split()]
abcd = [[int(x) for x in input().split()] for _ in range(q)]
all_pattern = []
start = ['1']

def dfs(s):
    last_s = int(s[-1])
    next_s = [str(x) for x in range(last_s, m + 1)]
    for i in next_s:
        t = s[:]
        t.append(i)
        if len(t) == n + 1:
            all_pattern.append(t[1:])
        else:
            dfs(t)
dfs(start)
ans = 0
for pattern in all_pattern:
    res = 0
    for i in range(q):
        a, b, c, d = abcd[i]
        if int(pattern[b - 1]) - int(pattern[a - 1]) == c:
            res += d
    ans = max(ans, res)

print(ans)

Solution (Python):

from collections import deque
from typing import Tuple

N: int
M: int
conditions: Tuple[Tuple[int, int, int, int]]


def dfs():
    queue = deque([[1]])
    highest = 0
    while queue:
        seq = queue.popleft()
        if len(seq) == N + 1:
            highest = max(
                highest, sum(d for a, b, c, d in conditions if seq[b] - seq[a] == c)
            )
        else:
            for i in range(seq[-1], M + 1):
                queue.append(seq + [i])
    return highest


def main():
    global N, M, conditions
    N, M, Q, *ABCD = map(int, open(0).read().split())
    conditions = tuple(zip(*[iter(ABCD)] * 4))
    print(dfs())


if __name__ == "__main__":
    main()

Solution (Python):
import sys
readline = sys.stdin.readline
from itertools import combinations_with_replacement

def main():
    N, M, Q = map(int, readline().rstrip().split())
    P = [tuple(map(int, readline().rstrip().split())) for _ in range(Q)]
    ans = 0    
    for pair in combinations_with_replacement([i for i in range(1, M+1)], N):
        score = 0
        for a, b, c, d in P:
            if pair[b-1] - pair[a-1] == c:
                score += d
        ans = max(ans, score)
    
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 6)


def dfs(num):
    global N, ans, M
    n = len(num)
    if n == N:
        cnt = 0
        for a, b, c, d in con:
            a -= 1; b -= 1
            if num[b] - num[a] == c:
                cnt += d
        ans = max(ans, cnt)
    else:
        e = 1 if n == 0 else num[-1]
        for i in range(e, M + 1):
            dfs((*num, i))


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

ans = 0
dfs(tuple())

print(ans)

Solution (Python):


import itertools

def main():
    n, m, q = map(int, input().split())
    List = []
    for i in range(q):
        a, b, c, d = map(int, input().split())
        List.append([a, b, c, d])
    
    max_total = 0

    for A in list(itertools.combinations_with_replacement(range(1, m+1),n)):
        total = 0
        for abcd in List:
            if A[abcd[1]-1] - A[abcd[0]-1] == abcd[2]:
                total += abcd[3]
        
        if total >= max_total:
            max_total = total
    
    print(max_total)

if __name__ == '__main__':
    main()

Solution (Python):
import itertools
def LI():return list(map(int,input().split()))
n,m,q=LI()
abcd=[]
for _ in range(q):
  a,b,c,d=LI()
  a-=1
  b-=1  
  abcd.append((a,b,c,d))
As=itertools.combinations_with_replacement(range(m),n)
ans=0
for A in As:
  cnt=0
  for a,b,c,d in abcd:
    if A[b]-A[a]==c:cnt+=d
  ans=max(ans,cnt)
print(ans)

Solution (Python):
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()))

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

nax = 0
for x in l:
    score = 0
    for i in range(Q):
        if int(x[b[i]-1]) - int(x[a[i]-1]) == c[i]:
            score += d[i]
    nax = max(nax,score)

print(nax)

Solution (Python):
from itertools import combinations_with_replacement as c 
n, m, q = map(int, input().split()) 
arr = [] 
for i in range(q): 
    l = [*map(int, input().split())] 
    arr.append(l) 
res = 0
for g in c(list(range(1, m+1)), n): 
    f = 0 
    for h in arr:
        if g[h[1]-1] - g[h[0]-1] == h[2]: 
            f += h[3]
    res = max(res, f) 
print(res)

Solution (Python):
import itertools
li=[]
n,m,q=map(int,input().split())
ans=0
ansl=[0]
for cnt in range(q):
    a,b,c,d=map(int,input().split())
    li.append([a,b,c,d])
for A in itertools.combinations_with_replacement(range(1,m+1),n):
    for i in range(q):
        if li[i][2]==A[li[i][1]-1]-A[li[i][0]-1]:
            ans+=li[i][3]
    ansl.append(ans)
    ans=0
print(max(ansl))

Solution (Python):
import copy
N, M, Q = map(int, input().split())
A = []
B = []
C = []
D = []
ans = 0
def dfs(l):
    if len(l) == N+1:
        global ans
        now = 0
        for i in range(Q):
            if(l[B[i]] - l[A[i]] == C[i]):
                now += D[i]
        ans = max(ans, now)
    else:
        tmp = copy.copy(l)
        tmp.append(l[-1])
        while tmp[-1] <= M:
            dfs(tmp)
            tmp[-1] += 1

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)

dfs([1])
print(ans)

Solution (Python):


import sys
from itertools import combinations_with_replacement

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, Q = MAP()
ABCD = []
for i in range(Q):
    a, b, c, d = MAP()
    ABCD.append((a-1, b-1, c, d))

ans = 0
for comb in combinations_with_replacement(range(1, M+1), N):
    cnt = 0
    for a, b, c, d in ABCD:
        if comb[b] - comb[a] == c:
            cnt += d
    ans = max(ans, cnt)
print(ans)

Solution (Python):
n, m, q = map(int, input().split())
l = [[int(i) for i in input().split()] for _ in range(q)]
m -= 1
mx = 0


def main(x, y, A, c):
  global mx
  if x == n and y == m:
    pts = 0
    for i in l:
      if int(A[i[1]-1])-int(A[i[0]-1]) == i[2]:
        pts += i[3]
    mx = max(mx, pts)
    return
  if x < n:
    nA = A+str(c)
    main(x+1, y, nA, c)
  if y < m:
    nc = c+1
    main(x, y+1, A, nc)


main(0, 0, "", 0)
print(mx)

Solution (Python):

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

def dfs(A):
    
    global ans
    
    
    if len(A) == N:
        score = 0
        for a, b, c, d in buff:
            if A[b-1] - A[a-1] == c:
                score += d
        ans = max(ans, score)
        return
    
    A.append(A[-1])
    
    while A[-1] <= M:
        
        dfs(A[:])
        A[-1] += 1



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

ans = 0
dfs([1])

print(ans)

Solution (Python):
import copy

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

def dfs(al):
    global ans
    if len(al) == n:
        test = 0
        for i in range(q):
            if al[b[i]-1] - al[a[i]-1] == c[i]:
                test += d[i]
        ans = max(ans, test)
        return
    
    al.append(al[-1])
    i = len(al)
    while True:
        if al[i-1] > m:
            break
        dfs(copy.deepcopy(al))
        al[i-1] += 1

dfs([1])
print(ans)

Solution (Python):
n, m, q = map(int, input().split())
l = [[int(i) for i in input().split()] for _ in range(q)]
m -= 1
mx = 0


def gen_A(x, y, A, c):
  global mx
  if x == n and y == m:
    pts = 0
    for i in l:
      if int(A[i[1]-1])-int(A[i[0]-1]) == i[2]:
        pts += i[3]
    mx = max(mx, pts)
    return
  if x < n:
    nA = A+str(c)
    gen_A(x+1, y, nA, c)
  if y < m:
    nc = c+1
    gen_A(x, y+1, A, nc)


gen_A(0, 0, "", 0)
print(mx)

Solution (Python):
from itertools import*
(n,m,_),*t=[[*map(int,t.split())]for t in open(0)]
print(max(sum(d*(z[b-1]-z[a-1]==c)for a,b,c,d in t)for z in combinations_with_replacement(range(m),n)))

Solution (Python):
from pprint import pprint
import itertools


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

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



a_lists = list(itertools.combinations_with_replacement(range(m), n))



dmax = 0

for a_mini in a_lists:
    dtemp = 0
    for ql_mini in ql:
        if a_mini[ql_mini[1]-1] - a_mini[ql_mini[0]-1] == ql_mini[2]:
            dtemp += ql_mini[3]
        else:
            pass
    if dtemp >= dmax:
        dmax = dtemp

print(dmax)

Solution (Python):
from itertools import*
(n,m,_),*t=[[*map(int,t.split())]for t in open(0)]
print(max(sum(d*(z[b-1]-z[a-1]==c)for a,b,c,d in t)for z in combinations_with_replacement(range(m),n)))

Solution (Python):

from typing import List, Tuple

N: int
M: int
conditions: Tuple[Tuple[int, int, int, int]]


def rec(seq: List[int]):
    if len(seq) == N + 1:
        return sum(d for a, b, c, d in conditions if seq[b] - seq[a] == c)
    return max(rec(seq + [i]) for i in range(seq[-1], M + 1))


def main():
    global N, M, conditions
    N, M, Q, *ABCD = map(int, open(0).read().split())
    conditions = tuple(zip(*[iter(ABCD)] * 4))
    print(rec([1]))


if __name__ == "__main__":
    main()

Solution (Python):
import itertools
n,m,q = map(int,input().split())
abcd = [tuple(map(int,input().split())) for _ in range(q)]

l = set(range(1,m+1))
h = itertools.combinations_with_replacement(l, n)

ans = 0
for i in h:
    tmp = 0
    for (a,b,c,d) in abcd:
        if(i[b-1]-i[a-1] == c):
            tmp += d
    ans = max(ans,tmp)

print(ans)

Solution (Python):
from sys import stdin


def input():
    return stdin.readline().strip()


def main():
    N, M, Q = map(int, input().split())
    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] = map(int, input().split())
        a[i] -= 1
        b[i] -= 1

    ans = 0

    def dfs(seq):
        nonlocal ans
        if len(seq) == N:
            score = 0
            for i in range(Q):
                if seq[b[i]] - seq[a[i]] == c[i]:
                    score += d[i]
            ans = max(ans, score)
            return

        score = 0
        for n in range(seq[-1], M + 1):
            seq.append(n)
            dfs(seq)
            seq.pop()

    dfs([1])
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import itertools
 
n,m,q = list(map(int, input().split()))
num_list = [list(map(int,input().split())) for l in range(q)]

result = 0
 
kumi = itertools.combinations_with_replacement(range(1, m+1), n)

for kumi in kumi:
    temp = 0
    for j in range(q):
        if kumi[num_list[j][1]-1] - kumi[num_list[j][0]-1] == num_list[j][2]:
            temp += num_list[j][3]
            result = max(temp,result)

print(result)

Solution (Python):
from collections import Counter
import sys
sys.setrecursionlimit(200000)


def read():
    N, M, Q = map(int, input().split())
    ABCD = []
    for i in range(Q):
        a, b, c, d = map(int, input().split())
        ABCD.append((a, b, c, d))
    return N, M, Q, ABCD


def iter_combinations(a, r):

    q = []

    def _dfs(a, r, m=[]):
        if r == 0:
            q.append(m)
        else:
            for i in range(len(a)):
                _dfs(a[i:], r-1, m + [a[i]])
    
    _dfs(list(a), r)
    return q
        

def solve(N, M, Q, ABCD):
    smax = 0
    for x in iter_combinations(range(1, M+1), N):
        sd = 0
        for a, b, c, d in ABCD:
            if x[b-1] - x[a-1] == c:
                sd += d
        smax = max(smax, sd)
    return smax


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("{}".format(outputs))

Solution (Python):
from itertools import combinations_with_replacement

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

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

ans = 0
for A in As:
    now = 0
    for q in q_list:
        if A[q[1]] - A[q[0]] == q[2]:
            now += q[3]
    ans = max(ans, now)

print(ans)

Solution (Python):
n,m,q  = map(int,input().split())
abcd = [list(map(int,input().split())) for i in range(q)]
import itertools
ans = 0
for i in itertools.combinations_with_replacement(range(1,m+1),n):
         tmp = 0
         for j in range(len(abcd)):
                  if i[abcd[j][1] - 1] - i[abcd[j][0] - 1] == abcd[j][2]:
                           tmp += abcd[j][3]
         if ans < tmp:
                  ans = tmp
print(ans)

Solution (Python):
import sys,bisect,string,math,time,functools,random
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            a,b,c=(inp+[1])[:3]
            org_inp.append(inp)
        else:
            index=0
            a,b,c=(ls[i]+[1])[:3]
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'

    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):
    rt=[]
    for tb in range(n**k):
        s=[tb//(n**bt)%n for bt in range(k)];rt+=[s]
    return rt
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase

input=lambda: sys.stdin.readline().rstrip()

class Comb:
    def __init__(self,n,mo=10**9+7):
        self.fac=[0]*(n+1)
        self.inv=[1]*(n+1)
        self.fac[0]=1
        self.fact(n)
        for i in range(1,n+1):
            self.fac[i]=i*self.fac[i-1]%mo
            self.inv[n]*=i
            self.inv[n]%=mo
        self.inv[n]=pow(self.inv[n],mo-2,mo)
        for i in range(1,n):
            self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
        return
    
    def fact(self,n):
        return self.fac[n]
        
    def invf(self,n):
        return self.inv[n]

    def comb(self,x,y):
        if y<0 or y>x:
            return 0
        return self.fac[x]*self.inv[x-y]*self.inv[y]%mo

class Tree:
    def __init__(self,inp_size=None,init=True):
        if init:
            self.stdin(inp_size)
        return

    def stdin(self,inp_size=None):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1)
        return
    
    def listin(self,ls):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls)
        return

    def __str__(self):
        return  str(self.edges)

    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v

    def EulerTour(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append((-1,x))
        v=[None]*self.size
        v[x]=root_v
        et=[]
        while q:
            cb,ce=q.pop()
            et.append(ce)
            for nb,d in self.edges[ce]:
                if v[nb]==None:
                    q.append((nb,ce))
                    q.append((ce,nb))
                    v[nb]=func(v[ce],nb,d)
        vid=[[-1,-1]for i in range(self.size)]
        for i,j in enumerate(et):
            if vid[j][0]==-1:
                vid[j][0]=i
            else:
                vid[j][1]=i
        return v,et,vid
    
    def LCA_init(self,depth,et):
        self.st=SegTree(self.size*2-1,func=min,ide=inf)
        for i,j in enumerate(et):
            self.st.update(i,j)
        self.LCA_init_stat==True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            depth,et,vid=self.EulerTour(root)
            self.LCA_init(depth,et)
        return self.st.query(x,y+1)

show_flg=False
show_flg=True

p=[]
def pat(n,m,ls):
    if ls:
        M=ls[-1]
    else:
        M=1

    if n==0:
        p.append(ls[:])
        return
    
    for i in range(M,m+1):
        pat(n-1,m,ls[:]+[i])

ans=0
z=[]
N,M,q=LI()
pat(N,M,[])
for i in range(q):
    a,b,c,d=LI()
    z+=[(a,b,c,d)]

for y in p:
    
    tmp=0
    for a,b,c,d in z:
        if y[b-1]-y[a-1]==c:
            tmp+=d
    if ans<tmp:
        ans=tmp
        rt=y[:]

print(ans)

Solution (Python):
n, m , q = map(int, input().split())
 
l = []
for i in range(q):
  a,b,c,d = map(int, input().split())
  l.append((a,b,c,d))
max_score = 0
comb = [[1]]
while len(comb) > 0:
  seed = comb.pop()
  if len(seed) == n:
    score = 0
    for j in l:
      if seed[j[1]-1]-seed[j[0]-1]==j[2]:
      
        score += j[3]
    if score > max_score:
      max_score = score
  else:
    for k in range(seed[-1], m+1):
      s = seed[:]
      s.append(k)
      comb.append(s)
print(max_score)

Solution (Python):

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

import itertools
ansscore = 0
combi = list(itertools.combinations_with_replacement(range(1,M+1),N))
for i in combi:
    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

print(ansscore)

Solution (Python):
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):
    now = 0
    for i in range(q):
        if A[b[i]-1] - A[a[i]-1] == c[i]:
            now += d[i]
    ans = max(ans, now)
print(ans)

Solution (Python):
from sys import stdin


def input():
    return stdin.readline().strip()


def main():
    N, M, Q = map(int, input().split())
    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] = map(int, input().split())
        a[i] -= 1
        b[i] -= 1

    ans = 0

    def dfs(seq):
        nonlocal ans
        if len(seq) == N:
            score = 0
            for i in range(Q):
                if seq[b[i]] - seq[a[i]] == c[i]:
                    score += d[i]
            ans = max(ans, score)
            return

        score = 0
        start = seq[-1] if seq else 1
        for n in range(start, M + 1):
            seq.append(n)
            dfs(seq)
            seq.pop()

    dfs([1])
    print(ans)


if __name__ == "__main__":
    main()

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

patterns = []
def dfs(a):
  if len(a) == N:
    patterns.append(a)
  else:
    for i in range(int(a[-1]), M+1):
   	  dfs(a+[i])

dfs(a=[1])
result = 0
for p in patterns:
  r = 0
  for q in Qs:
    if p[q[1]-1]-p[q[0]-1]==q[2]:
      r += q[3]
  
  result = max([result, r])
print(result)

Solution (Python):
import itertools

abcd = []
N,M,Q = map(int,input().split())
for i in range(Q):
    a,b,c,d = map(int,input().split())
    abcd.append([a,b,c,d])
  
A = itertools.combinations_with_replacement(list(range(1,M+1)),N)
ans = 0
for i in A: 
    _sum = 0
    for j in abcd: 
        if i[j[1]-1] - i[j[0]-1] == j[2]:
            _sum += j[3]
    if ans < _sum:
        ans = _sum
    
print(ans)

Solution (Python):
from sys import stdin


def input():
    return stdin.readline().strip()


def main():
    N, M, Q = map(int, input().split())
    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] = map(int, input().split())
        a[i] -= 1
        b[i] -= 1

    ans = 0

    def dfs(seq):
        nonlocal ans
        if len(seq) == N:
            score = 0
            for i in range(Q):
                if seq[b[i]] - seq[a[i]] == c[i]:
                    score += d[i]
            ans = max(ans, score)
            return

        score = 0
        start = seq[-1] if seq else 1
        for n in range(start, M + 1):
            seq.append(n)
            dfs(seq)
            seq.pop()

    dfs([])
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
N,M,Q = list(map(int, input().split()))
a = [0] * Q
b = [0] * Q
c = [0] * Q
d = [0] * Q
res = 0

def dfs(array):
  if(len(array) == N+1):
    global res
    p = 0

    for i in range(Q):
      
      if(array[b[i]] - array[a[i]] == c[i]):
        p += d[i]
  
    res = max(p, res);

    return

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

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

dfs([1])

print(res)

Solution (Python):
import itertools

N,M,Q = map(int, raw_input().split())
ABCD = []
for i in range(Q):
    abcd = map(int, raw_input().split())
    ABCD.append(abcd)

S = []
def gen(seq, n):
    if n == N:
        S.append(seq)
        return
    tail = seq[-1]
    for x in range(tail, M+1):
        gen(seq+[x], n+1)

gen([1], 1)

ans = 0
for seq in S:
    m = 0
    for a,b,c,d in ABCD:
        if seq[b-1] - seq[a-1] == c: 
            m += d
    ans = max(ans, m)
print ans

Solution (Python):
import itertools
import numpy as np

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

A = np.array(list(itertools.combinations_with_replacement(range(1, M+1), N)))
s = np.zeros(len(A), np.int32)

for i in range(Q):
    a, b, c, d = map(int, input().split())
    s += d * (A[:, b-1] - A[:, a-1] == c)

print(s.max())

Solution (Python):
from itertools import combinations
import sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(20000000)

n, m, q = map(int, input().split())
abcd = []
for i in range(q):
    a, b, c, d = map(int, input().split())
    abcd.append([a-1, b-1, c, d])

def dfs(A, depth, max_a):
    if depth == n:
        score = 0
        for a, b, c, d in abcd:
            if A[b] - A[a] == c:
                score += d
        return score
    ans = 0
    for i in range(max_a, m+1):
        ans = max(ans, dfs(A + [i], depth+1, i))
    return ans

ans = dfs([1], 1, 1)
print(ans)

Solution (Python):

from itertools import combinations_with_replacement

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

    ans = 0
    
    for i in combinations_with_replacement(range(1, m+1), n-1):
        A = [1] + list(i) 
        total = 0
        for abcd in abcd_l:
            
            if A[abcd[1]-1] - A[abcd[0]-1] == abcd[2]:
                total += abcd[3]
        ans = max(ans, total)
    return ans

if __name__ == "__main__":
    print(main())

Solution (Python):
import itertools

N, M, Q = map(int, input().split())
A, B, C, D = [[] for _ in range(4)]

for _ in range(Q):
    a, b, c, d = map(int, input().split())
    A.append(a - 1)
    B.append(b - 1)
    C.append(c)
    D.append(d)

res = 0
for lst in itertools.combinations_with_replacement(range(0, M), N):
    res = max(res, sum([D[i] for i in range(Q) if lst[B[i]] - lst[A[i]] == C[i]]))

print(res)

Solution (Python):
from itertools import combinations_with_replacement
N,M,Q = map(int,input().split())
A = []
for i in range(Q):
    b = list(map(int,input().split()))
    A.append(b)

T = range(1,M+1)
K = list(combinations_with_replacement(T,N))

ans = 0
for line in K:
    total = 0
    for combi in A:
        if line[combi[1]-1] - line[combi[0]-1] == combi[2]:
            total += combi[3]
    ans = max(total,ans)

print(ans)

Solution (Python):
import copy
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 = [1]
ans = 0
def dfs(lis):
    if len(lis) == n+1:
        now = 0
        for i in range(q):
            if lis[b[i]] - lis[a[i]] == c[i]:
                now += d[i]
        global ans
        ans = max(now, ans)
        return 0
    lis.append(lis[-1])
    while lis[-1] <= m:
        newlis = copy.deepcopy(lis)
        dfs(newlis)
        lis[-1] += 1
dfs(A)
print(ans)

Solution (Python):
import itertools
N, M, Q = map(int, input().split())
buff = [list(map(int, input().split())) for _ in range(Q)]

ans = 0
for A in itertools.combinations_with_replacement(range(1, M+1), N):
    score = 0
    for a, b, c, d in buff:
        if A[b-1] - A[a-1] == c:
            score += d
    ans = max(ans, score)

print(ans)

Solution (Python):
import itertools

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

A_comb = itertools.combinations_with_replacement(range(1, m+1), n)

d_sum = 0
for comb in A_comb:
    d_sum_by_comb  = 0
    for aq in a_list:
        b = aq[1]
        a = aq[0]
        c = aq[2]
        d = aq[3]
        if comb[b-1] - comb[a-1] == c:
            d_sum_by_comb += d

    if d_sum < d_sum_by_comb:
        d_sum = d_sum_by_comb

print(d_sum)

Solution (Python):
N, M, Q = map(int, input().split())
ptn = []
for i in range(Q):
    a,b,c,d = map(int, input().split())
    ptn.append([a-1,b-1,c,d])
mx = 0
def calc(arr):
    if len(arr) == N:
        global mx
        tot = 0
        for i in range(Q):
            if arr[ptn[i][1]] - arr[ptn[i][0]] == ptn[i][2]:
                tot += ptn[i][3]
        mx = max(mx, tot)
        return
    for i in range(1,M+1):
        if i < arr[-1]: continue
        calc(arr+[i])
for i in range(1,M+1):
    calc([i])
print(mx)

Solution (Python):
N, M, Q = map(int, input().split())
S=[[0 for i in range(4)] for j in range(Q)]
for i in range(Q):
    inputS=list(map(int,input().split()))
    S[i][0]=inputS[0]
    S[i][1]=inputS[1]
    S[i][2]=inputS[2]
    S[i][3]=inputS[3]
S2=[]
maxNum=0
for a in range(1,M+1):
    for b in range(a,M+1):
        for c in range(b,M+1):
            for d in range(c,M+1):
                for e in range(d,M+1):
                    for f in range(e,M+1):
                        for g in range(f,M+1):
                            for h in range(g,M+1):
                                for i in range(h,M+1):
                                    for j in range(i,M+1):
                                        S2=[a,b,c,d,e,f,g,h,i,j]
                                        count=0
                                        for k in range(Q):
                                            if S2[S[k][1]-1]-S2[S[k][0]-1]==S[k][2]:
                                                count+=S[k][3]
                                        maxNum=max(maxNum,count)
                                       
    
print(maxNum)

Solution (Python):
from itertools import combinations_with_replacement

n, m, q = map(int, input().split())
a = []
b = []
c = []
d = []
for _ in range(q):
    i, j, k, l = map(int, input().split())
    a.append(i - 1)
    b.append(j - 1)
    c.append(k)
    d.append(l)
it = a + b
it = list(set(it))
na = []
nb = []
for i in range(q):
    for j in range(len(it)):
        if a[i] == it[j]:
            na.append(j)
        if b[i] == it[j]:
            nb.append(j)
ans = 0
for x in combinations_with_replacement(range(1, m+1), len(it)):
    cnt = 0
    for i in range(q):
        if x[nb[i]] - x[na[i]] == c[i]:
            cnt += d[i]
    if ans < cnt:
        ans = cnt
print(ans)

Solution (Python):
import itertools

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

result = 0
for x in itertools.combinations_with_replacement(range(1, M + 1), N):
    temp = 0
    for a, b, c, d in A:
        if x[b - 1] - x[a - 1] == c:
            temp += d
    if temp > result:
        result = temp

print(result)

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

abcdl = []
for _ in range(q):
    a,b,c,d = map(int,input().split())
    abcdl.append((a,b,c,d))

cl = []
def dfs(i):
    if len(i) == n:
        cl.append(i)
        return
    for j in range(i[-1], m+1):
        dfs(i + [j])


for i in range(1,m+1):
    dfs([i])


ans = 0
for cc in cl:
    tmp = 0
    for a,b,c,d in abcdl:
        if cc[b-1] - cc[a-1] == c:
            tmp += d
    
    ans = max(tmp, ans)

print(ans)

Solution (Python):
N, M, Q = map(int, input().split())
l = []
for i in range(Q):
  l.append(list(map(int, input().split())))

A_N = [[i] for i in range(1, M+1)]
for i in range(N-1):
  a = []
  for j in range(len(A_N)):
    last = A_N[j][-1]
    for k in range(last, M+1):
      a.append(A_N[j] + [k])
  A_N = a

high_score = 0
for i in range(len(A_N)):
  A = A_N[i]
  score = 0
  for j in range(len(l)):
    aj, bj, cj, dj = l[j]
    if A[bj-1]-A[aj-1] == cj:
      score += dj
  high_score = max(high_score, score)

print(high_score)