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:
# -*- coding: utf-8 -*-
import sys
from itertools import combinations
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

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
    tmp_l=[[i] for i in range(1,M+1)]
    next=[]
    for _ in range(N-1):
        for l in tmp_l:
            for i in range(l[-1],M+1):
                next.append(l+[i])
        tmp_l=next[:]
        next=[]
    for A in tmp_l:
        tmp=0
        for i in range(Q):
            if A[b[i]]-A[a[i]]==c[i]:
                tmp+=d[i]
        ans=max(ans,tmp)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math
import sys
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from functools import lru_cache, reduce
from heapq import heapify, heappop, heappush
from itertools import chain, combinations, permutations, product
from typing import List, Dict

# import numpy as np

sys.setrecursionlimit(10**5 + 1)
input = sys.stdin.readline
write = sys.stdout.write


def read_item(cls=int):
    return cls(input())


def read_n_item(cls=int) -> list:
    return [cls(s) for s in input().split()]


def list2d(row, col, init_val=0) -> List[list]:
    return [[init_val] * col for _ in range(row)]


MOD = 10**9 + 7
# MOD = 998244353


N, M, Q = read_n_item()
items = []
for _ in range(Q):
    items.append(read_n_item())


def calc(cur, items):
    ans = 0
    for a, b, c, d in items:
        if cur[b-1] - cur[a-1] == c:
            ans += d
    return ans


def dfs(cur, pre):
    # print(cur, pre)
    if len(cur) == N:
        return calc(cur, items)
    ans = 0
    for i in range(pre, M+1):
        cur.append(i)
        ans = max(ans, dfs(cur, i))
        cur.pop()
    return ans


print(dfs([], 1))

Submission status: Accepted

Solution code:
from sys import stdin
from sys import setrecursionlimit
from itertools import combinations_with_replacement


n,m,q = map(int,stdin.readline().rstrip().split())

abcd = [list(map(int,stdin.readline().rstrip().split())) for _ in range(q)]
abcd.sort()

maxes = 0

kazu = [i for i in range(1,m+1)]

li = list(combinations_with_replacement(kazu,n))

for i in li:
    i = list(i)
    ma = 0
    for j in abcd:
        a,b,c,d = j
        a -= 1;b -= 1
        if i[b]-i[a] == c:
            ma += d
    maxes = max(ma,maxes)
print(maxes)

Submission status: Accepted

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

max_total = 0
def check(items, l):
	global max_total
	if l == N + 1:
		total = 0
		for a, b, c, d in data:
			if items[b] - items[a] == c:
				total += d
		if max_total < total:
			max_total = total
	else:
		for i in range(items[l - 1], M + 1):
			items[l] = i
			check(items, l + 1)

items = [None] * (N + 1)
items[0] = 1
check(items, 1)

print(max_total)

Submission status: Accepted

