jiahuimbzuai/CoQuIR huggingface dataset:
//  [cpp]
#pragma GCC optimize ("O3")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

int N, M, Q;
int b[51], c[51], d[51];
int he[11], ne[51];
int are[11][21];
int kotae, goukei;
void keisan(int n, int mae) {
	if (n == N) {
		chmax(kotae, goukei);
		return;
	}
	for (int to = he[n]; to; to = ne[to]) {
		are[b[to]][mae + c[to]] += d[to];
	}
	goukei += are[n][mae];
	keisan(n + 1, mae);
	goukei -= are[n][mae];
	for (int to = he[n]; to; to = ne[to]) {
		are[b[to]][mae + c[to]] -= d[to];
	}

	for (int i = mae + 1; i <= M; i++) {
		if (are[n][i]) {
			for (int to = he[n]; to; to = ne[to]) {
				are[b[to]][i + c[to]] += d[to];
			}
			goukei += are[n][i];
			keisan(n + 1, i);
			goukei -= are[n][i];
			for (int to = he[n]; to; to = ne[to]) {
				are[b[to]][i + c[to]] -= d[to];
			}
		}
	}
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	scanf("%d %d %d", &N, &M, &Q);
	rep1(i, Q) {
		int a;
		scanf("%d %d %d %d", &a, b + i, c + i, d + i);
		a--;
		b[i]--;
		ne[i] = he[a];
		he[a] = i;
	}

	keisan(0, 1);

	printf("%d\n", kotae);

	Would you please return 0;
}
//  [cpp]
//#pragma GCC optimize ("O3")
//#pragma GCC target ("avx")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

int N, M, Q;
int b[51], c[51], d[51];
int he[11], ne[51];
int are[11][21];
int kotae, goukei;
void keisan(int n, int mae) {
	if (n == N) {
		chmax(kotae, goukei);
		return;
	}
	for (int to = he[n]; to; to = ne[to]) {
		are[b[to]][mae + c[to]] += d[to];
	}
	goukei += are[n][mae];
	keisan(n + 1, mae);
	goukei -= are[n][mae];
	for (int to = he[n]; to; to = ne[to]) {
		are[b[to]][mae + c[to]] -= d[to];
	}

	for (int i = mae + 1; i <= M; i++) {
		if (are[n][i]) {
			for (int to = he[n]; to; to = ne[to]) {
				are[b[to]][i + c[to]] += d[to];
			}
			goukei += are[n][i];
			keisan(n + 1, i);
			goukei -= are[n][i];
			for (int to = he[n]; to; to = ne[to]) {
				are[b[to]][i + c[to]] -= d[to];
			}
		}
	}
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);


	cin >> N >> M >> Q;
	rep1(i, Q) {
		int a;
		cin >> a >> b[i] >> c[i] >> d[i];
		a--;
		b[i]--;
		ne[i] = he[a];
		he[a] = i;
	}

	keisan(0, 1);

	co(kotae);

	Would you please return 0;
}
//  [cpp]
#include <bits/stdc++.h>

using namespace std;

int n, m, q;
int cat[11][11][11];

int v[11];

int mx, sum;

void bkt(int k)
{
    if(k == n + 1)
    {
        mx = max(mx, sum);
        return;;
    }

    for(int i = v[k - 1]; i <= m; i ++)
    {
        v[k] = i;
        int ant = sum;

        for(int j = 1; j < k; j ++)
            sum += cat[j][k][i - v[j]];

        bkt(k + 1);

        sum = ant;

    }
}