Solution code:
n,m,q=map(int, input().split())
abcd=[list(map(int, input().split())) for i in range(q)]
from itertools import combinations_with_replacement
data=list(range(1,m+1))
prep=combinations_with_replacement(data, n)
ans=0
for p in prep:
    tmp=0
    p=sorted(list(p))
    for i in range(q):
        if p[abcd[i][1]-1]-p[abcd[i][0]-1]==abcd[i][2]:
            tmp+=abcd[i][3]
    ans=max(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
import itertools
n,m,q=map(int,input().split())
l=[list(map(int,input().split())) for i in range(q)]
x=0
for v in itertools.combinations_with_replacement(range(1,m+1),n):
  t=list(v)
  p=0
  for i in l:
    p+=(i[3]*(t[i[1]-1]-t[i[0]-1]==i[2]))
  x=max(x,p)
print(x)

Submission status: Accepted

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


def sol(list):
    res = 0
    for i in range(q):
        if list[abcd[i][1]-1] - list[abcd[i][0]-1] == abcd[i][2]:
            res += abcd[i][3]
    return res


def dfs(i, la):
    if i == n-1:
        return sol(la)
    else:
        last = 1
        if i >= 0:
            last = la[-1]
        res = 0
        for j in range(last, m+1):
            res = max(res, dfs(i+1, la+[j]))
        return res

print(dfs(-1,[]))

Submission status: Accepted

Solution code:
import itertools

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

choices = list(itertools.combinations_with_replacement([i for i in range(1, m+1)], n))
ans = -1
for choice in choices:
    score = 0
    for q in query:
        if choice[q[1]-1] - choice[q[0]-1] == q[2]:
            score += q[3]
    ans = max(ans, score)
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import sys
readline = sys.stdin.readline
read = sys.stdin.read

n,m,q = [int(i) for i in readline().split()]
abcd = [[int(i) for i in readline().split()] for _ in range(q)]
for i in range(q):
    abcd[i][0] -= 1
    abcd[i][1] -= 1

from itertools import combinations_with_replacement

ans = 0
L = range(1,m+1)
for v in combinations_with_replacement(L,n):
    res = 0
    for a,b,c,d in abcd:
        if v[b]-v[a] == c: res += d
    ans = max(ans,res)

print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations

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

ret = 0
for a in combinations(list(range(1, n + m)), n):
    a = sorted(a)
    a = [a - i for i, a in enumerate(a)]
    pret = 0
    for i in range(q):
        ai, bi, ci, di = abcd[i]
        if a[bi - 1] - a[ai - 1] == ci:
            pret += di
    ret = max(ret, pret)
print(ret)

Submission status: Accepted

Solution code:
import itertools


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

    arrays = itertools.combinations_with_replacement(range(m), n)

    def gen():
        for array in arrays:
            total = 0
            for a, b, c, d in li:
                if array[b - 1] - array[a - 1] == c:
                    total += d
            yield total

    return max(gen())


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

Submission status: Accepted

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

import itertools
ans = -1
for p in itertools.combinations_with_replacement(range(1, m+1), n):
    #print(p)
    temp = 0
    for d, c, a, b in L:
        if p[b]-p[a] == c:
            temp += d
    ans = max(ans, temp)
print(ans)

Submission status: Accepted

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


def f(i = 0, l = []):
    if i == N:
        return [l]

    t = []
    if i == 0:
        for e in range(1, M + 1):
            t += f(i+1, [e])
    else:
        for e in range(l[-1], M + 1):
            t += f(i+1, l + [e])

    return t


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

N = f()

m = 0
for n in N:
    t = 0
    for a, b, c, d in D:
        if n[b-1] - n[a-1] == c:
            t += d
    m = max(t, m)

print(m)

Submission status: Accepted

Solution code:
import sys,math,copy,queue,itertools,bisect,collections,heapq
sys.setrecursionlimit(10**7)
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
NI = lambda : int(sys.stdin.readline())
INF = 10**18
MOD = 10**9 + 7
DD = ((1,0),(-1,0),(0,1),(0,-1))

N,M,Q = LI()
req = [LI() for _ in range(Q)]
ans = 0
for a in itertools.combinations_with_replacement(range(1,M+1),N):
    cnt = 0
    for r in req:
        if a[r[1]-1] - a[r[0]-1] == r[2]: cnt+= r[3]
    ans = max(ans,cnt)
print (ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
def check(li):
    global ans
    res=0
    for i in range(Q):
        if(li[b[i]-1]-li[a[i]-1]==c[i]):
            res+=d[i]
    ans=max(ans,res)

def dfs(li,last,M):
    if(len(li)==N):
        check(li)
        return 
    l=li.copy()
    for i in range(last,M+1):
        dfs(l+[i],i,M)

import itertools
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
dfs([],1,M)
print(ans)

Submission status: Accepted

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

def calc(l):
    res = 0
    for a,b,c,d in abcd:
        if l[b-1]-l[a-1]==c:
            res += d
    # print(l,res)
    return res

def f(l):
    if len(l)==n:
        return calc(l)
    
    res = 0
    for x in range(l[-1],m+1):
        res = max(res, f(l+[x]))
    return res

res = 0
for x in range(1,m+1):
    res = max(res, f([x]))
print(res)

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 a2 in combinations_with_replacement(range(1,m+1),n-1):
    A = [0,1] + list(a2)
    score = 0
    for a,b,c,d in abcd:
        if A[b] -A[a] == c:
            score += d
    ans = max(ans,score)
    
print(ans)

Submission status: Accepted

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

abcd_dic={}
for i in range(Q):
  a,b,c,d=map(int,input().split())
  abcd_dic[(a,b,c)]=d
#print(abcd_dic)

max_answer=0
for perm in itertools.combinations_with_replacement(range(1,M+1),N):
  #print(perm)
  answer=0

  for i in range(N):
    for j in range(i+1,N):
      diff=perm[j]-perm[i]
      if (i+1,j+1,diff) in abcd_dic:
        answer+=abcd_dic[(i+1,j+1,diff)]
        
  max_answer=max(answer,max_answer)
  
print(max_answer)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline

N, M, Q, *abcd = map(int, read().split())
cand = [[0, 1]]

for _ in range(N - 1):
    new_cand = []
    for j in cand:
        for k in range(j[-1], M + 1):
            new_cand.append(j[:] + [k])
    cand = new_cand[:]

answer = 0
abcd = tuple(zip(*[iter(abcd)] * 4))
for seq in cand:
    t = 0
    for a, b, c, d in abcd:
        if seq[b] - seq[a] == c:
            t += d
    answer = max(answer, t)

print(answer)

Submission status: Accepted

Solution code:
import itertools

(N, M, Q) = [int(n) for n in input().split()]
reqs = []
for _ in range(Q):
    a, b, c, d = [int(n) for n in input().split()]
    a -= 1
    b -= 1
    reqs.append((a, b, c, d))

ans = 0

for A in itertools.combinations_with_replacement(range(1, M+1), N):
    score = 0
    for a, b, c, d in reqs:
        if A[b] - A[a] == c:
            score += d
    ans = max(score, ans)
    #print('A = {} score = {}'.format(A, score))
print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations
def main():
    N, M, Q = map( int, input().split())
    ABCD = [ tuple( map( int, input().split())) for _ in range(Q)]
    ans = 0
    for C in combinations( range(N+M-1), M-1):
        A = []
        index = 0
        now = 1
        for i in range(N+M-1):
            if index < M-1:
                if C[index] == i:
                    now += 1
                    index += 1
                    continue
            A.append(now)

        lans = 0
        for a, b, c, d in ABCD:
            if A[b-1] - A[a-1] == c:
                lans += d
        if ans < lans:
            ans = lans
    print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement

N, M, Q = list(map(int, input().split()))
Q_ = [list(map(int, input().split())) for i in range(Q)]
ans = 0
for A in combinations_with_replacement(range(1, M+1), N):
    ans = max(ans, sum([q[3] for q in Q_ if A[q[1] - 1] - A[q[0] - 1] == q[2]]))

print(ans)

Submission status: Accepted

Solution code:
def search(idx, N, mn, mx, cur, cand):
    if idx == N:
        cand.append(cur)
        return
    for i in range(mn, mx+1):
        search(idx+1, N, i, mx, cur+[i], cand)


def main():
    N, M, Q = map(int, input().split())
    conds = [None] * Q
    for i in range(Q):
        a, b, c, d = map(int, input().split())
        conds[i] = (a, b, c, d)
    candidates = []
    search(0, N, 1, M, [], candidates)
    ans = 0
    for A in candidates:
        score = 0
        for i in range(Q):
            a, b, c, d = conds[i]
            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
sys.setrecursionlimit(10 ** 7)

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

cands = []


def dfs(i, li):
    if i == n:
        return cands.append(li)

    if li:
        mn = li[-1]
    else:
        mn = 1
    for num in range(mn, m + 1):
        dfs(i + 1, li + [num])


dfs(0, [])

ans = 0
for li in cands:
    sm = 0
    for a, b, c, d in abcd:
        a -= 1
        b -= 1
        if li[b] - li[a] == c:
            sm += d

    ans = max(ans, sm)

print(ans)

Submission status: Accepted

Solution code:
def Int():
    return int(input())
def Ints():
    return map(int,input().split())
def IntList():
    return list(Ints())
def IntMat(N):
    return [IntList() for i in range(N)]

N,M,Q = Ints()
List = []

for i in range(Q):
    a,b,c,d = Ints()
    List.append([a,b,c,d])
    
import itertools
Num = [i for i in range(N+M-1)]
Ans = 0

for i in itertools.combinations(Num, N):
    TMP = []
    now = 1
    pre = -1
    for j in i:
        TMP.append(now+j-pre-1)
        now = now+j-pre-1
        pre = j
    #print(TMP)
    
    Tensuu = 0
    for (a,b,c,d) in List:
        if TMP[b-1]-TMP[a-1] == c:
            Tensuu += d
    Ans = max(Ans, Tensuu)
print(Ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

ret = -float('inf')
def dfs(A, cur, depth) :
  if depth == N :
    s = 0
    for a, b, c, d in abcd :
      a, b = a - 1, b - 1
      if A[b] - A[a] == c :
        s += d
    global ret
    ret = max(ret, s)
    return 
      
  for nex in range(cur, M + 1) :
    dfs(A + [nex], nex, depth + 1)
    
dfs([], 1, 0)

print(ret)

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement

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

ABCD = []
for _ in range(Q):
    a, b, c, d = map(int, input().split())
    a, b = a - 1, b - 1  # 0-indexed
    ABCD.append((a, b, c, d))

ans = 0
for combi in combinations_with_replacement(list(range(1, M + 1)), N):
    # print(combi)
    s = 0
    for a, b, c, d in ABCD:
        if combi[b] - combi[a] == c:
            # print('a, b, c, d', a, b, c, d)
            s += d
    # print('s', s)
    ans = max(ans, s)
print(ans)

Submission status: Accepted

Solution code:
n,m,q = map(int, input().split())
rq=list()
for i in range(q):
    a,b,c,d = map(int, input().split())
    a-=1
    b-=1
    rq.append([a,b,c,d])
ans=0
def solve(A,ans):

    if len(A)==n:
        score=0
        for a,b,c,d in rq:
            if A[b]-A[a]==c:
                score+=d
        ans=max(ans,score)
        return ans
    else:
        for i in range(1,m+1):
            if len(A)>=1 and A[-1]>i:
                continue
            B = A + [i]
            ans = max(ans,solve(B,ans))
        return ans

ans= solve(list(),ans)
print(ans)

Submission status: Accepted

Solution code:
import itertools

n, m, q = list(map(int, input().split()))
data = [list(map(int, input().split())) for i in range(q)]
a, b, c, d = [[], [], [], []]
for i in range(q):
    a.append(data[i][0])
    b.append(data[i][1])
    c.append(data[i][2])
    d.append(data[i][3])

maxpoint = 0
for x in itertools.combinations_with_replacement(range(1, m+1), n):
    point = 0
    for i in range(q):
        if x[b[i]-1] - x[a[i]-1] == c[i]:
            point += d[i]
    maxpoint = max(point, maxpoint)

print(maxpoint)

Submission status: Accepted

Solution code:
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):
    global cl
    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
    # print(tmp)
    ans = max(tmp, ans)

print(ans)

Submission status: Accepted

Solution code:
import sys
from itertools import combinations_with_replacement

def solve():
    input = sys.stdin.readline
    N, M, Q = map(int, input().split())
    E = [[int(c) for c in input().split()] for _ in range(Q)]
    maxPoint = 0
    for l in combinations_with_replacement(range(1, M + 1), N):
        point = 0
        #print(l)
        for a, b, c, d in E:
            if l[b-1] - l[a-1] == c: point += d
        maxPoint = max(maxPoint, point)
    print(maxPoint)
    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import itertools

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

Max = 0
for C in itertools.combinations_with_replacement(range(1, M + 1), N):
  score = sum([d for a, b, c, d in abcd if C[b-1] - C[a-1] == c])
  Max = max(Max, score)
print(Max)

Submission status: Accepted

Solution code:
import itertools

N,M,Q=map(int,input().split())
a=[]
b=[]
c=[]
d=[]
for i in range(Q):
  a1,b1,c1,d1=map(int,input().split())
  a.append(a1)
  b.append(b1)
  c.append(c1)
  d.append(d1)

point=0
x=list(itertools.combinations_with_replacement(range(M), N))
for y in x:
  temppoint=0
  for i in range(Q):
    if(y[b[i]-1]-y[a[i]-1]==c[i]):
      temppoint+=d[i]
  point=max(point,temppoint)
print(point)

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement

N, M, Q = map(int, input().split())
reqs = [tuple(map(int, input().split())) for _ in range(Q)]
ans = 0
for A in combinations_with_replacement(range(1, M + 1), N):
    temp = 0
    for a, b, c, d in reqs:
        a, b = a - 1, b - 1
        if A[b] - A[a] == c: temp += d
    ans = max(ans, temp)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(2 * 10**6)


def inpl():
    return list(map(int, input().split()))


back = []


def backtrack(n, ml, mh, tmp=[]):
    if n == 0:
        back.append(tmp)
        return

    for i in range(ml, mh + 1):
        backtrack(n - 1, i, mh, tmp + [i])


def main():
    def count(carrer):
        ret = 0
        for a, b, c, d in abcd:
            if carrer[b - 1] - carrer[a - 1] == c:
                ret += d
        return ret
    N, M, Q = inpl()
    ans = 0
    abcd = [inpl() for _ in range(Q)]
    backtrack(N, 1, M)
    for carrer in back:
        # print(carrer)
        tmp = count(carrer)
        if tmp > ans:
            ans = tmp
    print(ans)


if __name__ == '__main__':
    main()

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)]
N=[i+1 for i in range(m)]

cnt=0
for A in combinations_with_replacement(N,n):
    point=0
    for a,b,c,d in ABCD:
        if A[b-1]-A[a-1]==c:
            point +=d
    cnt=max(cnt,point)
print(cnt)

Submission status: Accepted

Solution code:
import itertools

n, m, q = map(int, input().split())
abcds = [tuple(map(int, input().split())) for _ in range(q)]
x = [(i + 1) for i in range(m)]
ans = 0
for elem in itertools.combinations_with_replacement(x, n):
    rep = 0
    for i in range(q):
        if elem[abcds[i][1] - 1] - elem[abcds[i][0] - 1] == abcds[i][2]:
            rep += abcds[i][3]
    ans = max(ans, rep)
print(ans)

Submission status: Accepted

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

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

heap = [[i] for i in range(1, m+1)]

for i in range(n-1):
    nxt = []
    for l in heap:
        for j in range(l[-1], m+1):
            k = l[:]
            k.append(j)
            nxt.append(k)
    heap = nxt

ans = 0
for l in heap:
    tmp = 0
    for a,b,c,d in abcd:
        if l[b-1]-l[a-1] == c:
            tmp += d
    if tmp > ans:
        ans = tmp
print(ans)

Submission status: Accepted

Solution code:
mod = 1000000007
eps = 10**-9