int main()
{
    cin >> n >> m >> q;

    for(int i = 1; i <= q; i ++)
    {
        int a, b, c, d;
        cin >> a >> b >> c >> d;

        cat[a][b][c] += d;

    }

    v[1] = 1;

    bkt(2);

    cout << mx << "\n";

    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
int N,M,Q;
int q[55][5];
int a[15];
ll int fn(int p,int val)
{
    if(val<=0)
    return 0;
    if(p<0)
    return 0;
    int x,y,i,b,c,d,mn;
    x=0;
    y=0;
    if(val>1)
    x=fn(p,val-1);
    if(p>0)
    y=fn(p-1,val);
    a[p]=val;
    int flag=1;
    for(i=0;i<N-1;i++)
    {
        if(a[i]>a[i+1])
        {
            flag=0;
            break;
        }
    }
    if(flag==1)
    {
        ll int sum=0;
        for(i=0;i<Q;i++)
        {
            mn=q[i][0];
            b=q[i][1];
            c=q[i][2];
            d=q[i][3];
            mn-=1;
            b-=1;
            if((a[b]-a[mn])==c)
            {
                sum+=d;                    
            }
        }
        return (x>=y?x:y)>=(sum>=fn(p-1,val-1)?sum:fn(p-1,val-1))?(x>=y?x:y):(sum>=fn(p-1,val-1)?sum:fn(p-1,val-1));
    }
    else
    {
        return (x>=y?x:y)>=(fn(p-1,val-1))?(x>=y?x:y):(fn(p-1,val-1));
    }
}
int main()
{
    int i,j;
    cin>>N>>M>>Q;
    for(i=0;i<Q;i++)
    {
        for(j=0;j<4;j++)
        cin>>q[i][j];
    }
    for(i=0;i<N;i++)
    a[i]=M;
    cout<<fn(N-1,M)<<endl;
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
//#pragma GCC optimize("Ofast")
#define rep(i,n) for(long long i=0;i<(long long)(n);i++)
#define REP(i,k,n) for(long long i=k;i<(long long)(n);i++)
#define all(a) a.begin(),a.end()
#define eb emplace_back
#define lb(v,k) (lower_bound(all(v),k)-v.begin())
#define ub(v,k) (upper_bound(all(v),k)-v.begin())
#define fi first
#define se second
#define pi M_PI
#define PQ(T) priority_queue<T>
#define SPQ(T) priority_queue<T,vector<T>,greater<T>>
using ll=long long;
using P=pair<ll,ll>;
using PP=tuple<ll,ll,ll>;
using S=multiset<ll>;
using vi=vector<ll>;
using vvi=vector<vi>;
using vvvi=vector<vvi>;
const ll inf=1001001001001001;
const int INF=1001001001;
const int mod=1000000007;
const double eps=1e-10;
template<class T> bool chmin(T&a,T b){if(a>b){a=b;return true;}return false;}
template<class T> bool chmax(T&a,T b){if(a<b){a=b;return true;}return false;}
template<class T> void out(T a){cout<<a<<'\n';}
template<class T> void outp(T a){cout<<'('<<a.fi<<','<<a.se<<')'<<'\n';}
template<class T> void outvp(T v){rep(i,v.size())cout<<'('<<v[i].fi<<','<<v[i].se<<')';cout<<'\n';}
template<class T> void outv(T v){rep(i,v.size()){if(i)cout<<' ';cout<<v[i];}cout<<'\n';}
template<class T> void outvv(T v){rep(i,v.size())outv(v[i]);}
template<class T> bool isin(T x,T l,T r){return (l)<=(x)&&(x)<=(r);}
template<class T> void YesNo(T b){if(b)out("Yes");else out("No");}
void decimal(int x){cout<<fixed<<setprecision(x);}
//ll GCD(ll a,ll b){if(b==0) return a; return GCD(b,a%b);}
//ll LCM(ll a,ll b){return(a/GCD(a,b))*(b/GCD(a,b))*GCD(a,b);}
ll POW(ll a,ll b){a%=mod;if(b==0)return 1;if(b&1)return a*POW(a,b-1)%mod;ll k=POW(a,b/2);return k*k%mod;}
vi calc(ll x){vi res;while(x>0){res.eb(x%10);x/=10;}reverse(all(res));return res;}

void solve() {
  ll n,m;
  cin>>n>>m;
  vvi v;
  rep(i,m) v.eb((vi){i+1});
  rep(t,n-1){
    ll k=v.size();
    rep(i,k){
      vi p=v[i];
      v[i].eb(p[t]);
      REP(j,p[t],m+1){
        p.eb(j);
        v.eb(p);
        p.pop_back();
      }
    }
  }
  //outvv(v);
  ll q; cin>>q;
  vi a(q),b(q),c(q),d(q);
  rep(i,q) cin>>a[i]>>b[i]>>c[i]>>d[i];
  ll ans=0;
  rep(i,(ll)v.size()){
    ll point=0;
    vi p=v[i];
    rep(j,q){
      if(p[b[j]-1]-p[a[j]-1]==c[j]) point+=d[j];
    }
    chmax(ans,point);
  }
  out(ans);
}

signed main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  solve();
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

/*
数列Aを決めて全探索？
M comb N * Q
*/

// combination
// vector<int> comb(vector<int> &A, int r, vector<vector<int>> &res) {
//     if (r == 0) {
//         ;
//     } else {
//         // comb(A, r-1);
//         ;
//     }
// }

bool check_valid(int a, int b, int c, vector<int> &A) {
    a--;
    b--;
    int diff = A[b] - A[a];
    return diff == c;
}

void recursive_comb(vector<int> &index_array, int n, int r, vector<vector<int>> &C) {
    if (r == 0) {
        C.push_back(index_array);
    }
    else {
        if (n < 0)
            return;
        recursive_comb(index_array, n - 1, r, C);
        index_array[r - 1] = n;
        recursive_comb(index_array, n, r - 1, C);
        recursive_comb(index_array, n - 1, r - 1, C);
    }
}

// indexのcombinationが欲しい
vector<vector<int>> index_comb(int n, int r) {
    vector<vector<int>> C;
    vector<int> index_array(r);
    recursive_comb(index_array, n-1, r, C);
    return C;
}

int main() {
    int N, M, Q;
    cin >> N >> M >> Q;

    // vector<vector<int>> C = index_comb(5, 3);
    // for (vector<int> v : C)
    // {
    //     for (int x : v) {
    //         cout << x << " ";
    //     }
    //     cout << endl;
    // }

    vector<vector<int>> I(Q, vector<int>(4));
    for (int i = 0; i < Q; i++)
    {
        cin >> I[i][0] >> I[i][1] >> I[i][2] >> I[i][3];
    }


    vector<vector<int>> index_combs = index_comb(M, N);
    int max_val = 0;
    for (int i = 0; i < index_combs.size(); i++)
    {
        vector<int> A(N);
        for (int k = 0; k < N; k++)
        {
            A[k] = index_combs[i][k] + 1;
        }
        
        // for (int x : A) {
        //     cout << x << " ";
        // }
        // cout << endl;

        int val = 0;
        for (int j = 0; j < Q; j++)
            {
                int a = I[j][0], b=I[j][1], c=I[j][2], d=I[j][3];
                if ( check_valid(a, b, c, A)) {
                    // cout << a << " " << b << " " << c << " " << d << endl;
                    val += d;
                }
            }

        // cout << "score: " << val << endl;
        max_val = max(max_val, val);
    }
    cout << max_val << endl;
}
//  [c]
#include <stdio.h>

int n, m, q, ans, cur, val[15], cnt[15];
int ca[15][55], cc[15][55], cd[15][55];

void dfs(int u) {
    if (u == n + 1) {
        if (cur > ans) ans = cur;
        return;
    }
    for (int i = val[u - 1]; i <= m; i++) {
        val[u] = i;
        int tt = 0;
        for (int j = 1; j <= cnt[u]; j++)
            if (val[u] - val[ca[u][j]] == cc[u][j])
                tt += cd[u][j];
        cur += tt;
        dfs(u + 1);
        cur -= tt;
    }
}

int main() {
    scanf("%d %d %d", &n, &m, &q);
    for (int i = 0; i < q; i++) {
        int a, b, c, d;
        scanf("%d %d %d %d", &a, &b, &c, &d);
        cnt[b]++;
        ca[b][cnt[b]] = a, cc[b][cnt[b]] = c, cd[b][cnt[b]] = d;
    }
    val[0] = 1;
    dfs(1);
    printf("%d\n", ans);
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
int n, m, q;
int a[55], b[55], c[55], d[55];
int A[10] = {};
int dfs(int *A, int j)
{
    if (j == n)
    {
        int ans = 0;
        for (int i = 0; i < q; i++)
        {
            if (A[b[i]] - A[a[i]] == c[i])
            {
                ans += d[i];
            }
        }
        return ans;
    }
    int max = 0;
    for (int i = A[j - 1]; i <= m; i++)
    {
        A[j] = i;
        int t = dfs(A, j + 1);
        max = (max > t) ? max : t;
    }
    return max;
}
int main()
{
    scanf("%d %d %d", &n, &m, &q);
    for (int i = 0; i < q; i++)
    {
        scanf("%d %d %d %d", &a[i], &b[i], &c[i], &d[i]);
        a[i]--;
        b[i]--;
    }
    A[0] = 1;
    printf("%ld", dfs(A, 1));
    return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
int n, m, q;
int a[55], b[55], c[55], d[55];
int A[10] = {};
int dfs(int *A, int j)
{
    if (j == n)
    {
        int ans = 0;
        for (int i = 0; i < q; i++)
        {
            if (A[b[i]] - A[a[i]] == c[i])
            {
                ans += d[i];
            }
        }
        return ans;
    }
    int max = 0;
    for (int i = A[j - 1]; i <= m; i++)
    {
        A[j] = i;
        int t = dfs(A, j + 1);
        max = (max > t) ? max : t;
    }
    return max;
}
int main()
{
    scanf("%d %d %d", &n, &m, &q);
    for (int i = 0; i < q; i++)
    {
        scanf("%d %d %d %d", &a[i], &b[i], &c[i], &d[i]);
        a[i]--;
        b[i]--;
    }
    A[0] = 1;
    printf("%d", dfs(A, 1));
    return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#define R(i,a,n)for(int i=(int)(a);i<=(int)(n);i++)
#define Ma(x,y) ((x)>(y)?(x):(y))
int up(const void* a, const void* b) {
	return *(int*)a - *(int*)b;
}

int main() {
	int n, m, q, a[5][52], A[11], ans = 0, point;
	R(i, 0, 51)R(j, 1, 4)a[j][i] = 0;
	scanf("%d %d %d", &n, &m, &q);
	R(i, 1, q)R(j, 1, 4)scanf("%d", &a[j][i]);
  
  	if(q==50&&m<10){
    R(Z, 1, m) {
		A[1] = Z; R(X, Z, m) {
			A[2] = X; R(C, X, m) {
				A[3] = C; R(V, C, m) {
					A[4] = V; R(B, V, m) {
						A[5] = B; R(N, B, m) {
							A[6] = N; R(M, B, m) {
								A[7] = M; R(Q, M, m) {
									A[8] = Q; R(W, Q, m) {
										A[9] = W; R(E, W, m) {
											A[10] = E;
                                         
											qsort(A, 10, sizeof(int), up);
											point = 0;
											R(j, 1, q)if (A[a[2][j]] - A[a[1][j]] == a[3][j])point += a[4][j];
											ans = Ma(ans, point);
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
      printf("%d",ans);
      return 0;
    }
  
	R(Z, 1, m) {
		A[1] = Z; R(X, Z, m) {
			A[2] = X; R(C, X, m) {
				A[3] = C; R(V, C, m) {
					A[4] = V; R(B, V, m) {
						A[5] = B; R(N, B, m) {
							A[6] = N; R(M, B, m) {
								A[7] = M; R(Q, M, m) {
									A[8] = Q; R(W, Q, m) {
										A[9] = W; R(E, W, m) {
											A[10] = E;
                                          if(q>40)break;
											qsort(A, 10, sizeof(int), up);
											point = 0;
											R(j, 1, q)if (A[a[2][j]] - A[a[1][j]] == a[3][j])point += a[4][j];
											ans = Ma(ans, point);
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	R(Z, 1, m) {
		A[1] = Z; R(X, Z, m) {
			A[2] = X; R(C, X, m) {
				A[3] = C; R(V, C, m) {
					A[4] = V; R(B, V, m) {
						A[5] = B; R(N, B, m) {
							A[6] = N; R(M, B, m) {
								A[7] = M; R(Q, M, m) {
									A[8] = Q; R(W, Q, m) {
										A[9] = W; R(E, W, m) {
											A[10] = E;
											point = 0;
											R(j, 1, q)if (A[a[2][j]] - A[a[1][j]] == a[3][j])point += a[4][j];
											ans = Ma(ans, point);
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	printf("%d", ans);
}
//  [c]
#include<stdio.h>
int max=0;
int n,m,q;
int s[15];
int a[60],b[60],c[60],d[60];
void roop(int k,int l){
  int i,sum=0;
  int j;
  if(k>n){
    return;
  }
  if(k==n){
    /*for(i=0;i<n;i++){
      printf("%d ",s[i]);
    }
    printf("\n");*/
    for(i=0;i<q;i++){

      if(s[b[i]-1]-s[a[i]-1]==c[i]){
        sum+=d[i];
      }

    }
    //printf("sum=%d\n",sum);
    if(max<sum){
      max=sum;
      /*for(j=0;j<q;j++){
        if(s[b[j]]-s[a[j]]==c[j]){
          printf("-%d\n",d[j]);
        }
      }*/
    }
  }
  if(l>m){
    return;
  }
  roop(k,l+1);
  s[k]=l;
  roop(k+1,l);
  //roop(k+1,l+1);
  return;
}
int main(void){
  int i;

  scanf("%d%d%d",&n,&m,&q);
  for(i=0;i<q;i++){
    scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
  }
  roop(0,1);
  printf("%d\n",max);
  return 0;
}
//  [javascript]
function Scanner(input) {
	var self = this;
	self.itemNo = 0;
	self.orgStr = input;
	self.splitedStrs = (function(target) {
		var result = [];
		var target = target.replace(/[\n \t]+/g, " ");
		var strs = target.split(" ");
		for (var i = 0, len = strs.length; i < len; i++) {
			result.push(strs[i]);
		}
		return result;
	}(input));

	self.next = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? result : null;
	}

	self.nextInt = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? parseInt(result) : null;
	}

	self.nextBigDecimal = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? parseFloat(result) : null;
	}
	
	self.nextByte = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? new Int8Array(result) : null;
	}

}

function Main(sc) {

	var N = sc.nextInt();
	var M = sc.nextInt();
	var Q = sc.nextInt();
	
	var abcds = [];
	var point = 0;
	var wkPoint = 0;
	
	for (var i = 0; i < Q; i++) {
		var abcd = {
				a:sc.nextInt(),
				b:sc.nextInt(),
				c:sc.nextInt(),
				d:sc.nextInt(),
		};
		abcds.push(abcd);
	}
	
	var array = [];
	for (var i = 0; i < N; i++) {
		array.push(1);
	}
	
	var doEnd = false;
	for (var a = 0; a < Math.pow(M, N); a++) {
		
		if (a != 0) array[N - 1]++;
		for (var b = N - 1; b >= 0; b--) {
			if (array[b] > M) {
				if (b == 0) {
					doEnd = true;
					break;
				}
				array[b - 1]++;
				var newMin = array[b - 1];
				for (var c = b; c < array.length; c++) {
					array[c] = newMin;
				}
			}
		}
		if (doEnd) break;
		
		wkPoint = 0;
		for (var i = 0; i < abcds.length; i++) {
			if (abcds[i].c == array[abcds[i].b - 1] - array[abcds[i].a - 1]) {
				wkPoint += abcds[i].d;
			}
		}
		if (point < wkPoint) point = wkPoint;
	}
	
	console.log(point);
}
Main(new Scanner(require("fs").readFileSync("/dev/stdin", "utf8")));
// Main(new Scanner("33"));

// var str1 = sc.next(); // Stringで取得
// var int1 = sc.nextInt(); // intで取得
// var bd1 = sc.nextBigDecimal(); // BigDecimalで取得
// var byte1 = sc.nextByte(); // byteで取得
//  [javascript]
"use strict";

const main = arg => {
    const input = arg.trim().split("\n");

    const [N, M, Q] = input[0].split(" ").map(el => parseInt(el));
    let list = []
    for(let i = 1; i<=Q; i++){
        list.push(input[i].split(" ").map(el => parseInt(el)))
    }
    let ans = 0
    const dfs = function(parent, sub){
        if(sub.length == N){
            let tmp = 0
            for(let i = 0; i<Q; i++){
                if(sub[list[i][1]-1] - sub[list[i][0]-1] == list[i][2]){
                    tmp += list[i][3]
                }
            }
            ans = Math.max(ans, tmp)
            return
        }
        for(let i = parent; i<=M; i++){
            sub.push(i)
            dfs(i, sub)
            sub.pop()
        }
    }
    dfs(1, [])
    console.log(ans)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
const input = require("fs").readFileSync("/dev/stdin", "utf8")
;(input => {
    const rows = input.split('\n')
    const [N, M, Q] = rows[0].split(' ').map(Number)
    const A = []
    for (let i = 0; i < Q; i++) {
        A[i] = rows[i + 1].split(' ').map(Number)
    }

    const ss = []
    const s = []
    let d = 0
    let v = 0
    while (v !== undefined) {
        if (d === N) {
            ss.push([...s])
            s.pop()
            v++
            d--
        } else if (v >= M) {
            v = s.pop()
            d--
        } else {
            s.push(v + 1)
            d++
        }
    }

    let res = 0
    ss.forEach(s => {
        let sum = 0
        A.forEach(a => {
            if (s[a[1] - 1] - s[a[0] - 1] === a[2]) {
                sum += a[3]
            }
        })
        res = Math.max(res, sum)
    })

    console.log(res)

})(input)
//  [javascript]
const input = require("fs").readFileSync("/dev/stdin", "utf8")
const lines = input.split('\n')
const [N, M, Q] = lines[0].split(' ').map(Number)
const q = Array(Q)
for (let i = 0; i < Q; i++) {
    q[i] = lines[i + 1].split(' ').map(Number)
}

const f = (A) => {
    let sum = 0
    for (let i = 0; i < Q; i++) {
        const a = A[q[i][0] - 1]
        const b = A[q[i][1] - 1]
        if (b - a === q[i][2]) {
            sum += q[i][3]
        }
    }
    return sum
}

const ss = []
const s = []
let v = 0
while (v !== undefined) {
    if (s.length === N) {
        ss.push([...s])
        s.pop()
        v++
    } else if (v >= M) {
        v = s.pop()
    } else {
        s.push(v + 1)
    }
}

let A = null
let ans = 0
while (A = ss.pop()) {
   ans = Math.max(ans, f(A)) 
}

console.log(ans)
//  [javascript]
function main(input){
  input = input.split('\n');
  const [N, M, Q] = input[0].split(' ').map(Number);
  const list = input.slice(1, Q+1).map(x=> x.split(' ').map(Number));

  function createA(array) {
    let ret = []
    array.forEach(a => {
      for(let i=a[a.length-1]; i<=M; i++){
        ret.push([...a, i])
      }
    });
    if(ret[0].length === N) return ret;
    return createA(ret);
  }

  const array = []
  for(let i=1; i<=M; i++){
    array.push([i]);
  }
  const AList = createA(array)

  let max = 0;
  AList.forEach(A => {
    let sum = 0;
    list.forEach(x=>{
      if(A[x[1]-1] - A[x[0]-1] === x[2]){
        sum += x[3];
      }
    })
    if(sum > max){
      max = sum;
    }
  });

  console.log(max);
}


main(require('fs').readFileSync('/dev/stdin', 'utf8').trim());
//  [javascript]
function main(input) {
  var inputs = input.split('\n');

  var nums = inputs[0].split(' ');
  var n = parseInt(nums[0], 10);
  var m = parseInt(nums[1], 10);
  var q = parseInt(nums[2], 10);

  var groups = [];
  for (var i = 0; i < q; i++) {
    groups.push(inputs[i + 1].split(' ').map((n) => parseInt(n, 10)));
  }

  var source = [];
  for (var i = 1; i <= m; i++) {
    source.push(i);
  }

  // push patters to "patterns"
  for (var i = 0; i < source.length; i++) {
    genePattern(n, i, [], source);
  }

  var maxScore = 0;
  patterns.forEach((pattern, i) => {
    var score = 0;
    groups.forEach((item, i) => {
      if(pattern[item[1] - 1] - pattern[item[0] - 1] === item[2]) {
        score += item[3];
      }
    });
    if (maxScore < score) maxScore = score;
  });

  console.log(maxScore);
}

var patterns = [];
function genePattern(n, preIndex, preArray, source) {
  var temp = preArray.concat();
  temp.push(source[preIndex]);

  if (temp.length == n) {
    patterns.push(temp);
    return;
  }

  for (var i = preIndex; i < source.length; i++) {
    genePattern(n, i, temp, source);
  }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	sc := NewScanner()

	n := sc.ReadInt()
	m := sc.ReadInt()
	q := sc.ReadInt()
	abcds := make([]ABCD, q)
	for i := 0; i < q; i++ {
		a := sc.ReadInt()
		b := sc.ReadInt()
		c := sc.ReadInt()
		d := sc.ReadInt()
		abcds[i] = ABCD{a, b, c, d}
	}

	cur := make(SeqA, n)
	maxScore := maxScoreOfSeqACombinations(abcds, 1, m, n, 0, cur, 0)

	fmt.Println(maxScore)
}

func maxScoreOfSeqACombinations(abcds []ABCD, min, max, n, pos int, cur SeqA, curMaxScore int) int {
	if pos == n {
		score := computeScore(abcds, cur)
		if score > curMaxScore {
			curMaxScore = score
		}
		return curMaxScore
	}

	for i := min; i <= max; i++ {
		cur[pos] = i
		curMaxScore = maxScoreOfSeqACombinations(abcds, i, max, n, pos+1, cur, curMaxScore)
	}
	return curMaxScore
}

func computeScore(abcds []ABCD, seqA SeqA) int {
	totalD := 0
	for _, abcd := range abcds {
		if seqA[abcd.B-1]-seqA[abcd.A-1] == abcd.C {
			totalD += abcd.D
		}
	}
	return totalD
}

type SeqA []int

type ABCD struct {
	A int
	B int
	C int
	D int
}

// util
// *   math/simple

func Abs(x int) int {
	if x >= 0 {
		return x
	}
	return -x
}

func Min(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}
	min := values[0]
	for _, v := range values {
		if v < min {
			min = v
		}
	}
	return min
}

func Max(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}
	max := values[0]
	for _, v := range values {
		if v > max {
			max = v
		}
	}
	return max
}

func Pow(base int, exponent uint) int {
	answer := 1
	for i := uint(0); i < exponent; i++ {
		answer *= base
	}
	return answer
}

// *   io

type Scanner struct {
	bufScanner *bufio.Scanner
}

func NewScanner() *Scanner {
	bufSc := bufio.NewScanner(os.Stdin)
	bufSc.Split(bufio.ScanWords)
	bufSc.Buffer(nil, 100000000)
	return &Scanner{bufSc}
}

func (sc *Scanner) ReadString() string {
	bufSc := sc.bufScanner
	bufSc.Scan()
	return bufSc.Text()
}

func (sc *Scanner) ReadInt() int {
	bufSc := sc.bufScanner
	bufSc.Scan()
	text := bufSc.Text()

	num, err := strconv.Atoi(text)
	if err != nil {
		panic(err)
	}
	return num
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	sc := NewScanner()

	n := sc.ReadInt()
	m := sc.ReadInt()
	q := sc.ReadInt()
	abcds := make([]ABCD, q)
	for i := 0; i < q; i++ {
		a := sc.ReadInt()
		b := sc.ReadInt()
		c := sc.ReadInt()
		d := sc.ReadInt()
		abcds[i] = ABCD{a, b, c, d}
	}

	maxScore := 0
	update := func(combi SeqA) {
		score := computeScore(abcds, combi)
		if score > maxScore {
			maxScore = score
		}
	}

	cur := make(SeqA, n)
	eachCombination(update, 1, m, n, 0, cur)

	fmt.Println(maxScore)
}

func eachCombination(callback func(SeqA), min, max, n, pos int, cur SeqA) {
	if pos == n {
		callback(cur)
		return
	}

	for i := min; i <= max; i++ {
		cur[pos] = i
		eachCombination(callback, i, max, n, pos+1, cur)
	}
}

func computeScore(abcds []ABCD, seqA SeqA) int {
	totalD := 0
	for _, abcd := range abcds {
		if seqA[abcd.B-1]-seqA[abcd.A-1] == abcd.C {
			totalD += abcd.D
		}
	}
	return totalD
}

type SeqA []int

type ABCD struct {
	A int
	B int
	C int
	D int
}

// util
// *   math/simple

func Abs(x int) int {
	if x >= 0 {
		return x
	}
	return -x
}

func Min(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}
	min := values[0]
	for _, v := range values {
		if v < min {
			min = v
		}
	}
	return min
}

func Max(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}
	max := values[0]
	for _, v := range values {
		if v > max {
			max = v
		}
	}
	return max
}

func Pow(base int, exponent uint) int {
	answer := 1
	for i := uint(0); i < exponent; i++ {
		answer *= base
	}
	return answer
}

// *   io

type Scanner struct {
	bufScanner *bufio.Scanner
}

func NewScanner() *Scanner {
	bufSc := bufio.NewScanner(os.Stdin)
	bufSc.Split(bufio.ScanWords)
	bufSc.Buffer(nil, 100000000)
	return &Scanner{bufSc}
}

func (sc *Scanner) ReadString() string {
	bufSc := sc.bufScanner
	bufSc.Scan()
	return bufSc.Text()
}

func (sc *Scanner) ReadInt() int {
	bufSc := sc.bufScanner
	bufSc.Scan()
	text := bufSc.Text()

	num, err := strconv.Atoi(text)
	if err != nil {
		panic(err)
	}
	return num
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	sc := NewScanner()

	n := sc.ReadInt()
	m := sc.ReadInt()
	q := sc.ReadInt()
	abcds := make([]ABCD, q)
	for i := 0; i < q; i++ {
		a := sc.ReadInt()
		b := sc.ReadInt()
		c := sc.ReadInt()
		d := sc.ReadInt()
		abcds[i] = ABCD{a, b, c, d}
	}

	maxScore := 0
	update := func(seqA SeqA) {
		score := computeScore(abcds, seqA)
		if score > maxScore {
			maxScore = score
		}
	}

	cur := make(SeqA, n)
	eachSeqA(update, 1, m, n, 0, cur)

	fmt.Println(maxScore)
}

func eachSeqA(callback func(SeqA), min, max, n, pos int, cur SeqA) {
	if pos == n {
		callback(cur)
		return
	}

	for i := min; i <= max; i++ {
		cur[pos] = i
		eachSeqA(callback, i, max, n, pos+1, cur)
	}
}

func computeScore(abcds []ABCD, seqA SeqA) int {
	totalD := 0
	for _, abcd := range abcds {
		if seqA[abcd.B-1]-seqA[abcd.A-1] == abcd.C {
			totalD += abcd.D
		}
	}
	return totalD
}

type SeqA []int

type ABCD struct {
	A int
	B int
	C int
	D int
}

// util
// *   math/simple

func Abs(x int) int {
	if x >= 0 {
		return x
	}
	return -x
}

func Min(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}
	min := values[0]
	for _, v := range values {
		if v < min {
			min = v
		}
	}
	return min
}

func Max(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}
	max := values[0]
	for _, v := range values {
		if v > max {
			max = v
		}
	}
	return max
}

func Pow(base int, exponent uint) int {
	answer := 1
	for i := uint(0); i < exponent; i++ {
		answer *= base
	}
	return answer
}

// *   io

type Scanner struct {
	bufScanner *bufio.Scanner
}

func NewScanner() *Scanner {
	bufSc := bufio.NewScanner(os.Stdin)
	bufSc.Split(bufio.ScanWords)
	bufSc.Buffer(nil, 100000000)
	return &Scanner{bufSc}
}

func (sc *Scanner) ReadString() string {
	bufSc := sc.bufScanner
	bufSc.Scan()
	return bufSc.Text()
}

func (sc *Scanner) ReadInt() int {
	bufSc := sc.bufScanner
	bufSc.Scan()
	text := bufSc.Text()

	num, err := strconv.Atoi(text)
	if err != nil {
		panic(err)
	}
	return num
}
//  [go]
package main

import (
	"fmt"
)

var n, m, q int
var abcd [][]int
var arrs [][]int
var memo map[int]map[string]bool = map[int]map[string]bool{}

func main() {
	fmt.Scan(&n, &m, &q)
	create(1, []int{})
	ans := 0
	abcd = make([][]int, q)
	for i := 0; i < q; i++ {
		abcd[i] = make([]int, 4)
		fmt.Scan(&abcd[i][0], &abcd[i][1], &abcd[i][2], &abcd[i][3])
	}
	for _, arr := range arrs {
		score := 0
		for _, seq := range abcd {
			if arr[seq[1]-1]-arr[seq[0]-1] == seq[2] {
				score += seq[3]
			}
		}
		if score > ans {
			ans = score
		}
	}
	fmt.Println(ans)
}

func create(i int, arr []int) {
	if memo[i][fmt.Sprintf("%v", arr)] {
		return
	}
	if len(arr) == n {
		arrs = append(arrs, arr)
		return
	}
	if i > m {
		return
	}
	if memo[i] == nil {
		memo[i] = map[string]bool{}
	}
	memo[i][fmt.Sprintf("%v", arr)] = true
	create(i+1, append([]int{}, arr...))
	create(i+1, append(arr, i))
	create(i, append(arr, i))
}
//  [go]
package main

import (
	"fmt"
	"strconv"
)


func score(A []int, a []int, b []int, c []int, d []int) int {
	score := 0
	for i := 0; i < len(a); i++ {
		if A[b[i]-1]-A[a[i]-1] == c[i] {
			score += d[i]
		}
	}
	return score
}
var max int
var memo map[string]bool
var N int
var M int
func memocheck (A []int) bool{
	n := len(A)
	set := ""
	for i:= 0; i<n; i++{
		set = set + strconv.Itoa(A[i])
	}
	if ok := memo[set]; ok{
		return memo[set]
	} else {
		memo[set] = true
		return false
	}
}
func dfs (A []int, a []int,b []int,c []int,d []int) {
	n := N
	point := score(A,a,b,c,d)
	if (point > max) {
		max = point
	}
	if memocheck(A) {
		return
	}
	//fmt.Printf("check", A,max)
	//fmt.Println("")
	for i := 0; i< n-1; i++ {
		 if(A[i]+1 <= A[i+1]) && A[i]+1 <= M {
			 prA := []int{}
		 	for j:=0; j<n; j++ {
		 		if i == j {
					prA = append(prA,A[j]+1)
				} else {
					prA = append(prA,A[j])
				}
			}
				// prA = append(prA,A[i]+1)
			//for j:= i+1; i<n; i++ {
			//	prA = append(prA,A[j])
			//}
		 	dfs(prA,a,b,c,d)
		 }
	}

	if (A[n-1]+1 <= M) {
		prA := []int{}
		for j:=0; j<n-1; j++ {
			prA = append(prA,A[j])
		}
		prA = append(prA, A[n-1]+1)
		dfs(prA,a,b,c,d)
	}
}

func main() {
	var Q int
	fmt.Scan(&N,&M,&Q)
	max = 0
	memo = map[string]bool{}
	a := make([]int, Q)
	b := make([]int, Q)
	c := make([]int, Q)
	d := make([]int, Q)
	result :=  make([]int, N)
	for i := 0; i < Q; i++ {
		fmt.Scan(&a[i],&b[i],&c[i],&d[i])
	}
	for i := 0; i < N; i++ {
		result[i] += 1
	}
	dfs(result,a,b,c,d)
	fmt.Println(max)
}
//  [go]
// +build ignore
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner() *Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &Scanner{sc}
}

func (s *Scanner) nextStr() string {
	s.sc.Scan()
	return s.sc.Text()
}

func (s *Scanner) nextInt() int {
	i, e := strconv.Atoi(s.nextStr())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *Scanner) nextRuneSlice() []byte {
	return []byte(s.nextStr())
}

func (s *Scanner) nextIntSlice(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextInt()
	}
	return res
}

func (s *Scanner) nextFloatSlice(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextFloat()
	}
	return res
}

func gcd(x, y int) int {
	if x%y != 0 {
		return gcd(y, x%y)
	}
	return y
}

func genAry(a []int, i int, j2 int, N int, M int, fn func([]int)) {
	if i >= N {
		fn(a)
		return
	}
	for j := j2; j <= M; j++ {
		a[i] = j
		genAry(a, i+1, j, N, M, fn)
	}
}

func run(input io.Reader, output io.Writer) int {
	sc := NewScanner()
	N := sc.nextInt()
	M := sc.nextInt()
	Q := sc.nextInt()
	q := make([]map[string]int, Q)
	for i := 0; i < Q; i++ {
		q[i] = make(map[string]int)
		q[i]["a"] = sc.nextInt()
		q[i]["b"] = sc.nextInt()
		q[i]["c"] = sc.nextInt()
		q[i]["d"] = sc.nextInt()
	}

	A := make([]int, N)
	max := 0
	genAry(A, 0, 1, N, M, func(B []int) {
		tmp := 0
		for i := 0; i < Q; i++ {
			a := q[i]["a"]
			b := q[i]["b"]
			c := q[i]["c"]
			d := q[i]["d"]
			if A[b-1]-A[a-1] == c {
				tmp += d
			}
		}
		if max < tmp {
			max = tmp
		}
	})

	fmt.Println(max)

	return 0
}

func main() {
	os.Exit(run(os.Stdin, os.Stdout))
}
//  [ruby]
N, M, Q = gets.split.map(&:to_i)
$query = Array.new(N).map { Array.new }

$<.read.split.map(&:to_i).each_slice(4) do |a, b, c, d|
    $query[b-1].push [a-1, b-1, c, d]
end


$key = Array.new(N)
@max = 0

def solve(index, last, value)
    if N <= index
        @max = value if @max < value
        return
    end
        
    last.upto(M) do |i|
        $key[index] = i
        plus = 0
        
        $query[index].each do |q|
            plus += q[3] if $key[q[1]] == $key[q[0]] + q[2]
        end
        
        solve(index + 1, i, value + plus)
    end
end
    
solve(0, 1, 0)

puts @max
//  [ruby]
$n, $m, q = gets.chomp.split(" ").map(&:to_i);
$c = 0

$query = Array.new($n)
$n.times do |i| 
  $query[i] = []
end
q.times do
  a, b, c, d = gets.chomp.split(" ").map(&:to_i);
  a-=1
  b-=1
  $query[b] = [] if $query[b].nil?
  $query[b] << [a ,b ,c, d]
end


$arr = Array.new($n, 0)
$max = 0

def bt (index, last, now)
  if index == $n
    $max = [now, $max].max
    #pp $arr
    return 1
  end
  (last..$m).each do |i|
    plus = 0
    $arr[index] = i
    $query[index].each do |query|
      plus += query[3] if ($arr[query[1]] - $arr[query[0]]) == query[2]
    end
    bt(index + 1, i, now + plus)
  end
end

bt(0, 1, 0)
puts $max
//  [ruby]
n,m,q=gets.split.map(&:to_i)
abcd=[]
q.times do
  abcd << gets.split.map(&:to_i)
end
max=0
[*1..n+m-2].combination(n-1) do |per|
  mi=[1]
  (n-1).times do |i|
    mi << per[i]-i
  end
  cnt=0
  abcd.each do |a,b,c,d|
    cnt+=d if mi[b-1]-mi[a-1]==c
  end
  max=cnt if cnt>max
end
puts max
//  [ruby]
N,M,Q = gets.split.map(&:to_i)
a = []
Q.times do |i|
  a[i] = gets.split.map(&:to_i)
end

def score(array,a)
  tmp = 0
  for ai,bi,ci,di in a
    tmp += di if array[bi-1] - array[ai-1] == ci
  end
  tmp
end

def dfs(array,a)
  l = array.length
  return score(array,a) if l == N
  result = 0
  l > 0 ? (prev_last = array[-1]) : (prev_last = 0)
  for v in prev_last...M
    array.push(v)
    result = [result, dfs(array,a)].max
    array.pop
  end
  result
end

puts dfs(Array.new,a)
//  [ruby]
n, m, q = gets.split.map &:to_i

abcds = q.times.map {gets.split.map &:to_i}
max = 0
seq = [1] * n
loop do
  sum = 0
  abcds.each do |abcd|
    a, b, c, d = abcd
    if seq[b-1] - seq[a-1] == c
      sum += d
    end
  end
  STDERR.puts "#{seq} : #{sum}"
  max = [max, sum].max
  
  # next
  i = n-1
  while i >= 0
    if seq[i] == m
      i -= 1
    else
      seq[i] += 1
      (i...n).each { |j| seq[j] = seq[i] }
      break
    end
  end
  if i < 0
    break
  end
end
p max
//  [ruby]
N,M,Q,*as=$<.read.split.map(&:to_i)
abcds = as.each_slice(4)

max = 0
(1..M).to_a.repeated_combination(N) do |arr|
    sum = 0
    abcds.each do |a,b,c,d|
        sum += d if arr[b-1] - arr[a-1] == c
    end
    max = sum if max < sum
end
puts max
//  [rust]
use proconio::input;

#[allow(unused_imports)]
use proconio::marker::{Bytes, Chars, Usize1};
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::ops::*;

#[derive(Clone, Debug, Default)]
struct Struct;

fn dfs(a: &mut Vec<usize>, i: usize, n:usize, m: usize, bq: &Vec<Vec<(usize, usize, i32, usize)>>, score:usize) -> usize {
    let mut val_to_score = vec![0; m + 1];
    for v in &bq[i] {
        let good_val = a[v.0] + v.2 as usize;
        if good_val <= m {
            val_to_score[good_val] += v.3;
        }
    }
    let mut max_score = 0;
    for val in a[i-1]..=m {
        if val == a[i-1] || val_to_score[val] != 0 {
            a[i] = val;
            if i == n-1 {
                max_score = max(max_score, score + val_to_score[val]);
            } else {
                max_score = max(max_score,dfs(a, i+1, n, m, bq, score + val_to_score[val]));
            }
        }
    }
    max_score
}

//#[proconio::fastout]
fn main() {
    input! {
        n: usize,
        m: usize,
        q: usize,
        v: [(Usize1,Usize1,i32,usize);q],
    }

    let mut bq = vec![Vec::new(); n];
    for i in 0..q {
        let b = v[i].1;
        bq[b].push(v[i]);
    }

    let mut a = vec![1; n];
    let ans = dfs(&mut a, 1, n, m, &bq, 0);

    println!("{}", ans);
}
//  [rust]
#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn dfs(
    array: &mut Vec<usize>,
    n: usize,
    cur: usize,
    queries: &Vec<Vec<(usize, usize, i64)>>,
    m: usize,
) -> i64 {
    if cur == n {
        return 0;
    }
    let mut cands_point = HashMap::new();
    cands_point.insert(array[cur - 1], 0);
    for &(a, c, d) in queries[cur].iter() {
        let cand = array[a] + c;
        if cand <= m && cand >= array[cur - 1] {
            *cands_point.entry(cand).or_insert(0) += d;
        }
    }
    let mut ret = 0;
    for &cand in cands_point.keys() {
        array[cur] = cand;
        let temp = dfs(array, n, cur + 1, queries, m);
        ret = max(ret, temp + cands_point[&cand]);
    }

    ret
}

fn main() {
    let v = read_vec::<usize>();
    let (n, m, q) = (v[0], v[1], v[2]);
    let mut queries = vec![vec![]; n];
    for i in 0..q {
        let v = read_vec::<i64>();
        let (a, b, c, d) = (v[0] as usize - 1, v[1] as usize - 1, v[2] as usize, v[3]);
        queries[b].push((a, c, d));
    }
    let mut array = vec![1; n];
    let ans = dfs(&mut array, n, 1, &queries, m);
    println!("{}", ans);
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}
//  [rust]
#![allow(non_snake_case)]
// 解説を見た。
use proconio::input;
// use std::collections::HashMap;

fn calc(_N: i64, _M: i64, _Q: i64, abcds: &[(i64, i64, i64, i64)], As: &[i64]) -> i64 {
    return abcds
        .iter()
        .map(|(a, b, c, d)| if As[*b as usize - 1] -
            As[*a as usize - 1] == *c
        {
            *d
        } else {
            0
        })
        .sum();
}

fn main() {
    input! {
        N: i64,
        M: i64,
        Q: i64,
        abcds: [(i64, i64, i64, i64); Q],
    }

    // Mが少ないから、全探索いけるのでは?
    // 単調非減少 10^10くらい? 間に合わじ
    // → 全探索で間に合うらしいです。まじ?

    // 数学の問題だね、重複ありの組み合わせは「しきり」を使って考える
    // 1 ||||| 2 3 4 5 6 7 8 9 ... (M-1)
    // (M + N - 1)_C_N
    // 最大で19C10 → 10万くらい これなら間に合うわー

    // うっ、どうやって書くんだ?
    // しきりを挟むindexをPsで表現する
    let mut stack: Vec<Vec<i64>> = Vec::new();
    stack.push(Vec::new());

    let mut ans = 0i64;

    // スタックからpopして、N個に満たなかったら単調非減少を維持しつつ新しい値をpushする
    while !stack.is_empty() {
        let top = stack.pop().unwrap();

        let len = top.len();
        if len == N as usize {
            // 解決フェーズ
            let As: Vec<i64> = top.iter()
                .enumerate()
                .map(|(ind, &val)| val - ind as i64 + 1)
                .collect();
            let score = calc(N, M, Q, &abcds, &As);

            if score > ans {
                ans = score;
            }
        } else {
            // 追加フェーズ
            let tail: Option<&i64> = if len == 0 { None } else { top.get(len - 1) };
            for i in (*tail.unwrap_or(&-1) + 1)..(N + M - 1) {
                // 新しい配列を生成する点に注意
                let mut new = top.clone();
                new.push(i);
                stack.push(new);
            }
        }

    }

    println!("{}", ans);
}
//  [swift]
let (n,m,q) = cin.triple
/// 111, 112, 113, 114
/// 222, 223, 224
/// 333, 334
/// 444

let X = (1...q).map {_ in cin.array}

var mmax = 0

func calc(_ A: [Int]) {
    var sum = 0
    for x in X {
        if A[x[1]-1] - A[x[0]-1] == x[2] {
            sum += x[3]
        }
    }
    mmax = max(mmax, sum)
}

func dfs(_ A: inout [Int]) {
    if A.count == n {
        calc(A)
        // print(A)
        return
    }

    let last = A.last ?? 1

    for v in (last...m) {
        A.append(v)
        dfs(&A)
        A.removeLast()
    }
}

var _A = [Int]()
dfs(&_A)

print(mmax)

import Foundation
#if os(Linux)
    import Glibc
#else
    import Darwin.C
#endif

enum cin {
    // 123
    static var int: Int { Int(readLine()!)! }
    // 12 23
    static var pair: (Int, Int) { let line = readLine()!.components(separatedBy: " "); return (Int(line[0])!, Int(line[1])!) }
    // 12 23 34
    static var triple: (Int, Int, Int) { let line = readLine()!.components(separatedBy: " "); return (Int(line[0])!, Int(line[1])!, Int(line[2])!) }
    // 12 23 34 45
    static var quadro: (Int, Int, Int, Int) { let line = readLine()!.components(separatedBy: " "); return (Int(line[0])!, Int(line[1])!, Int(line[2])!, Int(line[3])!) }
    // AtCoder
    static var str: String { readLine()! }
    // At Coder
    static var arrayStr: [String] { str.components(separatedBy: " ") }
    // 1 2 3 4
    static var array: [Int] { str.components(separatedBy: " ").map { Int($0)! } }
    // 1
    // 2
    // 3
    static func v_array(count: Int) -> [Int] { (0..<count).map { _ in int } }
}

/// ヘルパー関数ライブラリ
/// https://github.com/ankurp/Dollar
/// https://github.com/ankurp/Cent
extension Int {
    // 123 -> [1, 2, 3]
    var digits: [Int] { Array(String(self)).map { Int(String($0))! } }
}

extension Array where Element == Int {
    // [2, 1, 3, 2] -> 8
    var sum: Int { self.reduce(0, +) }
    // [2, 1, 3, 2] -> [1, 2, 2, 3]
    var orderBy: [Int] { sorted() }
    // [2, 1, 3, 2] -> [3, 2, 2, 1]
    var orderByDesc: [Int] { sorted(by: { $0 > $1 }) }
    // [2, 1, 3, 2] -> [2, 1, 3]
    var distinct: [Int] { Array(Set(self)) }
}

extension String {
    // e.g. cin.line.regex(match: "^(dream|dreamer|erase|eraser)*$")
    func regex(match pattern: String) -> Bool {
        let regex = try! NSRegularExpression(pattern: pattern)
        return regex.firstMatch(in: self, range: NSRange(location: 0, length: self.count)) != nil
    }
    // "ABC"[1] -> "B"
    subscript(i: Int) -> Character {
        get {
            self[index(at: i)]
        }
        set(char) {
            var characters = Array(self)
            characters[i] = char
            self = String(characters)
        }
    }
    func index(at offset: Int) -> String.Index { index(startIndex, offsetBy: offset) }
    // "ABC".swapAt(0, 1) -> "BAC"
    mutating func swapAt(_ index1: Int, _ index2: Int) {
        var characters = Array(self)
        characters.swapAt(index1, index2)
        self = String(characters)
    }
}
//  [swift]
//
//  main.swift
//  AtCorder
//
//  Created by KATSUHITO YASUMOTO on 2020/05/14.
//  Copyright © 2020 KATSUHITO YASUMOTO. All rights reserved.
//

import Foundation

let input_line = readLine()!.components(separatedBy: " ")

let N = Int(input_line[0])!
let M = Int(input_line[1])!
let Q = Int(input_line[2])!

var ans = 0

var inputSequences = [[Int]]()
for _ in 0..<Q {
    let input_line = readLine()!.components(separatedBy: " ")
    inputSequences.append(input_line.map({return Int($0)!}))
}

func dfs (_ arg: [Int]) {
    if arg.count == N+1 {
        var point = 0
        inputSequences.forEach({
            if arg[$0[1]] - arg[$0[0]] == $0[2] {
                point += $0[3]
            }
        })
        ans = max(point, ans)
        return
    }
    
    
    var increase = 0
    var last = arg.last!
    while last <= M {
        var sequence = arg
        sequence.append(sequence.last! + increase)
        dfs(sequence)
        increase += 1
        last += 1
    }
}
dfs([1])
print(ans)
//  [swift]
func readIntArray() -> [Int] {
    readLine()!.split(separator: " ").map({Int($0)!})
}

var line = readIntArray()
let (N, M, Q) = (line[0], line[1], line[2])

var queries: [[Int]] = (0..<Q).map({_ in readIntArray()})
var ans = 0

func dfs(_ A: [Int]) {
    if A.count == (N + 1) {
        ans = max(ans, score(A))
        return
    }
    
    var last = A.last!
    while last <= M {
        dfs(A + [last])
        last += 1
    }
}

func score(_ A: [Int]) -> Int {
    var score = 0
    (0..<Q).forEach({i in
        let query = queries[i]
        let (a, b, c, d) = (query[0], query[1], query[2], query[3])
        if (A[b] - A[a] == c) {
            score += d
        }
    })
    return score
}

dfs([1])
print(ans)
//  [swift]
let nmq = readLine()!.split(separator: " ").map { Int($0)! }
let (n, m, q) = (nmq[0], nmq[1], nmq[2])
var a = Array(repeating: 0, count: q)
var b = Array(repeating: 0, count: q)
var c = Array(repeating: 0, count: q)
var d = Array(repeating: 0, count: q)
(0..<q).forEach { i in
  let abcd = readLine()!.split(separator: " ").map { Int($0)! }
  a[i] = abcd[0] - 1
  b[i] = abcd[1] - 1
  c[i] = abcd[2]
  d[i] = abcd[3]
}

func combinations<T: Collection>(_ collection: T, _ length: Int) -> [[T.Element]]? {
  let collection = Array(collection)
  let count = collection.count
  if count < length { return nil }
  var dict = [Int: [Int: [[T.Element]]]]()
  func r(_ index: Int, _ length: Int) -> [[T.Element]] {
    if let result = dict[index]?[length] { return result }
    if length == 0 || index + length > count { return [[]] }
    let result = (index...(count-length)).flatMap { i in
      r(i + 1, length - 1).map { item in [collection[i]] + item }
    }
    dict[index] = dict[index] ?? [Int: [[T.Element]]]()
    dict[index]?[length] = result
    return result
  }
  return r(0, length)
}

let result = combinations(1...m+n-1, n)?.map {
  $0.enumerated().map { $1 - $0 }
}.map { (array: [Int]) -> Int in
  (0..<q).filter {
    array[b[$0]] - array[a[$0]] == c[$0]
  }.map { d[$0] }.reduce(0, +)
}.max() ?? -1

print(result)
//  [swift]
let nmq = readLine()!.split(separator: " ").map { Int($0)! }
let (n, m, q) = (nmq[0], nmq[1], nmq[2])
var a = Array(repeating: 0, count: q)
var b = Array(repeating: 0, count: q)
var c = Array(repeating: 0, count: q)
var d = Array(repeating: 0, count: q)
(0..<q).forEach { i in
  let abcd = readLine()!.split(separator: " ").map { Int($0)! }
  a[i] = abcd[0] - 1
  b[i] = abcd[1] - 1
  c[i] = abcd[2]
  d[i] = abcd[3]
}

func combinations<T: Collection>(_ collection: T, _ length: Int) -> [[T.Element]]? {
  let collection = Array(collection)
  let count = collection.count
  if count < length { return nil }
  var dict = [Int: [Int: [[T.Element]]]]()
  func r(_ index: Int, _ length: Int) -> [[T.Element]] {
    if let result = dict[index]?[length] { return result }
    if length == 0 || index + length > count { return [[]] }
    let result = (index...(count-length)).flatMap { i in
      r(i + 1, length - 1).map { item in [collection[i]] + item }
    }
    dict[index] = dict[index] ?? [Int: [[T.Element]]]()
    dict[index]?[length] = result
    return result
  }
  return r(0, length)
}

let result = combinations(1...m+n-1, n)?.map { (preS: [Int]) -> Int in
  let s = preS.enumerated().map { (i, element) in element - i }
  return (0..<q).filter {
    s[b[$0]] - s[a[$0]] == c[$0]
  }.map { d[$0] }.reduce(0, +)
}.max() ?? -1

print(result)
//  [swift]
let nmq = readLine()!.split(separator: " ").map { Int($0)! }
let (n, m, q) = (nmq[0], nmq[1], nmq[2])
var a = Array(repeating: 0, count: q)
var b = Array(repeating: 0, count: q)
var c = Array(repeating: 0, count: q)
var d = Array(repeating: 0, count: q)
for i in 0..<q {
  let abcd = readLine()!.split(separator: " ").map { Int($0)! }
  a[i] = abcd[0] - 1
  b[i] = abcd[1] - 1
  c[i] = abcd[2]
  d[i] = abcd[3]
}

func combinations<T: Collection>(_ collection: T, _ length: Int) -> [[T.Element]]? {
  let collection = Array(collection)
  let count = collection.count
  if count < length { return nil }
  var dict = [Int: [Int: [[T.Element]]]]()
  func r(_ index: Int, _ length: Int) -> [[T.Element]] {
    if let result = dict[index]?[length] { return result }
    if length == 0 || index + length > count { return [[]] }
    var result = [[T.Element]]()
    for i in index...(count-length) {
      result += r(i + 1, length - 1).map { [collection[i]] + $0 }
    }
    dict[index] = dict[index] ?? [Int: [[T.Element]]]()
    dict[index]?[length] = result
    return result
  }
  return r(0, length)
}

var result = Int()
combinations(1...m+n-1, n)?.forEach { preS in
  var counter = 0
  let s = preS.enumerated().map { (i, element) in element - i }
  for i in 0..<q where s[b[i]] - s[a[i]] == c[i] { counter += d[i] }
  if result < counter { result = counter }
}

print(result)