def main():
    import sys
    from math import factorial
    from itertools import combinations_with_replacement
    input = sys.stdin.readline

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

    ans = 0
    L = list(range(1, M+1))
    for v in combinations_with_replacement(L, N):
        V = list(v)
        tmp = 0
        for a, b, c, d in query:
            if V[b-1] - V[a-1] == c:
                tmp += d
        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import math  # noqa
import bisect  # noqa
import queue  # noqa


def input():
    return sys.stdin.readline().rstrip()


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

    ans = 0
    for a0 in range(1, M + 1):
        for a1 in range(a0, M + 1):
            for a2 in range(a1, M + 1):
                for a3 in range(a2, M + 1):
                    for a4 in range(a3, M + 1):
                        for a5 in range(a4, M + 1):
                            for a6 in range(a5, M + 1):
                                for a7 in range(a6, M + 1):
                                    for a8 in range(a7, M + 1):
                                        for a9 in range(a8, M + 1):
                                            array = [a0, a1, a2, a3,
                                                     a4, a5, a6, a7, a8, a9]
                                            res = 0
                                            for i in range(Q):
                                                if array[B[i]] - array[A[i]] == C[i]:
                                                    res += D[i]
                                            ans = max(ans, res)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float("INF")

#solve
def solve():
    n, m, q = LI()
    abcd = LIR(q)
    ans = 0
    fulls = itertools.combinations_with_replacement(range(m),n)
    for full in fulls:
        tmp = 0
        for a, b, c, d in abcd:
            if full[b-1] - full[a-1] == c:
                tmp += d
        ans = max(tmp, ans)
    print(ans)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement

def main():
    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-1)
        b.append(_b-1)
        c.append(_c)
        d.append(_d)
    ans = 0
    for A in combinations_with_replacement(range(M), N):
        # print(A)
        tmp = 0
        for i in range(Q):
            if A[b[i]] - A[a[i]] == c[i]:
                tmp += d[i]
        ans = max(ans, tmp)
    print(ans)
    return
main()

Submission status: Accepted

Solution code:

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

abcd = tuple(tuple(map(int,input().split())) for _ in range(Q))

A = [1]

def rec():
    if len(A) == N:
        return sum(d for a,b,c,d in abcd if A[b-1] == A[a-1]+c)

    t = 0
    for x in range(A[-1],M+1):
        A.append(x)
        t = max(t, rec())
        A.pop()
    return t

print(rec())

Submission status: Accepted

Solution code:
def rec(X, N, M, queries):
    if len(X) == N:
        ret = 0
        for a, b, c, d in queries:
            ret += (c == (X[b] - X[a])) * d
        return ret
    ret = 0
    start = X[-1] if len(X) > 0 else 1
    for i in range(start, M+1):
        X.append(i)
        ret = max(ret, rec(X, N, M, queries))
        X.pop()
    return ret


def main() -> None:
    N, M, Q = map(int, input().split())
    queries = []
    for _ in range(Q):
        a, b, c, d = map(int, input().split())
        queries.append((a-1, b-1, c, d))
    print(rec([], N, M, queries))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def cur(x):

    if len(x)<n+1:
        ans=0
        for i in range(x[-1],m+1):
            ans=max(ans,cur(x+[i]))
    else:
        ans=0
        for i in range(q):
            [a,b,c,d]=l[i]
            if x[b]-x[a]==c: ans+=d
    return ans

n,m,q=map(int,input().split())
l=[list(map(int,input().split())) for i in range(q)]
print(cur([1]))

Submission status: Accepted

Solution code:
from itertools import combinations_with_replacement
n,m,q = map(int, input().split())
data = []
ans = 0
for i in range(q):
    data.append(list(map(int, input().split())))
for array in combinations_with_replacement(range(1,m+1),n):
    count = 0
    array = list(array)
    array.sort()
    for i in range(q):
        if array[data[i][1]-1] - array[data[i][0]-1] == data[i][2]:
            count += data[i][3]
    ans = max(ans, count)
print(ans)

Submission status: Accepted

Solution code:
N, M, Q = map(int, input().split())
a,b,c,d = [],[],[],[]
for _ in range(Q):
    ta, tb, tc, td = map(int, input().split())
    a.append(ta)
    b.append(tb)
    c.append(tc)
    d.append(td)

def solve(S):
    out = 0
    for i in range(Q):
        if (S[b[i]-1] - S[a[i]-1]) == c[i]:
            out += d[i]

    return out

def bfs(S,cnt):
    ans = 0
    if cnt == N:
        return solve(S)
    
    for i in range(S[-1], M+1):
        ans = max(ans, bfs(S + [i], cnt + 1))

    return ans

answer = 0
for i in range(1,M+1):
    answer = max(answer, bfs([i], 1))

print(answer)

Submission status: Accepted

Solution code:
import itertools

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

nums = [(i+1) for i in range(m)]
ans = 0
for balls in itertools.combinations_with_replacement(nums, n):
    tp = 0
    # print(balls)
    for i in range(q):
        if balls[sc[i][1]-1]-balls[sc[i][0]-1] == sc[i][2]:
            tp += sc[i][3]
    if tp > ans:
        ans = tp

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)

N, M, Q = map(int, input().split())
abcds = []
for _ in range(Q):
    a, b, c, d = map(int, input().split())
    a, b = a-1, b-1
    abcds.append((a, b, c, d))

def check():
    score = 0
    for a, b, c, d in abcds:
        if As[b]-As[a] == c:
            score += d
#    print(As, score)
    return score

def dfs(i, mx):
    if i == N:
        return check()
    score = 0
    for x in range(mx, M+1):
        As[i] = x
        s = dfs(i+1, x)
        if s > score:
            score = s
    return score

As = [0] * N
ans = dfs(0, 1)

print(ans)

Submission status: Accepted

Solution code:
n,m,q = map(int, input().split())
abcd=[list(map(int,input().split())) for i in range(q)]

def calc(lis):
    ret=0
    for tmp in abcd:
        a,b,c,d=tmp
        a-=1
        b-=1
        if lis[b]-lis[a] == c:
            ret+=d
    return ret

ans=0
from itertools import *
for lis in combinations_with_replacement(range(1,m+1),n):
    ret =calc(lis)
    ans=max(ans,ret)

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline

from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict
from itertools import combinations, permutations
from itertools import accumulate
from math import ceil, sqrt, pi

MOD = 10 ** 9 + 7
INF = 10 ** 18


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

lst = []

def dfs(i, n, tmp):
    if n == N:
        lst.append(tmp)
        return 0
    for j in range(i, M + 1):
        dfs(j, n + 1, tmp + [j])

dfs(1, 0, [])
#print(lst)

ans = 0
for l in lst:
    tmp = 0
    for abcd in ABCD:
        a, b, c, d = abcd
        if l[b - 1] - l[a - 1] == c:
            tmp += d
    ans = max(tmp, ans)
    
print(ans)

Submission status: Accepted

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

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

MAX=0
for i in l:
    ans=0
    for g in range(q):
        a,b,c,d = Q[g]
        if i[b-1]-i[a-1]==c:
            ans+=d
    MAX=max(ans,MAX)
print(MAX)